Skip to content

The agent that grows with you

fix(api_server): fail closed on unstamped runs; claim session-chat-stream run owner (#93689)

Teknium7a86397a46ea
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 33c77eaa688..9fc9e40c01d 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -4906,6 +4906,11 @@ class APIServerAdapter(BasePlatformAdapter):
queue: "asyncio.Queue[Optional[tuple[str, Dict[str, Any]]]]" = asyncio.Queue()
message_id = f"msg_{uuid.uuid4().hex}"
run_id = f"run_{uuid.uuid4().hex}"
+ # Claim ownership while still inside the request's profile scope,
+ # before any run-keyed state exists — the same rule as /v1/runs, so
+ # /v1/runs/{id}* control of this turn is confined to the profile
+ # that started it (#93689).
+ self._run_owners[run_id] = self._run_idempotency_scope(request)
self._set_run_status(
run_id,
"queued",
@@ -5041,6 +5046,7 @@ class APIServerAdapter(BasePlatformAdapter):
await queue.put(_event_payload("error", {"message": _redact_api_error_text(exc)}))
finally:
self._active_run_agents.pop(run_id, None)
+ self._release_run_owner_if_forgotten(run_id)
await queue.put(_event_payload("done", {}))
await queue.put(None)
@@ -7775,6 +7781,9 @@ class APIServerAdapter(BasePlatformAdapter):
def _request_owns_run(self, request: "web.Request", run_id: str) -> bool:
return _api_runs._request_owns_run(self, request, run_id)
+ def _release_run_owner_if_forgotten(self, run_id: str) -> None:
+ _api_runs._release_run_owner_if_forgotten(self, run_id)
+
async def _handle_get_run(self, request: "web.Request") -> "web.Response":
"""GET /v1/runs/{run_id} — return pollable run status for external UIs."""
return await _api_runs._handle_get_run(
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index 3ec16744264..758d847e45f 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -1017,6 +1017,7 @@ async def _handle_runs(
self._active_run_tasks.pop(run_id, None)
self._run_approval_sessions.pop(run_id, None)
self._stopping_run_ids.discard(run_id)
+ self._release_run_owner_if_forgotten(run_id)
self._activate_admitted_request()
task = asyncio.create_task(_run_and_close())
@@ -1038,25 +1039,36 @@ async def _handle_runs(
)
-def _request_owns_run(self, request: "web.Request", run_id: str) -> bool:
- scope = self._run_idempotency_scope(request)
- owner = self._run_owners.get(run_id)
- if self._room_grant_token(request):
- return owner == scope or (
- owner is None
- and self._run_idempotency_store.owns_run(scope, run_id)
- )
- if owner is None and (
+def _release_run_owner_if_forgotten(self, run_id: str) -> None:
+ """Drop the owner stamp only once nothing keyed by *run_id* survives.
+
+ Ownership must outlive every surface it protects (statuses, live
+ agent/task refs, SSE transport, approval sessions), which are retired
+ on different clocks. Releasing earlier would leave a stateful run
+ without an owner, which ``_request_owns_run`` treats as fail-closed.
+ """
+ if (
run_id in self._run_statuses
or run_id in self._active_run_agents
or run_id in self._active_run_tasks
+ or run_id in self._run_streams
+ or run_id in self._run_approval_sessions
):
- # Backward compatibility for statuses created by older/in-process
- # integrations before ownership tracking was introduced.
- return True
- return owner == scope or (
- owner is None and self._run_idempotency_store.owns_run(scope, run_id)
- )
+ return
+ self._run_owners.pop(run_id, None)
+
+
+def _request_owns_run(self, request: "web.Request", run_id: str) -> bool:
+ scope = self._run_idempotency_scope(request)
+ owner = self._run_owners.get(run_id)
+ if owner is not None:
+ return owner == scope
+ # No in-memory owner: only a durable record under the caller's own scope
+ # admits it. Run state that exists without an owner stamp is an
+ # unanswered authorization question, not a run anyone may control —
+ # under gateway.multiplex_profiles every served profile holds a valid
+ # key, so admitting it would make the boundary allow-all (#93689).
+ return self._run_idempotency_store.owns_run(scope, run_id)
async def _handle_get_run(
@@ -1154,6 +1166,7 @@ async def _handle_run_events(
self._run_stream_subscribers.discard(run_id)
self._run_streams.pop(run_id, None)
self._run_streams_created.pop(run_id, None)
+ self._release_run_owner_if_forgotten(run_id)
return response
@@ -1485,6 +1498,7 @@ def _sweep_orphaned_runs_once(self, now: Optional[float] = None) -> None:
self._active_run_tasks.pop(run_id, None)
self._run_approval_sessions.pop(run_id, None)
self._stopping_run_ids.discard(run_id)
+ self._release_run_owner_if_forgotten(run_id)
stale_statuses = [
run_id
@@ -1495,4 +1509,4 @@ def _sweep_orphaned_runs_once(self, now: Optional[float] = None) -> None:
for run_id in stale_statuses:
self._run_statuses.pop(run_id, None)
self._run_idempotency_ids.discard(run_id)
- self._run_owners.pop(run_id, None)
+ self._release_run_owner_if_forgotten(run_id)
diff --git a/tests/gateway/test_api_server.py b/tests/gateway/test_api_server.py
index ecb49cd7a88..56e298dc062 100644
--- a/tests/gateway/test_api_server.py
+++ b/tests/gateway/test_api_server.py
@@ -611,7 +611,9 @@ class TestDisconnectedAgentReap:
adapter._active_run_agents["run_x"] = agent
request = MagicMock()
+ request.headers = {}
request.match_info = {"run_id": "run_x"}
+ adapter._run_owners["run_x"] = adapter._run_idempotency_scope(request)
resp = await adapter._handle_stop_run(request)
assert resp.status == 200
diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.py
index 0f9f573ac4e..8d68f919c94 100644
--- a/tests/gateway/test_api_server_runs.py
+++ b/tests/gateway/test_api_server_runs.py
@@ -22,6 +22,7 @@ from aiohttp.test_utils import TestClient, TestServer
from gateway.config import PlatformConfig
from gateway.platforms.api_server import (
APIServerAdapter,
+ _api_request_profile,
_approval_event_choices,
cors_middleware,
security_headers_middleware,
@@ -68,6 +69,13 @@ def _make_adapter(api_key: str = "") -> APIServerAdapter:
return adapter
+def _claim_run(adapter: APIServerAdapter, run_id: str) -> None:
+ """Stamp *run_id* as owned by the unprefixed (default) request scope."""
+ request = MagicMock()
+ request.headers = {}
+ adapter._run_owners[run_id] = adapter._run_idempotency_scope(request)
+
+
def _create_runs_app(adapter: APIServerAdapter) -> web.Application:
"""Create an aiohttp app with /v1/runs routes registered."""
mws = [mw for mw in (cors_middleware, security_headers_middleware) if mw is not None]
@@ -468,6 +476,7 @@ class TestSteerRun:
adapter._active_run_agents["run_123"] = agent
adapter._run_streams["run_123"] = queue
adapter._set_run_status("run_123", "running")
+ _claim_run(adapter, "run_123")
async with TestClient(TestServer(app)) as cli:
resp = await cli.post("/v1/runs/run_123/steer", json={"input": "tighten the ending"})
@@ -500,6 +509,7 @@ class TestSteerRun:
async def test_steer_inactive_run_returns_409(self, adapter):
app = _create_runs_app(adapter)
adapter._set_run_status("run_done", "completed")
+ _claim_run(adapter, "run_done")
async with TestClient(TestServer(app)) as cli:
resp = await cli.post("/v1/runs/run_done/steer", json={"input": "hello"})
@@ -515,6 +525,7 @@ class TestSteerRun:
agent.steer.return_value = True
adapter._active_run_agents["run_123"] = agent
adapter._set_run_status("run_123", "running")
+ _claim_run(adapter, "run_123")
async with TestClient(TestServer(app)) as cli:
resp = await cli.post("/v1/runs/run_123/steer", json={"input": ""})
@@ -681,6 +692,92 @@ class TestRunLifecycleSweep:
mock_agent.interrupt.assert_called_once_with("Stop requested via API")
+# ---------------------------------------------------------------------------
+# Run ownership across served profiles (#93689 / #90415)
+# ---------------------------------------------------------------------------
+
+
+class TestRunOwnershipAcrossProfiles:
+ """Every served profile holds a valid key under multiplex; only the
+ creating profile may see or control a run."""
+
+ KEYS = {"victim": "sk-victim-profile-key-0001", "attacker": "sk-attacker-profile-key-01"}
+
+ @classmethod
+ def _profile_app(cls, adapter: APIServerAdapter) -> web.Application:
+ """Runs routes behind a stand-in for the /p/<profile>/ middleware:
+ the routed profile arrives in ``X-Test-Profile`` and each profile
+ authenticates with its own key, as under gateway.multiplex_profiles."""
+
+ @web.middleware
+ async def stamp_profile(request, handler):
+ token = _api_request_profile.set(request.headers.get("X-Test-Profile"))
+ try:
+ return await handler(request)
+ finally:
+ _api_request_profile.reset(token)
+
+ adapter._expected_api_key = lambda: cls.KEYS.get(_api_request_profile.get(), "")
+ app = _create_runs_app(adapter)
+ app.middlewares.append(stamp_profile)
+ app.router.add_post(
+ "/api/sessions/{session_id}/chat/stream", adapter._handle_session_chat_stream
+ )
+ return app
+
+ @pytest.mark.asyncio
+ async def test_unstamped_run_state_fails_closed(self, adapter):
+ """Run state with no owner stamp is nobody's — not everybody's."""
+ app = _create_runs_app(adapter)
+ adapter._active_run_agents["run_unstamped"] = MagicMock()
+ adapter._set_run_status("run_unstamped", "running")
+
+ async with TestClient(TestServer(app)) as cli:
+ get_resp = await cli.get("/v1/runs/run_unstamped")
+ stop_resp = await cli.post("/v1/runs/run_unstamped/stop")
+
+ assert (get_resp.status, stop_resp.status) == (404, 404)
+
+ @pytest.mark.asyncio
+ async def test_session_chat_stream_run_is_owned_by_creating_profile(self, adapter):
+ """The session-chat-stream run mint claims ownership like /v1/runs does."""
+ app = self._profile_app(adapter)
+ victim = {"X-Test-Profile": "victim", "Authorization": f"Bearer {self.KEYS['victim']}"}
+ attacker = {"X-Test-Profile": "attacker", "Authorization": f"Bearer {self.KEYS['attacker']}"}
+ gate = asyncio.Event()
+
+ async def slow_run_agent(**kwargs):
+ await gate.wait()
+ return {"final_response": "ok"}, {}
+
+ async with TestClient(TestServer(app)) as cli:
+ with (
+ patch.object(adapter, "_get_existing_session_or_404", new=AsyncMock(return_value=({"id": "s1"}, None))),
+ patch.object(adapter, "_conversation_history_for_session", new=AsyncMock(return_value=[])),
+ patch.object(adapter, "_run_agent", new=slow_run_agent),
+ ):
+ stream = await cli.post(
+ "/api/sessions/s1/chat/stream", json={"message": "hi"}, headers=victim
+ )
+ await stream.content.readline()
+ (run_id,) = list(adapter._run_statuses)
+ assert run_id in adapter._run_owners
+
+ foreign_get = await cli.get(f"/v1/runs/{run_id}", headers=attacker)
+ foreign_stop = await cli.post(f"/v1/runs/{run_id}/stop", headers=attacker)
+ own_get = await cli.get(f"/v1/runs/{run_id}", headers=victim)
+ assert (foreign_get.status, foreign_stop.status, own_get.status) == (404, 404, 200)
+
+ gate.set()
+ await stream.text()
+
+ # The owner outlives the terminal status and goes with the last surface.
+ assert run_id in adapter._run_owners
+ adapter._run_statuses.pop(run_id)
+ adapter._release_run_owner_if_forgotten(run_id)
+ assert run_id not in adapter._run_owners
+
+
# ---------------------------------------------------------------------------
# POST /v1/runs/{run_id}/stop — interrupt a running agent
# ---------------------------------------------------------------------------
diff --git a/website/docs/user-guide/features/api-server.md b/website/docs/user-guide/features/api-server.md
index 3784d7e7153..36b6e1c7c03 100644
--- a/website/docs/user-guide/features/api-server.md
+++ b/website/docs/user-guide/features/api-server.md
@@ -629,6 +629,10 @@ to the routed profile**:
- Unprefixed routes and `/p/default/...` keep using the default profile's key.
- A named profile with no `API_SERVER_KEY` of its own fails closed — its
prefix is unreachable until you set one.
+- Runs are per-profile scoped: `/v1/runs/{run_id}` and its `events`, `stop`,
+ `steer`, and `approval` routes only answer for the profile that created
+ the run (including runs started via `/api/sessions/{id}/chat/stream`);
+ another profile's run id returns `404`, never `403`.
:::warning Breaking change (July 2026)
Before this fix, a valid default-profile key was accepted on any