Skip to content

Commit 6b15092

Browse files
authored
Merge pull request #1211 from BitterSecurity/fix/proxy-key-transport-settings-20261120
fix: preserve model transport when binding per-run proxy credentials
2 parents 28b9754 + 23c7b2b commit 6b15092

8 files changed

Lines changed: 637 additions & 30 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
---
2+
name: verify-proxy-key-transport
3+
description: Verify per-run proxy credentials through actual loopback HTTP and SSE without external providers or customer data.
4+
---
5+
6+
1. Launch: use an isolated latest-main worktree and its owned locked dev environment
7+
(`uv sync --locked --dev --extra mcp`, reusing the package download store).
8+
The tests own a temporary loopback HTTP server; no application service,
9+
container, database, target or external model is started.
10+
2. Doctor: `python3 tests/ci/verify_proxy_key_transport.py --doctor` asserts that
11+
all three product packages and the interpreter environment belong to this
12+
worktree. Baseline `28b97543` must exist locally for historical checks.
13+
`--types` and `--types-full` reuse the canonical root type configuration.
14+
3. Drive: run the root service-harness inspect, verify and status commands.
15+
The transport gate runs real sync/async HTTP and SSE requests, selected-model
16+
and vendor tool-turn checks, credential-failure refusals and connected suites.
17+
The identical six assertions must fail against immutable old middleware,
18+
loaded in memory without changing the worktree. Historical infrastructure
19+
errors, skips and incomplete regressions return2 rather than qualifying.
20+
4. Evidence: retain source hashes, exact commands, stdout/stderr and actual exit
21+
codes outside the task worktree. This proves local transport behavior, not
22+
external upstream availability or deployment acceptance. The pinned personal
23+
runner rejects existing benchmark submodule directories before execution;
24+
report that limit, preserve the submodules, and run every exact declared
25+
command independently. Manual results are not a successful runner receipt.
26+
Repository protection and exact-head hosted checks remain separate.
27+
5. Cleanup: the fixture closes and joins only its own HTTP server, and the
28+
driver deletes only its temporary JUnit file. No credentials are required.
29+
Preserve evidence and remove the worktree only after actual merge and
30+
clean/pushed/inactive checks.

‎AGENTS.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,9 @@ Keep Brain local-only with ENTIRE_BRAIN_NO_EGRESS=1. Before opening or updating
6161
a PR, update the single root CHAGELOG.md and link it from the PR description.
6262
Keep checkpoint uploads disabled for public source; do not attach sessions
6363
containing private work.
64+
65+
# Model credential binding
66+
67+
| Invariant | Enforcement |
68+
| --- | --- |
69+
| Binding a per-run proxy key retains the selected model's transport/protocol configuration and never silently dispatches with an environment key on binding failure. | `tests/ci/verify_proxy_key_transport.py`, real loopback HTTP/SSE and sync/async rejection cases; immutable historical middleware must fail all six regression assertions. |

‎CHAGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ Keep proposed and unmerged changes out of released sections.
1515

1616
## [Unreleased]
1717

18+
- Proposed per-run proxy credential correction ([#1211](https://github.com/BitterSecurity/Decepticon/pull/1211)): preserve selected-model streaming, usage, token limits, retry/timeout settings, vendor protocol subclasses and HTTP transports when binding an engagement key. Refuse dispatch if an explicit key cannot be bound instead of silently using the environment account; requests without a per-run key are unchanged. No package version, publication or deployment. [Verification and compatibility](docs/verification/proxy-key-transport-20261120.md).
19+
1820
- Proposed CI verification correction ([#1210](https://github.com/BitterSecurity/Decepticon/pull/1210)): require every declared dependency to succeed or intentionally skip before CI OK passes. Reject abandoned, unknown and missing outcomes while preserving existing scope skips and protections. This corrects a false-positive aggregate after a hosted macOS runner could not be assigned; runner availability and actual hosted CI remain separate. [Verification](docs/verification/ci-required-terminal-results-20261120.md).
1921

2022
- Proposed [PR #1209](https://github.com/BitterSecurity/Decepticon/pull/1209) on the rust-anything streaming text experiment. Recorded parity held for 231 cases, while the Node native binding was slower in the local microbenchmark. See the [measured results](docs/verification/rust-anything-streaming-text-20261120.md).
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Per-run proxy credentials preserve selected-model behavior
2+
3+
## Problem and change
4+
5+
Rebuilding a selected model as a plain `ChatOpenAI` silently reset streaming,
6+
streaming usage, token limits and selected timeout/retry settings. It also
7+
discarded vendor protocol subclasses and custom HTTP transports. In a shared
8+
server, a credential-binding error continued with the original environment
9+
credential instead of rejecting the request.
10+
11+
Revalidate the selected concrete model with its original configuration and
12+
fresh OpenAI clients. Preserve serialization-excluded configuration such as
13+
HTTP pools, callbacks and the streaming chunk timeout. Keep the configured
14+
proxy destination; remove a default Authorization override and update an
15+
existing LiteLLM authentication header. Preserve provider BYOK and tracing
16+
headers. The established temperature compatibility rule remains in place.
17+
18+
An explicit per-run credential that cannot be bound now refuses dispatch in
19+
both sync and async middleware. The generic error/log does not contain the
20+
underlying exception or credential. Requests without a per-run credential keep
21+
their existing single-tenant behavior. This failure behavior is intentional:
22+
multi-tenant callers must fix their credential configuration rather than
23+
silently charge the environment account.
24+
25+
## Local evidence
26+
27+
Baseline: immutable main `28b97543aba2e80761564fdf85e8c4ba4d9f5738`.
28+
The final verification uses an owned environment installed with
29+
`uv sync --locked --dev --extra mcp`, reusing the download store. The driver
30+
asserts environment ownership and all three product imports resolve to this
31+
worktree. A shared environment was first used for compatibility measurements;
32+
its dependency drift and foreign editable analyzer paths were identified and
33+
those results are not the locked-environment acceptance evidence.
34+
35+
| Check | Actual result |
36+
| --- | --- |
37+
| New transport assertions against original middleware | All6 fail;0 errors/skips |
38+
| Transport and original proxy middleware cases |16 passed |
39+
| Connected factory, model-selection and proxy suites |902 passed;0 skips |
40+
| Full repository Ruff |Passed |
41+
| Full repository format check |943 files formatted |
42+
| Changed Python files, errors-only type check |0 errors |
43+
| Full canonical root type check, locked environment |893 files;0 errors;953 existing warnings |
44+
| Existing CI aggregate behavior |22 real Bash fixtures pass; historical regression exits1 |
45+
46+
`python3 tests/ci/verify_proxy_key_transport.py --doctor` checks import ownership.
47+
`python3 tests/ci/verify_proxy_key_transport.py` drives the connected suite.
48+
`python3 tests/ci/verify_proxy_key_transport.py --historical` reads the immutable
49+
old middleware into memory and must exit1 with exactly six assertion failures.
50+
Setup, collection, skips and incomplete historical runs do not qualify.
51+
52+
The HTTP fixture runs real `invoke` and `ainvoke` requests against a disposable
53+
loopback server, including SSE aggregation, token callbacks and usage. It checks
54+
wire credentials, streaming mode, token limits, sampling, subclass behavior,
55+
fresh client construction, custom HTTP pool identity and original-model
56+
immutability. Two vendor tool-bound turns retain opaque synthetic protocol
57+
blocks. Binding-failure tests assert no handler dispatch and capture the actual
58+
logger's output. No model provider, database, remote target or real credential
59+
is used by these tests.
60+
61+
## Verification limits
62+
63+
The pinned personal `service-harness` runner rejects the repository's existing
64+
benchmark submodule directories before gates execute: `Submodules need an
65+
explicit verification contract: benchmark/MHBench`. Inspect/verify exit2 and
66+
status has no receipt. No submodule, runner, trust configuration or repository
67+
protection was changed to work around it. All seven declared gates and their
68+
two historical regressions were run directly with their exact argv; direct
69+
results are not a successful personal-harness receipt.
70+
71+
These tests establish local HTTP/protocol behavior. They do not establish
72+
external provider availability, end-to-end deployment acceptance, package
73+
publication or a production rollout. No version is bumped by this change.

‎packages/decepticon/decepticon/middleware/proxy_key_override.py‎

Lines changed: 42 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -101,32 +101,37 @@ def _read_proxy_key(request: Any) -> str:
101101

102102

103103
def _rekey_model(original: BaseChatModel, api_key: str) -> BaseChatModel:
104-
"""Rebuild ``original`` against the LiteLLM proxy, authenticating with
105-
``api_key`` instead of the env master key.
106-
107-
Rebuild rather than ``model_copy`` because the OpenAI client binds the API
108-
key at ``__init__`` — a shallow copy would keep the old client (old key).
109-
Model id, base url, timeout, retries, and the temperature gate mirror the
110-
baked-in primary (same as ``model_override._build_proxied_llm``) so
111-
streaming / tool calling / fallback semantics are unchanged; only the
112-
Authorization key differs.
104+
"""Bind fresh proxy clients while retaining the selected model's protocol.
105+
106+
The OpenAI clients capture credentials at construction, so a shallow model
107+
copy would retain the previous key. Revalidate the original concrete class
108+
with all its configuration, including fields excluded from serialization
109+
(custom HTTP transports, callbacks and streaming timeouts). Only the bound
110+
OpenAI clients must be recreated. Never send a virtual key to an arbitrary
111+
model URL: the destination remains the configured proxy.
113112
"""
113+
if not isinstance(original, ChatOpenAI):
114+
raise TypeError("per-run proxy credentials require an OpenAI-compatible proxy model")
114115
proxy = LLMFactory._resolve_proxy_config()
115-
model_id = getattr(original, "model_name", None) or getattr(original, "model", None)
116-
if not model_id:
117-
raise ValueError("cannot resolve model id from current model for re-key")
118-
kwargs: dict[str, Any] = {
119-
"model": model_id,
120-
"base_url": proxy.url,
121-
"api_key": SecretStr(api_key),
122-
"timeout": proxy.timeout,
123-
"max_retries": proxy.max_retries,
116+
bound_clients = {"client", "async_client", "root_client", "root_async_client"}
117+
kwargs = {
118+
name: getattr(original, name)
119+
for name in type(original).model_fields
120+
if name not in bound_clients
124121
}
125-
if not _model_drops_temperature(str(model_id)):
126-
temperature = getattr(original, "temperature", None)
127-
if temperature is not None:
128-
kwargs["temperature"] = temperature
129-
return ChatOpenAI(**kwargs)
122+
kwargs["openai_api_base"] = proxy.url
123+
kwargs["openai_api_key"] = SecretStr(api_key)
124+
# Default headers can override the client's new Authorization header. Keep
125+
# provider BYOK and tracing headers, but replace proxy authentication only.
126+
if original.default_headers is not None:
127+
kwargs["default_headers"] = {
128+
name: api_key if name.lower() == "x-litellm-api-key" else value
129+
for name, value in original.default_headers.items()
130+
if name.lower() != "authorization"
131+
}
132+
if _model_drops_temperature(original.model_name):
133+
kwargs["temperature"] = None
134+
return type(original).model_validate(kwargs)
130135

131136

132137
class ProxyKeyOverrideMiddleware(AgentMiddleware):
@@ -149,9 +154,13 @@ def wrap_model_call(self, request, handler):
149154
return handler(request)
150155
try:
151156
new_llm = _rekey_model(request.model, key)
152-
except Exception as exc:
153-
log.warning("proxy_key_override failed to bind: %s", exc)
154-
return handler(request)
157+
except Exception:
158+
log.warning(
159+
"proxy_key_override refused dispatch: per-run proxy credential binding failed"
160+
)
161+
raise RuntimeError(
162+
"Failed to bind per-run proxy credential; model dispatch refused"
163+
) from None
155164
log.info("proxy_key_override active (per-run virtual key)")
156165
return handler(request.override(model=new_llm))
157166

@@ -162,9 +171,13 @@ async def awrap_model_call(self, request, handler):
162171
return await handler(request)
163172
try:
164173
new_llm = _rekey_model(request.model, key)
165-
except Exception as exc:
166-
log.warning("proxy_key_override failed to bind: %s", exc)
167-
return await handler(request)
174+
except Exception:
175+
log.warning(
176+
"proxy_key_override refused dispatch: per-run proxy credential binding failed"
177+
)
178+
raise RuntimeError(
179+
"Failed to bind per-run proxy credential; model dispatch refused"
180+
) from None
168181
log.info("proxy_key_override active (per-run virtual key)")
169182
return await handler(request.override(model=new_llm))
170183

0 commit comments

Comments
 (0)