Skip to content

The agent that grows with you

test: Anthropic OAuth mid-turn refresh E2E via TLS-intercepting token proxy (#120815 strict xfail)

teknium1c66e4d584b8d
diff --git a/tests/e2e/core/providers/_oauth_helpers.py b/tests/e2e/core/providers/_oauth_helpers.py
index 3745c4ee90d..784035f1464 100644
--- a/tests/e2e/core/providers/_oauth_helpers.py
+++ b/tests/e2e/core/providers/_oauth_helpers.py
@@ -136,8 +136,9 @@ def wait_until(pred: Callable[[], Any], timeout: float, what: str, interval: flo
#
# Just enough of the Messages API for a text turn (JSON and SSE). The request
# record keeps the bearer so a test can prove which access token each call
-# carried; ``decide`` maps a record to ("text", str) | ("error", status, type, msg)
-# | ("hold", threading.Event, next_decision).
+# carried; ``decide`` maps a record to ("text", str) | ("tool", name, input)
+# | ("error", status, type, msg) | ("hold", threading.Event, next_decision)
+# | ("call", zero-arg callable returning the decision at send time).
def _sse(event: str, data: dict[str, Any]) -> bytes:
@@ -186,6 +187,9 @@ class MessagesServer:
def do_POST(self) -> None: # noqa: N802
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
+ if not self.path.split("?", 1)[0].endswith("/v1/messages"):
+ # Local-endpoint capability probes (e.g. ``/api/show``) are not Messages calls.
+ return self._json(404, {"type": "error", "error": {"type": "not_found_error", "message": "no"}})
body = json.loads(raw or b"{}")
auth = self.headers.get("Authorization", "")
record = {"path": self.path, "body": body, "bearer": auth.removeprefix("Bearer ").strip(),
@@ -193,20 +197,28 @@ class MessagesServer:
with outer._lock:
outer.requests.append(record)
decision = outer.decide(record)
- while decision[0] == "hold":
+ while decision[0] in ("hold", "call"):
+ if decision[0] == "call":
+ decision = decision[1]()
+ continue
decision[1].wait(120)
decision = decision[2]
if decision[0] == "error":
_, status, etype, msg = decision
return self._json(status, {"type": "error", "error": {"type": etype, "message": msg}})
- text = decision[1]
+ if decision[0] == "tool":
+ block = {"type": "tool_use", "id": f"toolu_{uuid.uuid4().hex[:12]}", "name": decision[1],
+ "input": decision[2]}
+ stop = "tool_use"
+ else:
+ block, stop = {"type": "text", "text": decision[1]}, "end_turn"
if body.get("stream"):
- return self._stream(text)
+ return self._stream(block, stop)
self._json(200, {"id": "msg_fake", "type": "message", "role": "assistant", "model": outer.MODEL,
- "content": [{"type": "text", "text": text}], "stop_reason": "end_turn",
+ "content": [block], "stop_reason": stop,
"stop_sequence": None, "usage": {"input_tokens": 10, "output_tokens": 5}})
- def _stream(self, text: str) -> None:
+ def _stream(self, block: dict[str, Any], stop: str) -> None:
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Connection", "close")
@@ -214,15 +226,19 @@ class MessagesServer:
msg = {"id": "msg_fake", "type": "message", "role": "assistant", "model": outer.MODEL,
"content": [], "stop_reason": None, "stop_sequence": None,
"usage": {"input_tokens": 10, "output_tokens": 1}}
+ if block["type"] == "tool_use":
+ start = {**block, "input": {}}
+ delta = {"type": "input_json_delta", "partial_json": json.dumps(block["input"])}
+ else:
+ start = {"type": "text", "text": ""}
+ delta = {"type": "text_delta", "text": block["text"]}
for chunk in (
_sse("message_start", {"type": "message_start", "message": msg}),
- _sse("content_block_start", {"type": "content_block_start", "index": 0,
- "content_block": {"type": "text", "text": ""}}),
- _sse("content_block_delta", {"type": "content_block_delta", "index": 0,
- "delta": {"type": "text_delta", "text": text}}),
+ _sse("content_block_start", {"type": "content_block_start", "index": 0, "content_block": start}),
+ _sse("content_block_delta", {"type": "content_block_delta", "index": 0, "delta": delta}),
_sse("content_block_stop", {"type": "content_block_stop", "index": 0}),
_sse("message_delta", {"type": "message_delta",
- "delta": {"stop_reason": "end_turn", "stop_sequence": None},
+ "delta": {"stop_reason": stop, "stop_sequence": None},
"usage": {"output_tokens": 5}}),
_sse("message_stop", {"type": "message_stop"}),
):
@@ -244,3 +260,62 @@ class MessagesServer:
return
return Handler
+
+
+# ---- Anthropic OAuth rig ----------------------------------------------------
+#
+# The Anthropic token URL is hardcoded (no supported override), so the child
+# reaches the fake token server through TLSInterceptProxy: HTTPS_PROXY + a test
+# CA in SSL_CERT_FILE; NO_PROXY keeps inference to the loopback fake direct.
+
+ANTHROPIC_TOKEN_HOSTS = ("platform.claude.com", "console.anthropic.com")
+OLD_ACCESS = "sk-ant-oat01-e2e-old-access"
+
+
+@dataclass
+class AnthropicOAuthRig:
+ fh: FakeHome
+ tokens: Any # OAuthTokenServer
+ proxy: Any # TLSInterceptProxy
+ messages: MessagesServer
+ seed_refresh: str
+ child_env: dict[str, str]
+
+ def stop(self) -> None:
+ kill_tagged(self.fh.tag)
+ self.messages.stop()
+ self.proxy.stop()
+ self.tokens.stop()
+
+ def pool_row(self, entry_id: str = "e1") -> dict[str, Any]:
+ rows = self.fh.read_auth().get("credential_pool", {}).get("anthropic") or []
+ return next((r for r in rows if r.get("id") == entry_id), {})
+
+
+def start_anthropic_rig(root: Path, decide: Callable[[dict[str, Any]], tuple], *,
+ title_generation: bool, entries: int = 1) -> AnthropicOAuthRig:
+ from tests.fakes.providers.oauth_token_server import OAuthTokenServer, TLSInterceptProxy, make_test_ca
+
+ ca = make_test_ca(root / "ca", ANTHROPIC_TOKEN_HOSTS)
+ tokens = OAuthTokenServer().start()
+ proxy = TLSInterceptProxy(tokens, ca, ANTHROPIC_TOKEN_HOSTS).start()
+ messages = MessagesServer(decide).start()
+ fh = make_home(root)
+ fh.write_config({
+ "model": {"provider": "anthropic", "default": MessagesServer.MODEL, "base_url": messages.base_url},
+ "auxiliary": {"title_generation": {"enabled": title_generation}},
+ })
+ seed = tokens.seed_refresh_token()
+ rows = [{"id": "e1", "label": "acct-1", "auth_type": "oauth", "priority": 0, "source": "manual",
+ "access_token": OLD_ACCESS, "refresh_token": seed,
+ # Not expired by the clock: the vendor revoking/expiring it early (401) is the trigger.
+ "expires_at_ms": int(time.time() * 1000) + 3_600_000}]
+ for i in range(2, entries + 1):
+ rows.append({"id": f"e{i}", "label": f"acct-{i}", "auth_type": "oauth", "priority": i - 1,
+ "source": "manual", "access_token": f"sk-ant-oat01-e2e-spare-{i}",
+ "refresh_token": tokens.seed_refresh_token(), "expires_at_ms": int(time.time() * 1000) + 3_600_000})
+ fh.write_auth({"version": 1, "credential_pool": {"anthropic": rows}})
+ loopback = "127.0.0.1,localhost"
+ env = {"HTTPS_PROXY": proxy.url, "https_proxy": proxy.url, "NO_PROXY": loopback, "no_proxy": loopback,
+ "SSL_CERT_FILE": str(ca.ca_pem)}
+ return AnthropicOAuthRig(fh=fh, tokens=tokens, proxy=proxy, messages=messages, seed_refresh=seed, child_env=env)
diff --git a/tests/e2e/core/providers/test_oauth_anthropic_refresh.py b/tests/e2e/core/providers/test_oauth_anthropic_refresh.py
new file mode 100644
index 00000000000..76b0df8d89a
--- /dev/null
+++ b/tests/e2e/core/providers/test_oauth_anthropic_refresh.py
@@ -0,0 +1,132 @@
+"""Anthropic OAuth access token expires mid-turn: one refresh, the turn completes, the rotation persists.
+
+Real ``hermes -z`` process, native ``anthropic`` provider on the OAuth route
+(``sk-ant-oat…`` pool credential), inference against a loopback Messages
+endpoint (accepted base-URL override ``http://127.0.0.1:<port>/anthropic``),
+and the vendor token endpoint (hardcoded ``https://platform.claude.com``)
+reached through the TLS-intercepting proxy — nothing of ours is faked.
+
+The first model call is answered with a tool call; the follow-up call (same,
+now expired, bearer) gets the vendor's 401. The single-use refresh token must
+be spent exactly once, the retry must carry the new bearer, and auth.json must
+hold the NEW, still-live refresh token afterwards — otherwise the next process
+replays a spent token and the login is lost.
+"""
+
+from __future__ import annotations
+
+import sys
+import threading
+import time
+import uuid
+
+import pytest
+
+from tests.e2e.core.providers._oauth_helpers import OLD_ACCESS, run_hermes, start_anthropic_rig, wait_until
+
+pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="tagged-tree cleanup uses /proc")
+
+FINAL = "OAUTH-REFRESH-TURN-COMPLETE"
+EXPIRED = ("error", 401, "authentication_error", "OAuth token has expired")
+SLOW_TOKEN_ENDPOINT_S = 2.0
+
+# Red on main for a tracked, open bug. Strict: XPASS fails, forcing the entry out with the fix.
+KNOWN: dict[str, str] = {
+ "aux_call_shares_expired_token": (
+ "#120815 a stale credential pool (the auxiliary title call's) persists the spent refresh token "
+ "over the rotation the main turn just committed"),
+}
+
+
+def _has_tool_result(body: dict) -> bool:
+ return any(isinstance(m.get("content"), list) and any(b.get("type") == "tool_result" for b in m["content"])
+ for m in body.get("messages") or [])
+
+
+def _run_turn(tmp_path, *, aux_401: bool):
+ canary = f"CANARY-{uuid.uuid4().hex[:10]}"
+ note = tmp_path / "note.txt"
+ note.write_text(canary, encoding="utf-8")
+ # Race order that loses the login on main, pinned with events: the auxiliary (title) call is
+ # sent with the expired bearer before the main turn refreshes, and its 401 lands while the
+ # main turn's refresh POST is in flight (the vendor token endpoint answers slowly).
+ aux_sent, refresh_in_flight, aux_answered, aux_settled = (threading.Event() for _ in range(4))
+ aux_answered_at: list[int] = []
+
+ def answer_aux() -> tuple:
+ aux_answered_at.append(time.time_ns())
+ aux_answered.set()
+ return EXPIRED
+
+ def decide(record: dict) -> tuple:
+ body, bearer = record["body"], record["bearer"] or record["x_api_key"]
+ if not body.get("tools"): # auxiliary call (title generation)
+ if aux_401 and bearer == OLD_ACCESS:
+ aux_sent.set()
+ return ("hold", refresh_in_flight, ("call", answer_aux))
+ return ("text", "OAuth refresh title")
+ if not _has_tool_result(body):
+ return ("tool", "read_file", {"path": str(note)})
+ if bearer == OLD_ACCESS:
+ return ("hold", aux_sent, EXPIRED) if aux_401 else EXPIRED
+ return ("hold", aux_settled, ("text", FINAL)) if aux_401 else ("text", FINAL)
+
+ rig = start_anthropic_rig(tmp_path, decide, title_generation=aux_401)
+
+ def slow_token_endpoint(_grant) -> None:
+ refresh_in_flight.set()
+ aux_answered.wait(60)
+ threading.Event().wait(SLOW_TOKEN_ENDPOINT_S) # vendor latency window, not synchronization
+
+ def settle() -> None:
+ # The aux client has handled its 401 once auth.json is written after that 401 was sent
+ # (bounded: a build that never writes there just releases the turn at the deadline).
+ try:
+ wait_until(lambda: aux_answered_at, 90, "the aux 401 to be sent")
+ wait_until(lambda: rig.fh.auth_path.stat().st_mtime_ns > aux_answered_at[0] + int(
+ SLOW_TOKEN_ENDPOINT_S * 1e9), 15, "a write after the rotation")
+ except AssertionError:
+ pass
+ aux_settled.set()
+
+ if aux_401:
+ rig.tokens.before_refresh_response = slow_token_endpoint
+ threading.Thread(target=settle, daemon=True).start()
+ try:
+ proc = run_hermes(rig.fh, ["-z", "Read the note file and report."], extra_env=rig.child_env, timeout=150)
+ finally:
+ for ev in (aux_sent, refresh_in_flight, aux_answered, aux_settled):
+ ev.set()
+ rig.stop()
+ return rig, proc, canary
+
+
+ pytest.param("main_turn_only", id="main_turn_only"),
+ pytest.param("aux_call_shares_expired_token", id="aux_call_shares_expired_token",
+ marks=pytest.mark.xfail(strict=True, reason=KNOWN["aux_call_shares_expired_token"])),
+])
+def test_expired_oauth_token_mid_turn_refreshes_once_and_persists(case: str, tmp_path) -> None:
+ rig, proc, canary = _run_turn(tmp_path, aux_401=case != "main_turn_only")
+ out = f"exit={proc.returncode}\nstdout:\n{proc.stdout[-1500:]}\nstderr:\n{proc.stderr[-2500:]}"
+ mains = rig.messages.main_requests()
+ grants = rig.tokens.refresh_grants()
+
+ assert proc.returncode == 0 and FINAL in proc.stdout, f"turn did not deliver the answer\n{out}"
+ assert not rig.proxy.refused or all("claude" not in r and "anthropic" not in r for r in rig.proxy.refused)
+ assert len(grants) == 1 and grants[0].status == 200, (
+ f"expected exactly one successful refresh grant, got {[(g.presented, g.status, g.error) for g in grants]}")
+ assert grants[0].presented == rig.seed_refresh, "the refresh spent a token other than the stored one"
+ new_access, new_refresh = grants[0].issued_access_token, grants[0].issued_refresh_token
+
+ tool_rounds = [r for r in mains if _has_tool_result(r["body"])]
+ assert any(canary in str(r["body"]) for r in tool_rounds), "the tool result never reached the model"
+ assert [r["bearer"] or r["x_api_key"] for r in tool_rounds][-1] == new_access, (
+ "the retried request did not carry the refreshed bearer")
+
+ row = rig.pool_row("e1")
+ assert rig.tokens.is_live(row.get("refresh_token", "")), (
+ f"auth.json holds a refresh token the vendor no longer accepts (login lost on the next process): "
+ f"disk={row.get('refresh_token')!r} status={row.get('last_status')!r}; issued={new_refresh!r}, "
+ f"spent={sorted(rig.tokens.spent)}")
+ assert row.get("access_token") == new_access
diff --git a/tests/fakes/providers/oauth_token_server.py b/tests/fakes/providers/oauth_token_server.py
index ad1cfb48cf3..e49c2cf0564 100644
--- a/tests/fakes/providers/oauth_token_server.py
+++ b/tests/fakes/providers/oauth_token_server.py
@@ -109,6 +109,9 @@ class OAuthTokenServer:
self.grants: list[Grant] = []
self.device: DeviceFlow | None = None
self.device_requests = 0
+ # Fault injection: called (outside the lock) after a refresh grant is recorded and the
+ # pair rotated, before the response is written -- a slow vendor token endpoint.
+ self.before_refresh_response: Callable[[Grant], None] | None = None
self._httpd: ThreadingHTTPServer | None = None
self._thread: threading.Thread | None = None
@@ -166,6 +169,8 @@ class OAuthTokenServer:
self.spent.add(presented)
access, refresh = self._issue_pair()
grant.issued_access_token, grant.issued_refresh_token = access, refresh
+ if self.before_refresh_response is not None:
+ self.before_refresh_response(grant)
return 200, self._token_body(access, refresh)
def _device_poll(self, form: dict[str, str], meta: dict[str, str]) -> tuple[int, dict[str, Any]]: