The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: C11 routing truth table across a fleet of keyed loopback providers
teknium1616e8d4df6b4
diff --git a/tests/e2e/core/tenancy/__init__.py b/tests/e2e/core/tenancy/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/e2e/core/tenancy/_routing_helpers.py b/tests/e2e/core/tenancy/_routing_helpers.pynew file mode 100644index 00000000000..87f23ae9ba3--- /dev/null+++ b/tests/e2e/core/tenancy/_routing_helpers.py@@ -0,0 +1,389 @@+"""Lane-private harness for the C11 routing truth table.++A ``Fleet`` is K real loopback provider hosts (``FakeLLMServer``), one per provider+identity, each accepting only its own randomly minted key. ``check_routing`` is the one+invariant every scenario shares: a request on a host the scenario did not select, or a+selected host receiving any bearer other than its own, is a credential leak.++Hermes itself runs for real in child processes (``hermes chat -q`` / ``hermes -z`` /+``python -m tui_gateway.entry``) with HOME and HERMES_HOME inside the test's tmp dir,+every credential/endpoint env var stripped, and only these fake hosts configured.+"""++from __future__ import annotations++import json+import os+import pwd+import queue+import secrets+import signal+import subprocess+import sys+import threading+import time+from dataclasses import dataclass, field+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import Any, Callable, Iterable++import yaml++from tests.fakes.fake_llm_provider import Error, FakeLLMServer, Text++REPO_ROOT = Path(__file__).resolve().parents[4]++# Env that could route or authenticate a child Hermes outside the fake fleet.+_STRIP_SUFFIXES = ("_API_KEY", "_TOKEN", "_BASE_URL", "_SECRET", "_ACCESS_KEY", "_KEY_ID")+_STRIP_PREFIXES = ("HERMES_", "OPENAI", "ANTHROPIC", "OPENROUTER", "AWS_", "AZURE_", "GOOGLE_",+ "GEMINI", "PYTEST_", "NOUS_", "XAI_", "LLM_", "CUSTOM_")+++def hermetic_env(home: Path, hermes_home: Path | None = None, proxy: str | None = None) -> dict[str, str]:+ real_home = Path(pwd.getpwuid(os.getuid()).pw_dir).resolve()+ fake = home.resolve()+ # The state-db guard is bypassed below, so prove first that this child can never reach the+ # real install: its HOME (and therefore every profile root) lives outside the real home.+ assert fake != real_home and real_home / ".hermes" not in (fake, *fake.parents), fake+ env = {k: v for k, v in os.environ.items()+ if not (k.endswith(_STRIP_SUFFIXES) or k.startswith(_STRIP_PREFIXES))}+ env.update(+ HOME=str(home),+ HERMES_HOME=str(hermes_home or home / ".hermes"),+ PYTHONPATH=str(REPO_ROOT),+ NO_COLOR="1",+ TERM="dumb",+ # A pytest-descendant child treats $HOME/.hermes/state.db as production; that HOME is ours.+ HERMES_STATE_DB_GUARD_BYPASS="1",+ )+ for var in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"):+ env.pop(var, None)+ if proxy:+ env.update(HTTP_PROXY=proxy, HTTPS_PROXY=proxy, ALL_PROXY=proxy, http_proxy=proxy, https_proxy=proxy,+ all_proxy=proxy, NO_PROXY="127.0.0.1,localhost", no_proxy="127.0.0.1,localhost")+ return env+++# Fleet --------------------------------------------------------------------------+++def _bearer(record: dict[str, Any]) -> str:+ auth = record.get("auth") or ""+ if auth.lower().startswith("bearer "):+ return auth[7:]+ return (record.get("headers") or {}).get("x-api-key", "") or auth+++@dataclass+class Fleet:+ """One FakeLLMServer per provider identity; every identity owns distinct secrets."""++ roles: Iterable[str]+ key_counts: dict[str, int] = field(default_factory=dict)+ servers: dict[str, FakeLLMServer] = field(init=False, default_factory=dict)+ keys: dict[str, tuple[str, ...]] = field(init=False, default_factory=dict)++ def __post_init__(self) -> None:+ for role in self.roles:+ n = self.key_counts.get(role, 1)+ self.keys[role] = tuple(f"sk-c11-{role}-{i}-{secrets.token_hex(6)}" for i in range(n))+ srv = FakeLLMServer(self._dispatch(role), api_key=self.keys[role],+ aux=self._aux(role), record_get=True)+ self.servers[role] = srv+ self._scripts: dict[str, Callable[[dict[str, Any]], Any]] = {}++ # scripting: a callable(record) -> Response per role; default answers name the host+ def script(self, role: str, responder: Callable[[dict[str, Any]], Any]) -> None:+ self._scripts[role] = responder++ def _dispatch(self, role: str) -> Callable[[dict[str, Any]], Any]:+ def respond(record: dict[str, Any]) -> Any:+ fn = self._scripts.get(role)+ resp = fn(record) if fn else None+ return resp if resp is not None else Text(f"answer-from-{role}")+ return respond++ def _aux(self, role: str) -> Callable[[dict[str, Any]], Any]:+ def respond(record: dict[str, Any]) -> Any:+ fn = self._scripts.get(f"{role}:aux")+ resp = fn(record) if fn else None+ return resp if resp is not None else Text(f"aux-from-{role}")+ return respond++ def key(self, role: str, i: int = 0) -> str:+ return self.keys[role][i]++ def url(self, role: str) -> str:+ return self.servers[role].base_url++ def start(self) -> "Fleet":+ for srv in self.servers.values():+ srv.start()+ return self++ def stop(self) -> None:+ for srv in self.servers.values():+ srv.stop()++ def marks(self) -> dict[str, int]:+ return {role: len(srv.requests) for role, srv in self.servers.items()}++ def since(self, marks: dict[str, int] | None = None) -> dict[str, list[dict[str, Any]]]:+ marks = marks or {}+ return {role: list(srv.requests[marks.get(role, 0):]) for role, srv in self.servers.items()}++ def owner_of(self, secret: str) -> str:+ for role, keys in self.keys.items():+ if secret in keys:+ return role+ return "<no identity>"+++def check_routing(+ fleet: Fleet,+ log: dict[str, list[dict[str, Any]]],+ expect: dict[str, Iterable[str]],+ must_hit: dict[str, int] | None = None,+) -> list[str]:+ """Return every routing violation in ``log`` (empty list == correct routing).++ ``expect`` maps each host the scenario may reach to the secrets it may carry there;+ ``must_hit`` maps hosts to the minimum number of chat POSTs they must have served.+ """+ allowed = {role: set(keys) for role, keys in expect.items()}+ problems: list[str] = []+ for role, records in log.items():+ for r in records:+ secret = _bearer(r)+ where = f"{r.get('kind')} {r.get('path')}"+ if r.get("kind") == "get":+ # Model-list/metadata probes carry no prompt: they may reach any configured host,+ # but never with another identity's key.+ owner = fleet.owner_of(secret)+ if secret and owner not in {role, "<no identity>"}:+ problems.append(f"LEAK: host '{role}' got {where} carrying the key of '{owner}' ({secret!r})")+ continue+ if role not in allowed:+ problems.append(f"LEAK: unselected host '{role}' got {where} carrying the key of "+ f"'{fleet.owner_of(secret)}' ({secret!r})")+ elif secret not in allowed[role]:+ problems.append(f"LEAK/WRONG KEY: host '{role}' got {where} carrying the key of "+ f"'{fleet.owner_of(secret)}' ({secret!r})")+ for role, n in (must_hit or {}).items():+ got = sum(1 for r in log.get(role, []) if r.get("kind") in {"main", "aux"})+ if got < n:+ problems.append(f"MISSING: host '{role}' served {got} chat request(s), expected >= {n}")+ return problems+++def describe(log: dict[str, list[dict[str, Any]]]) -> str:+ rows = [f" {role}: " + ", ".join(f"{r.get('kind')}[{_bearer(r)[:22]}]" for r in recs)+ for role, recs in log.items() if recs]+ return "\n".join(rows) or " (no requests anywhere)"+++# Egress trap ------------------------------------------------------------------------+++class EgressTrap:+ """HTTP(S)_PROXY for the child: records every non-loopback destination and refuses it.++ The fleet is reached directly (NO_PROXY=loopback), so anything arriving here is traffic to a+ host the scenario never configured -- e.g. a fall-through to the real OpenRouter/OpenAI API.+ """++ def __init__(self) -> None:+ self.attempts: list[tuple[str, str]] = []+ trap = self++ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *_a: object) -> None:+ pass++ def _refuse(self) -> None:+ target = self.path if self.command != "CONNECT" else f"https://{self.path}"+ trap.attempts.append((self.command, target))+ self.send_response(403)+ self.send_header("Content-Length", "0")+ self.send_header("Connection", "close")+ self.end_headers()+ self.close_connection = True++ do_CONNECT = do_GET = do_POST = do_PUT = do_HEAD = _refuse # noqa: N815++ self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ self._server.daemon_threads = True+ threading.Thread(target=self._server.serve_forever, daemon=True, name="c11-egress").start()++ @property+ def url(self) -> str:+ return f"http://127.0.0.1:{self._server.server_address[1]}"++ def stop(self) -> None:+ self._server.shutdown()+ self._server.server_close()+++def inference_hosts() -> frozenset[str]:+ """Hostnames of every inference API Hermes itself knows (its provider registry + OpenRouter).++ Read from the product, never copied: a CONNECT to one of these from a scenario that+ configured only loopback hosts is a prompt leaving for a real provider.+ """+ from urllib.parse import urlparse++ from hermes_cli.auth import PROVIDER_REGISTRY+ from hermes_constants import OPENROUTER_BASE_URL++ urls = [getattr(p, "inference_base_url", "") or "" for p in PROVIDER_REGISTRY.values()] + [OPENROUTER_BASE_URL]+ return frozenset(h for h in (urlparse(u).hostname for u in urls) if h and h not in {"127.0.0.1", "localhost"})+++# HERMES_HOME writing ------------------------------------------------------------+++def write_home(hermes_home: Path, config: dict[str, Any], env: dict[str, str],+ auth: dict[str, Any] | None = None) -> Path:+ hermes_home.mkdir(parents=True, exist_ok=True)+ (hermes_home / "config.yaml").write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")+ (hermes_home / ".env").write_text("".join(f"{k}={v}\n" for k, v in env.items()), encoding="utf-8")+ if auth is not None:+ (hermes_home / "auth.json").write_text(json.dumps(auth), encoding="utf-8")+ return hermes_home+++def pool_auth(provider: str, keys: Iterable[str]) -> dict[str, Any]:+ return {"version": 1, "providers": {}, "credential_pool": {provider: [+ {"id": f"k{i}", "label": f"key-{i}", "auth_type": "api_key", "priority": i,+ "source": "manual", "access_token": key}+ for i, key in enumerate(keys)+ ]}}+++# Child Hermes processes ---------------------------------------------------------+++@dataclass+class RunResult:+ argv: list[str]+ rc: int | None+ stdout: str+ stderr: str+ seconds: float+++def run_hermes(argv: list[str], home: Path, *, hermes_home: Path | None = None, proxy: str | None = None,+ timeout: float = 240.0) -> RunResult:+ """Run the real ``hermes`` entry point in its own process group; kill only that group."""+ start = time.monotonic()+ proc = subprocess.Popen(+ [sys.executable, "-m", "hermes_cli.main", *argv],+ cwd=str(home), env=hermetic_env(home, hermes_home, proxy), stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True,+ )+ try:+ out, err = proc.communicate(timeout=timeout)+ except subprocess.TimeoutExpired:+ _kill_group(proc)+ out, err = proc.communicate()+ err += f"\n[c11 harness] killed after {timeout}s"+ _kill_group(proc) # reap any grandchild left in our own session+ return RunResult(argv, proc.returncode, out, err, time.monotonic() - start)+++def _kill_group(proc: subprocess.Popen) -> None:+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except (ProcessLookupError, PermissionError):+ pass+++class TuiGateway:+ """The real stdio JSON-RPC backend (``python -m tui_gateway.entry``) the TUI/Desktop drive."""++ def __init__(self, home: Path, proxy: str | None = None) -> None:+ self.home = home+ self._stderr = open(home / "tui_gateway.stderr.log", "w", encoding="utf-8") # noqa: SIM115+ self.proc = subprocess.Popen(+ [sys.executable, "-m", "tui_gateway.entry"], cwd=str(home), env=hermetic_env(home, proxy=proxy),+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self._stderr, text=True, bufsize=1,+ start_new_session=True,+ )+ self._q: queue.Queue[dict[str, Any]] = queue.Queue()+ self._rid = 0+ self.seen: list[dict[str, Any]] = []+ threading.Thread(target=self._read, daemon=True, name="c11-tui-reader").start()++ def _read(self) -> None:+ assert self.proc.stdout is not None+ for line in self.proc.stdout:+ try:+ self._q.put(json.loads(line))+ except json.JSONDecodeError:+ continue++ def wait(self, pred: Callable[[dict[str, Any]], bool], timeout: float = 120.0) -> dict[str, Any]:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if self.proc.poll() is not None and self._q.empty():+ break+ try:+ msg = self._q.get(timeout=0.25)+ except queue.Empty:+ continue+ self.seen.append(msg)+ if pred(msg):+ return msg+ tail = [(m.get("method"), (m.get("params") or {}).get("type"), m.get("id")) for m in self.seen[-25:]]+ raise AssertionError(f"tui_gateway: condition not met within {timeout}s (rc={self.proc.poll()}); "+ f"last frames {tail}")++ def seen_or_wait(self, pred: Callable[[dict[str, Any]], bool], timeout: float = 120.0) -> dict[str, Any]:+ """Like ``wait`` but also satisfied by a frame already consumed (events may race a turn's end)."""+ return next((m for m in self.seen if pred(m)), None) or self.wait(pred, timeout)++ @staticmethod+ def event(kind: str, sid: str | None = None) -> Callable[[dict[str, Any]], bool]:+ def pred(m: dict[str, Any]) -> bool:+ p = m.get("params") or {}+ return m.get("method") == "event" and p.get("type") == kind and (sid is None or p.get("session_id") == sid)+ return pred++ def call(self, method: str, params: dict[str, Any], timeout: float = 120.0) -> dict[str, Any]:+ self._rid += 1+ rid = self._rid+ assert self.proc.stdin is not None+ self.proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}) + "\n")+ self.proc.stdin.flush()+ return self.wait(lambda m: m.get("id") == rid and "method" not in m, timeout)++ def turn(self, sid: str, text: str, timeout: float = 120.0) -> dict[str, Any]:+ """Submit one prompt and wait for the turn's terminal event (complete or error)."""+ reply = self.call("prompt.submit", {"session_id": sid, "text": text})+ assert "result" in reply, f"prompt.submit refused: {reply}"+ return self.wait(lambda m: self.event("message.complete", sid)(m) or self.event("error", sid)(m), timeout)++ def close(self) -> None:+ try:+ if self.proc.stdin:+ self.proc.stdin.close()+ self.proc.wait(timeout=30)+ except (subprocess.TimeoutExpired, OSError, ValueError):+ pass+ _kill_group(self.proc)+ try:+ self.proc.wait(timeout=10)+ except subprocess.TimeoutExpired:+ pass+ self._stderr.close()+++def always(resp_factory: Callable[[], Any]) -> Callable[[dict[str, Any]], Any]:+ return lambda _record: resp_factory()+++def reject_key(bad_key: str, status: int) -> Callable[[dict[str, Any]], Any]:+ """Answer ``status`` for requests carrying ``bad_key`` (a pooled key that is rate limited)."""+ return lambda record: Error(status, "scripted pool-key failure") if _bearer(record) == bad_key else Nonediff --git a/tests/e2e/core/tenancy/test_routing_truth_table.py b/tests/e2e/core/tenancy/test_routing_truth_table.pynew file mode 100644index 00000000000..ea153146232--- /dev/null+++ b/tests/e2e/core/tenancy/test_routing_truth_table.py@@ -0,0 +1,384 @@+"""C11 routing truth table: every config shape users write routes the prompt AND the key to+exactly one host.++Class: provider / model routing and credential resolution (issue_classes.md C11). Users hit it+as "I picked my custom provider and the prompt went to the default cloud", "`-m alias` sent the+alias key to the wrong host" (#103933/#107191/#109440), "a bare custom provider fell through to a+stale OPENAI_BASE_URL", "fallback shipped the primary key to the fallback host", "a rate-limited+pool key spilled onto another provider".++Harness: ``Fleet`` stands up one real loopback OpenAI-compatible host per provider identity+(main, alias, named, legacy, fallback, pool, aux, deleg, profile, plus the ambient+env-configured identities ``decoy`` = OPENAI_BASE_URL/OPENAI_API_KEY, ``cloud`` =+OPENROUTER_BASE_URL/OPENROUTER_API_KEY and ``vendor`` = ANTHROPIC_API_KEY). Each accepts only its+own random key. A loopback CONNECT trap (HTTPS_PROXY) records any egress to a real inference API. EVERY scenario+configures ALL identities (the full config a real user accumulates) and differs only in the+selection, so a misroute always has somewhere to land and be caught. Hermes runs for real in a+child process (``hermes chat -q``, ``hermes -z``, the stdio ``tui_gateway`` the TUI/Desktop+drive) with a tmp HOME/HERMES_HOME and every credential env var stripped.++One invariant (``check_routing``) after every leg: requests exist only on the selected hosts,+each carrying only that host's own key, and the answer the user sees came from that host.+"""++from __future__ import annotations++import concurrent.futures as cf+import copy+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Callable+from urllib.parse import urlparse++import pytest++from tests.fakes.fake_llm_provider import MODEL_ID, Error, ToolCall++from ._routing_helpers import (+ EgressTrap,+ Fleet,+ RunResult,+ TuiGateway,+ always,+ check_routing,+ describe,+ inference_hosts,+ pool_auth,+ reject_key,+ run_hermes,+ write_home,+)++ROLES = ("main", "alias", "named", "legacy", "fallback", "pool", "aux", "deleg", "profile", "decoy", "cloud", "vendor")+Q = ["chat", "-q", "hello"]+++def base_config(f: Fleet) -> tuple[dict[str, Any], dict[str, str]]:+ """Every identity configured at once; scenarios only change what is SELECTED."""+ config: dict[str, Any] = {+ "model": {"provider": "custom", "base_url": f.url("main"), "default": "model-main",+ "key_env": "C11_MAIN_KEY", "context_length": 128000},+ "providers": {+ "named-host": {"name": "NamedHost", "base_url": f.url("named"), "key_env": "C11_NAMED_KEY",+ "model": "model-named"},+ "pool-host": {"name": "PoolHost", "base_url": f.url("pool"), "model": "model-pool"},+ },+ "custom_providers": [+ {"name": "legacy-host", "base_url": f.url("legacy"), "api_key": f.key("legacy"), "model": "model-legacy"},+ ],+ "model_aliases": {+ "alias-host": {"model": "model-alias", "provider": "custom", "base_url": f.url("alias"),+ "api_key": f.key("alias")},+ "alias-env": {"model": "model-alias-env", "provider": "custom", "base_url": f.url("alias"),+ "key_env": "C11_ALIAS_KEY"},+ },+ "agent": {"api_max_retries": 1},+ }+ env = {+ "C11_MAIN_KEY": f.key("main"),+ "C11_NAMED_KEY": f.key("named"),+ "C11_ALIAS_KEY": f.key("alias"),+ "C11_FALLBACK_KEY": f.key("fallback"),+ # Ambient identities a real .env carries: a routing bug that "falls back to the default+ # provider" lands on one of these two hosts and is caught.+ "OPENAI_API_KEY": f.key("decoy"),+ "OPENAI_BASE_URL": f.url("decoy"),+ "OPENROUTER_API_KEY": f.key("cloud"),+ "OPENROUTER_BASE_URL": f.url("cloud"),+ # A built-in vendor key with no host of its own: it must never appear on ANY fleet host.+ "ANTHROPIC_API_KEY": f.key("vendor"),+ }+ return config, env+++# Scenario table -------------------------------------------------------------------+++@dataclass+class Leg:+ argv: list[str]+ hosts: tuple[str, ...] # hosts this leg may reach (each with its own key only)+ must_hit: dict[str, int] = field(default_factory=dict)+ answer_from: str | None = None # host whose answer the user must see (rc 0)+ rc: str = "ok" # ok | fail | any+ profile: str | None = None # run with HERMES_HOME = profiles/<name>+++@dataclass+class Case:+ id: str+ legs: list[Leg]+ setup: Callable[[dict[str, Any], dict[str, str], Fleet], dict[str, Any] | None] = lambda c, e, f: None+ key_counts: dict[str, int] = field(default_factory=dict)+ profiles: Callable[[Fleet], dict[str, tuple[dict[str, Any], dict[str, str]]]] = lambda f: {}+ # extra ordered-key expectation on one host: (host, [key indexes in first-seen order])+ key_order: tuple[str, list[int]] | None = None+++def _model(**block: Any) -> Callable[[dict[str, Any], dict[str, str], Fleet], None]:+ def setup(c: dict[str, Any], _e: dict[str, str], _f: Fleet) -> None:+ c["model"] = {"context_length": 128000, **block}+ return setup+++def _main_api_key_literal(c: dict[str, Any], e: dict[str, str], f: Fleet) -> None:+ c["model"].pop("key_env")+ c["model"]["api_key"] = f.key("main")+ e.pop("C11_MAIN_KEY")+++def _bare_custom(c: dict[str, Any], e: dict[str, str], _f: Fleet) -> None:+ c["model"] = {"provider": "custom", "default": "model-main", "context_length": 128000}+ # Bare custom + an OpenRouter key/mirror is a deliberate contract (it resolves to OpenRouter,+ # tests/hermes_cli/test_runtime_provider_resolution.py); with neither, nothing may be reached+ # -- not the env OPENAI_BASE_URL decoy, not the real OpenRouter API (egress trap).+ e.pop("OPENROUTER_BASE_URL")+ e.pop("OPENROUTER_API_KEY")+++def _fallback_named_after(status: int) -> Callable[[dict[str, Any], dict[str, str], Fleet], None]:+ def setup(c: dict[str, Any], _e: dict[str, str], f: Fleet) -> None:+ c["fallback_providers"] = [{"provider": "named-host", "model": "model-named"}]+ f.script("main", always(lambda: Error(status, "scripted primary failure")))+ return setup+++def _fallback_custom_after(status: int) -> Callable[[dict[str, Any], dict[str, str], Fleet], None]:+ def setup(c: dict[str, Any], _e: dict[str, str], f: Fleet) -> None:+ c["fallback_providers"] = [{"provider": "custom", "base_url": f.url("fallback"),+ "key_env": "C11_FALLBACK_KEY", "model": "model-fallback"}]+ f.script("main", always(lambda: Error(status, "scripted primary failure")))+ return setup+++def _pool(n_keys: int, *, first_key_status: int | None, all_fail: bool = False):+ def setup(c: dict[str, Any], _e: dict[str, str], f: Fleet) -> dict[str, Any]:+ c["model"] = {"provider": "pool-host", "default": "model-pool", "context_length": 128000}+ c["agent"]["api_max_retries"] = 3 # rate limits retry once, then rotate+ if all_fail:+ f.script("pool", always(lambda: Error(429, "scripted pool exhaustion")))+ elif first_key_status is not None:+ f.script("pool", reject_key(f.key("pool", 0), first_key_status))+ return pool_auth("pool-host", f.keys["pool"][:n_keys])+ return setup+++def _aux_title_endpoint(c: dict[str, Any], _e: dict[str, str], f: Fleet) -> None:+ c["auxiliary"] = {"title_generation": {"base_url": f.url("aux"), "api_key": f.key("aux"), "model": "model-aux"}}+++def _aux_bare_custom(c: dict[str, Any], e: dict[str, str], _f: Fleet) -> None:+ # Aux task pinned to bare ``custom`` while no custom endpoint exists anywhere (see _bare_custom):+ # the title call must not ride the env OPENAI_BASE_URL decoy.+ c["model"] = {"provider": "named-host", "default": "model-named", "context_length": 128000}+ c["auxiliary"] = {"title_generation": {"provider": "custom", "model": "model-aux"}}+ e.pop("OPENROUTER_BASE_URL")+ e.pop("OPENROUTER_API_KEY")+++def _delegate_first(f: Fleet) -> None:+ calls = {"n": 0}++ def respond(_record: dict[str, Any]) -> Any:+ calls["n"] += 1+ if calls["n"] == 1:+ return ToolCall("delegate_task", {"goal": "Reply with the single word ok.", "context": "none"})+ return None+ f.script("main", respond)+++def _delegation_endpoint(c: dict[str, Any], _e: dict[str, str], f: Fleet) -> None:+ c["delegation"] = {"base_url": f.url("deleg"), "api_key": f.key("deleg"), "model": "model-deleg"}+ _delegate_first(f)+++def _delegation_named(c: dict[str, Any], _e: dict[str, str], f: Fleet) -> None:+ c["delegation"] = {"provider": "named-host", "model": "model-named"}+ _delegate_first(f)+++def _delegation_openai_alias(c: dict[str, Any], e: dict[str, str], f: Fleet) -> None:+ # ``provider: openai`` = the user's OPENAI_BASE_URL/OPENAI_API_KEY pair (here: the deleg host).+ e["OPENAI_BASE_URL"], e["OPENAI_API_KEY"] = f.url("deleg"), f.key("deleg")+ c["delegation"] = {"provider": "openai", "model": "model-deleg"}+ _delegate_first(f)+++def _profile_work(f: Fleet) -> dict[str, tuple[dict[str, Any], dict[str, str]]]:+ config, env = base_config(f)+ config["model"] = {"provider": "custom", "base_url": f.url("profile"), "default": "model-profile",+ "key_env": "C11_PROFILE_KEY", "context_length": 128000}+ env = {k: v for k, v in env.items() if k != "C11_MAIN_KEY"}+ env["C11_PROFILE_KEY"] = f.key("profile")+ return {"work": (config, env)}+++CASES: list[Case] = [+ Case("custom_base_url_key_env", [Leg(Q, ("main",), {"main": 1}, "main")]),+ Case("custom_base_url_api_key_literal", [Leg(Q, ("main",), {"main": 1}, "main")], _main_api_key_literal),+ Case("bare_custom_without_base_url_fails_fast", [Leg(Q, (), rc="fail")], _bare_custom),+ Case("named_providers_entry_key_env",+ [Leg(Q, ("named",), {"named": 1}, "named")], _model(provider="named-host", default="model-named")),+ Case("legacy_custom_providers_entry_api_key",+ [Leg(Q, ("legacy",), {"legacy": 1}, "legacy")], _model(provider="custom:legacy-host", default="model-legacy")),+ Case("alias_startup_q_api_key", [Leg([*Q, "-m", "alias-host"], ("alias",), {"alias": 1}, "alias")]),+ Case("alias_startup_q_key_env", [Leg([*Q, "-m", "alias-env"], ("alias",), {"alias": 1}, "alias")]),+ Case("alias_startup_oneshot_z", [Leg(["-z", "hello", "-m", "alias-host"], ("alias",), {"alias": 1}, "alias")]),+ Case("fallback_named_after_401",+ [Leg(Q, ("main", "named"), {"main": 1, "named": 1}, "named")], _fallback_named_after(401)),+ Case("fallback_custom_after_429",+ [Leg(Q, ("main", "fallback"), {"main": 1, "fallback": 1}, "fallback")], _fallback_custom_after(429)),+ Case("pool_two_keys_429_rotates_on_same_host",+ [Leg(Q, ("pool",), {"pool": 2}, "pool")], _pool(2, first_key_status=429), key_counts={"pool": 2},+ key_order=("pool", [0, 1])),+ Case("pool_single_key_exhausted_no_spill",+ [Leg(Q, ("pool",), {"pool": 1}, rc="any")], _pool(1, first_key_status=None, all_fail=True)),+ Case("profile_override_routes_per_profile",+ [Leg(Q, ("main",), {"main": 1}, "main"),+ Leg(["-p", "work", *Q], ("profile",), {"profile": 1}, "profile")],+ profiles=_profile_work),+ Case("aux_bare_custom_never_reaches_env_openai_base_url",+ [Leg(Q, ("named",), {"named": 1}, "named")], _aux_bare_custom),+ Case("aux_title_endpoint_separate_from_main",+ [Leg(Q, ("main", "aux"), {"main": 1, "aux": 1}, "main")], _aux_title_endpoint),+ Case("delegation_endpoint_child_routed",+ [Leg(Q, ("main", "deleg"), {"main": 2, "deleg": 1}, "main")], _delegation_endpoint),+ Case("delegation_named_provider_child_routed",+ [Leg(Q, ("main", "named"), {"main": 2, "named": 1}, "main")], _delegation_named),+ Case("delegation_provider_openai_alias_child_routed",+ [Leg(Q, ("main", "deleg"), {"main": 2, "deleg": 1}, "main")], _delegation_openai_alias),+]+++# Execution ------------------------------------------------------------------------+++@dataclass+class LegOutcome:+ leg: Leg+ run: RunResult+ log: dict[str, list[dict[str, Any]]]+ egress: list[tuple[str, str]]+++def _run_case(case: Case, root: Path) -> tuple[Fleet, list[LegOutcome]]:+ fleet = Fleet(ROLES, key_counts=case.key_counts).start()+ trap = EgressTrap()+ try:+ home = root / case.id / "home"+ config, env = base_config(fleet)+ auth = case.setup(config, env, fleet)+ write_home(home / ".hermes", config, env, auth)+ for name, (pconfig, penv) in case.profiles(fleet).items():+ write_home(home / ".hermes" / "profiles" / name, pconfig, penv)+ outcomes = []+ for leg in case.legs:+ marks, egress_mark = fleet.marks(), len(trap.attempts)+ hermes_home = home / ".hermes" / "profiles" / leg.profile if leg.profile else None+ run = run_hermes(leg.argv, home, hermes_home=hermes_home, proxy=trap.url)+ outcomes.append(LegOutcome(leg, run, fleet.since(marks), trap.attempts[egress_mark:]))+ return fleet, outcomes+ finally:+ fleet.stop()+ trap.stop()++[email protected](scope="module")+def cli_outcomes(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Any]:+ """All CLI scenarios run concurrently (each owns its own fleet and HOME)."""+ root = tmp_path_factory.mktemp("c11-cli")+ with cf.ThreadPoolExecutor(max_workers=6, thread_name_prefix="c11-case") as pool:+ futures = {case.id: pool.submit(_run_case, case, root) for case in CASES}+ return {cid: fut for cid, fut in futures.items()}++[email protected]("case", CASES, ids=[c.id for c in CASES])+def test_cli_routing_truth_table(case: Case, cli_outcomes: dict[str, Any]) -> None:+ fleet, outcomes = cli_outcomes[case.id].result(timeout=900)+ for i, out in enumerate(outcomes):+ leg, run = out.leg, out.run+ ctx = (f"[{case.id} leg {i}: hermes {' '.join(leg.argv)}] rc={run.rc} ({run.seconds:.1f}s)\n"+ f"requests:\n{describe(out.log)}\nstdout tail:\n{run.stdout[-1500:]}\nstderr tail:\n{run.stderr[-1500:]}")+ problems = check_routing(fleet, out.log, {h: fleet.keys[h] for h in leg.hosts}, leg.must_hit)+ assert not problems, "\n".join(problems) + "\n" + ctx+ if leg.rc == "ok":+ assert run.rc == 0, ctx+ elif leg.rc == "fail":+ assert run.rc != 0, "expected a fail-fast exit\n" + ctx+ if leg.answer_from:+ assert f"answer-from-{leg.answer_from}" in run.stdout, ctx+ leaked = [t for _m, t in out.egress if urlparse(t).hostname in inference_hosts()]+ assert not leaked, f"prompt egress to a real inference API: {leaked}\n{ctx}"+ if case.key_order:+ host, order = case.key_order+ seen: list[str] = []+ for r in (r for out in outcomes for r in out.log[host] if r["kind"] == "main"):+ if not seen or seen[-1] != r["auth"]:+ seen.append(r["auth"])+ assert seen == [f"Bearer {fleet.key(host, i)}" for i in order], (+ f"{host} main-request keys in order: {seen}")+++# Mid-session /model switches through the real tui_gateway (TUI / Desktop backend) -------------+++@dataclass+class Switch:+ value: str | None # config.set model value; None = no switch (first turn)+ host: str # host this turn must land on, with its own key only+ ok: bool = True # False: the turn is expected to fail (e.g. exhausted pool)+ keyless: bool = False # the host may also see NO credential (withholding a key is not a leak)+++def test_tui_gateway_model_switch_routing(tmp_path: Path) -> None:+ """One live session walks the switch matrix; after every switch the next turn lands on+ exactly the selected host with exactly its key, and nothing reaches any other host."""+ fleet = Fleet(ROLES).start()+ trap = EgressTrap()+ home = tmp_path / "home"+ config, env = base_config(fleet)+ # Built-in vendor label + foreign host, no key: ANTHROPIC_API_KEY must stay home (#28660).+ config["model_aliases"]["builtin-label-lan"] = {+ "model": MODEL_ID, "provider": "anthropic", "base_url": fleet.url("alias")} # id the host lists+ pool_state = {"fail": False}+ fleet.script("pool", lambda _r: Error(429, "scripted pool exhaustion") if pool_state["fail"] else None)+ write_home(home / ".hermes", config, env, pool_auth("pool-host", fleet.keys["pool"]))+ gw = TuiGateway(home, proxy=trap.url)+ try:+ gw.wait(gw.event("gateway.ready"), timeout=120)+ created = gw.call("session.create", {"cols": 100})+ sid = created["result"]["session_id"]+ legs = [+ Switch(None, "main"),+ Switch("alias-host", "alias"),+ Switch("model-named --provider named-host", "named"),+ Switch("model-legacy --provider custom:legacy-host", "legacy"),+ Switch("alias-env", "alias"),+ Switch("model-alias --provider named-host", "named"),+ Switch("builtin-label-lan", "alias", ok=False, keyless=True),+ Switch("model-legacy --provider custom:legacy-host", "legacy"),+ Switch("model-pool --provider pool-host", "pool", ok=False),+ Switch(None, "pool"),+ ]+ for i, leg in enumerate(legs):+ marks = fleet.marks()+ if leg.value:+ reply = gw.call("config.set", {"session_id": sid, "key": "model", "value": leg.value})+ assert "result" in reply, f"leg {i} switch {leg.value!r} refused: {reply}"+ pool_state["fail"] = leg.host == "pool" and not leg.ok+ done = gw.turn(sid, f"turn {i}")+ if i == 0:+ gw.seen_or_wait(gw.event("session.title", sid), timeout=120) # first-turn aux call settles+ log = fleet.since(marks)+ payload = (done.get("params") or {}).get("payload") or {}+ ctx = f"leg {i} ({leg.value!r} -> {leg.host}): {done.get('params', {}).get('type')} {str(payload)[:300]}\n{describe(log)}"+ print(ctx)+ allowed = {*fleet.keys[leg.host], *(("", "no-key-required") if leg.keyless else ())}+ problems = check_routing(fleet, log, {leg.host: allowed}, {leg.host: 1})+ assert not problems, "\n".join(problems) + "\n" + ctx+ if leg.ok:+ assert payload.get("text") == f"answer-from-{leg.host}", ctx+ finally:+ gw.close()+ fleet.stop()+ trap.stop()diff --git a/tests/fakes/fake_llm_provider.py b/tests/fakes/fake_llm_provider.pyindex 6c0065aa626..200d75ccd47 100644--- a/tests/fakes/fake_llm_provider.py+++ b/tests/fakes/fake_llm_provider.py@@ -126,14 +126,20 @@ class FakeLLMServer:*,default_text: str = "ok",aux: Responder | None = None,- api_key: str | None = None,+ api_key: str | list[str] | tuple[str, ...] | frozenset[str] | None = None,+ record_get: bool = False,prompt_tokens_fn: Callable[[dict[str, Any]], int] | None = None,) -> None:self._script: list[Response] = list(script) if isinstance(script, list) else []self._responder: Responder | None = script if callable(script) else Noneself.default_text = default_textself._aux = aux or (lambda _req: Text("Fake summary of the earlier conversation."))- self.expected_api_key = api_key+ # ``api_key`` may name several accepted keys (a credential pool on one host).+ self.expected_api_key = api_key if isinstance(api_key, str) or api_key is None else None+ self.accepted_api_keys: frozenset[str] | None = (+ None if api_key is None else frozenset([api_key] if isinstance(api_key, str) else api_key))+ # Opt-in so existing ``requests`` counts stay main/aux POSTs only.+ self.record_get = record_get# Optional: derive reported ``usage.prompt_tokens`` from each request body (so token-driven# logic such as compaction triggers sees a realistic, growing count instead of a constant).self.prompt_tokens_fn = prompt_tokens_fn@@ -226,6 +232,12 @@ def _handler_for(server: FakeLLMServer) -> type[BaseHTTPRequestHandler]:self.wfile.write(body)def do_GET(self) -> None: # noqa: N802+ if server.record_get:+ with server._lock:+ server.requests.append({+ "path": self.path, "kind": "get", "auth": self.headers.get("Authorization", ""),+ "headers": {k.lower(): v for k, v in self.headers.items()}, "body": None, "t": time.time(),+ })if self.path.rstrip("/").endswith("/models"):self._send_json(200, {"object": "list", "data": [{"id": MODEL_ID, "object": "model", "context_length": 128000},@@ -252,7 +264,8 @@ def _handler_for(server: FakeLLMServer) -> type[BaseHTTPRequestHandler]:}with server._lock:server.requests.append(record)- if server.expected_api_key is not None and auth != f"Bearer {server.expected_api_key}":+ accepted = server.accepted_api_keys+ if accepted is not None and auth not in {f"Bearer {k}" for k in accepted}:self._send_json(401, {"error": {"message": "invalid api key", "type": "authentication_error"}})returnif not self.path.rstrip("/").endswith("/chat/completions"):