Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions agent-adk/tests/test_conversation_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
STANDING_ROLE,
anthropic_environment,
check_gateway_keys,
check_pass_refresh,
conversation,
fake_provider,
missing_from,
Expand Down Expand Up @@ -138,6 +139,8 @@ def app_for(environment):
return importlib.reload(main).app

check_gateway_keys(app_for, wire, token=TOKEN)
# A pass that runs out part way is renewed once and the call sent again.
check_pass_refresh(app_for, wire, token=TOKEN)


@pytest.mark.parametrize("environment", [openai_environment, anthropic_environment])
Expand Down
3 changes: 3 additions & 0 deletions agent-ag2/tests/test_conversation_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from harness_contract import (
anthropic_environment,
check_gateway_keys,
check_pass_refresh,
conversation,
fake_provider,
missing_from,
Expand Down Expand Up @@ -66,6 +67,8 @@ def app_for(environment):
return importlib.reload(main).app

check_gateway_keys(app_for, wire, path="/", token=TOKEN)
# A pass that runs out part way is renewed once and the call sent again.
check_pass_refresh(app_for, wire, path="/", token=TOKEN)


@pytest.mark.parametrize("environment", [openai_environment, anthropic_environment])
Expand Down
3 changes: 3 additions & 0 deletions agent-agno/tests/test_conversation_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from harness_contract import (
anthropic_environment,
check_gateway_keys,
check_pass_refresh,
conversation,
fake_provider,
missing_from,
Expand Down Expand Up @@ -67,6 +68,8 @@ def app_for(environment):
return importlib.reload(main).app

check_gateway_keys(app_for, wire, path="/agui", token=TOKEN)
# A pass that runs out part way is renewed once and the call sent again.
check_pass_refresh(app_for, wire, path="/agui", token=TOKEN)


@pytest.mark.parametrize("environment", [openai_environment, anthropic_environment])
Expand Down
62 changes: 45 additions & 17 deletions agent-claude-sdk/src/run_model_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@
Only where the configured address is the gateway's (`/api/model-provider/`) and a run brought a
token. Otherwise Claude Code is given what it always was.
A query outlasts its pass too: one long query runs past the pass's ten minutes before any run steps
in. So the thread's slot keeps the run's pass whole, refresh credential and all (`RunPass`), and a
call the gateway refuses because the pass ran out (`x-openbot-pass: expired`) is renewed and sent
again once, as every Python harness's calls are (`send_on_pass` in shared/run_model_key.py, which
cites the OAuth practice it follows). The renewed pass is the slot's from then on.
"""

import os
Expand All @@ -31,7 +37,7 @@
# The module every Python harness shares: beside this harness in the repository, at /shared in the
# image the Dockerfile builds.
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared"))
from run_model_key import GATEWAY_PATH, run_key # noqa: E402
from run_model_key import GATEWAY_PATH, RunPass, asend_on_pass, run_pass # noqa: E402

PROXY_PATH = "/_run-model/"
# The header a query's model calls carry their secret in, set through Claude Code's
Expand All @@ -44,13 +50,19 @@


class _Slot:
__slots__ = ("secret", "key", "at")
"""A thread's way back in: its secret, and the pass of the newest run that brought one."""

__slots__ = ("secret", "run_pass", "at")

def __init__(self, secret: str, key: str):
def __init__(self, secret: str, run_pass: RunPass):
self.secret = secret
self.key = key
self.run_pass = run_pass
self.at = time.monotonic()

@property
def key(self) -> str:
return self.run_pass.token


_by_thread: dict[str, _Slot] = {}
_by_secret: dict[str, _Slot] = {}
Expand All @@ -73,17 +85,17 @@ def query_environment(thread_id: str | None) -> dict[str, str]:
Empty where the run brought no token or the configured address is not the gateway's.
"""
key = run_key()
if not key or not thread_id or not _gateway_base():
holder = run_pass()
if holder is None or not holder.token or not thread_id or not _gateway_base():
return {}
now = time.monotonic()
_forget_old(now)
slot = _by_thread.get(thread_id)
if slot is None:
slot = _Slot(secrets.token_urlsafe(32), key)
slot = _Slot(secrets.token_urlsafe(32), holder)
_by_thread[thread_id] = slot
_by_secret[slot.secret] = slot
slot.key, slot.at = key, now
slot.run_pass, slot.at = holder, now
port = (os.environ.get("PORT") or "4212").strip()
# Headers the container already sends with its model calls go on being sent, as the SDK lays
# a query's environment over the container's own.
Expand All @@ -99,18 +111,26 @@ def query_environment(thread_id: str | None) -> dict[str, str]:


def refresh(thread_id: str | None) -> None:
"""A run of `thread_id` brought a newer token: the query it carries on sends that from now."""
key = run_key()
"""A run of `thread_id` brought a newer token: the query it carries on sends that from now.
The run's pass itself, so a renewal made for the query is the run's too, and the other way round.
"""
holder = run_pass()
slot = _by_thread.get(thread_id or "")
if key and slot is not None:
slot.key, slot.at = key, time.monotonic()
if holder is not None and holder.token and slot is not None:
slot.run_pass, slot.at = holder, time.monotonic()


def slot_key(secret: str) -> str | None:
slot = _by_secret.get(secret)
return slot.key if slot is not None else None


def _slot_pass(secret: str) -> RunPass | None:
slot = _by_secret.get(secret)
return slot.run_pass if slot is not None else None


# What is not passed on to the gateway: how this hop was made, the key Claude Code was given, and
# the secret that let it back in.
_REQUEST_DROPPED = {
Expand All @@ -130,17 +150,18 @@ def slot_key(secret: str) -> str | None:
async def forward(request, path: str):
"""One of Claude Code's model calls, passed on to the gateway with its thread's newest token.
Turned away before its body is read when it names no query of this process.
Turned away before its body is read when it names no query of this process. A pass the gateway
refuses as run out is renewed and the call sent again once (`asend_on_pass`).
"""
import httpx
from fastapi.responses import JSONResponse, StreamingResponse
from starlette.background import BackgroundTask

global _client
key = slot_key((request.headers.get(SECRET_HEADER) or "").strip())
holder = _slot_pass((request.headers.get(SECRET_HEADER) or "").strip())
base = _gateway_base()
client_host = request.client.host if request.client else ""
if not key or not base or client_host not in ("127.0.0.1", "::1"):
if holder is None or not holder.token or not base or client_host not in ("127.0.0.1", "::1"):
return JSONResponse({"error": "not found"}, status_code=404)
if _client is None:
_client = httpx.AsyncClient(timeout=httpx.Timeout(None, connect=30.0))
Expand All @@ -152,11 +173,18 @@ async def forward(request, path: str):
for name, value in request.headers.items()
if name.lower() not in _REQUEST_DROPPED
}
headers["x-api-key"] = key
# Swapped for the slot's pass as it is sent, and again if that pass is renewed.
headers["x-api-key"] = ""
upstream = _client.build_request(
request.method, target, headers=headers, content=await request.body()
)
response = await _client.send(upstream, stream=True)
client = _client
response = await asend_on_pass(
holder,
upstream,
lambda again: client.send(again, stream=True),
lambda renewal: client.send(renewal),
)
return StreamingResponse(
response.aiter_raw(),
status_code=response.status_code,
Expand Down
70 changes: 65 additions & 5 deletions agent-claude-sdk/tests/test_run_model_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared"))
from harness_contract import (
DEPLOYMENT_KEY,
FRESH_KEY,
REFRESH_KEY,
RUN_KEY,
PassGate,
fake_provider,
gateway_environment,
run_events,
Expand Down Expand Up @@ -56,10 +59,14 @@ def _serve(app, port):
return server, thread


def _run(port, thread, key=None):
def _run(port, thread, key=None, *, refresh=None, finished=True):
props = {"openbotSendOnce": True}
if key:
props["openbotModelRoute"] = {"via": "anthropic", "token": key}
props["openbotModelRoute"] = {
"via": "anthropic",
"token": key,
**({"refresh": refresh} if refresh else {}),
}
props["openbotOrganization"] = "contract-organization"
response = httpx.post(
f"http://127.0.0.1:{port}/",
Expand All @@ -77,14 +84,21 @@ def _run(port, thread, key=None):
)
assert response.status_code == 200
events = run_events(response.text)
assert events[-1]["type"] == "RUN_FINISHED", events
if finished:
assert events[-1]["type"] == "RUN_FINISHED", events
return events


@pytest.fixture
def harness(monkeypatch, tmp_path):
def gate():
"""No pass runs out, unless a test says which (`PassGate`)."""
return PassGate(expired=())


@pytest.fixture
def harness(monkeypatch, tmp_path, gate):
keys: list[str] = []
with fake_provider(keys) as (base, bodies):
with fake_provider(keys, gate) as (base, bodies):
for name, value in gateway_environment("anthropic")(base).items():
monkeypatch.setenv(name, value)
monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False)
Expand Down Expand Up @@ -238,3 +252,49 @@ def test_the_way_back_in_takes_nothing_it_does_not_know(harness):
)
assert response.status_code == 404
assert keys == []


@pytest.mark.parametrize("gate", [PassGate(engine=TOKEN)])
def test_a_query_whose_pass_runs_out_renews_it_once_and_keeps_it(harness, gate):
"""A query that outlasts its pass renews it once, and the thread's calls carry the fresh one.
Found on staging: an unattended job ran past its ten-minute pass, its next model call got the
gateway's 401, and the run ended. The gateway now says a pass ran out (`x-openbot-pass:
expired`), and the harness renews it with the run's refresh credential and sends the call again.
"""
from src import run_model_proxy

port, keys, bodies = harness
_run(port, "thread-renewed", RUN_KEY, refresh=REFRESH_KEY)
used = _messages_keys(keys, 0)
assert used and used[0] == RUN_KEY, keys
first_fresh = used.index(FRESH_KEY)
# Calls that ran out together waited on one renewal; every call after it carries the fresh pass.
assert set(used[:first_fresh]) == {RUN_KEY} and set(used[first_fresh:]) == {FRESH_KEY}, used
assert gate.passes == [REFRESH_KEY]
# The renewal carried the engine's own secret (`MANAGED_AGENT_TOKEN`); no model call did.
assert gate.engines == [TOKEN] and gate.leaked == [], (gate.engines, gate.leaked)
assert run_model_proxy._by_thread["thread-renewed"].key == FRESH_KEY
text = json.dumps(bodies)
assert REFRESH_KEY not in text and FRESH_KEY not in text


@pytest.mark.parametrize(
"gate",
[
PassGate(engine=TOKEN, refuse_pass=True),
PassGate(engine=TOKEN, flagged=False),
# The gateway refuses a renewal that does not carry this engine's own secret.
PassGate(engine="another-engines-token"),
],
)
def test_a_pass_the_gateway_will_not_renew_reaches_claude_code_as_the_gateway_said(harness, gate):
"""A renewal refused, or a 401 that is not a pass running out: Claude Code gets the 401 as it came."""
port, keys, _ = harness
events = _run(port, "thread-refused", RUN_KEY, refresh=REFRESH_KEY, finished=False)
used = _messages_keys(keys, 0)
assert used and set(used) == {RUN_KEY}, keys
assert set(gate.passes) <= {REFRESH_KEY}
assert bool(gate.passes) == gate.flagged
# The model never answered: the call was not sent again on a pass it does not hold.
assert not any(event.get("delta") == "ok" for event in events), events
Loading
Loading