From 570950f4641a9bfe74b3acd8abe53402bfe2f2c2 Mon Sep 17 00:00:00 2001 From: Vietpr Date: Fri, 20 Nov 2026 01:55:34 +0700 Subject: [PATCH 1/2] fix(agent-server): sync Codex credentials in Docker Co-authored-by: openhands --- .../openhands/agent_server/dependencies.py | 16 + .../agent_server/docker_runtime/routers.py | 285 +++++++++++++++++- .../docker_runtime/test_mediation.py | 37 ++- .../docker_runtime/test_routes.py | 211 ++++++++++++- 4 files changed, 537 insertions(+), 12 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/dependencies.py b/openhands-agent-server/openhands/agent_server/dependencies.py index ae05cd0f7a7..5cdf551e8c0 100644 --- a/openhands-agent-server/openhands/agent_server/dependencies.py +++ b/openhands-agent-server/openhands/agent_server/dependencies.py @@ -9,6 +9,7 @@ them through ``app.dependency_overrides``. """ +import re from typing import Annotated from uuid import UUID @@ -48,6 +49,10 @@ _WORKSPACE_SESSION_COOKIE = APIKeyCookie( name=WORKSPACE_SESSION_COOKIE_NAME, auto_error=False ) +_RUNTIME_CREDENTIAL_BINDING_PATH = re.compile( + r"^/api/(?:_docker/)?conversations/[0-9a-fA-F-]{36}/" + r"runtime-credential-bindings/[^/]+$" +) # Declared with ``Annotated`` so that they are required arguments: calling a @@ -124,11 +129,22 @@ def _unavailable(connection: HTTPConnection, detail: str) -> Exception: def check_session_api_key( + connection: HTTPConnection, config: Annotated[Config, Depends(get_config)], session_api_key: Annotated[str | None, Depends(_SESSION_API_KEY_HEADER)], ) -> None: """Reject the request if the supplied key is not in the current session keys.""" if config.session_api_keys and session_api_key not in config.session_api_keys: + # Docker runtimes call this one broker route with their per-runtime key. + # The route itself verifies the key against the requested conversation; + # this exception only lets that exact request reach that validation. + if ( + session_api_key is not None + and connection.scope["type"] == "http" + and connection.scope.get("method") in {"GET", "PUT"} + and _RUNTIME_CREDENTIAL_BINDING_PATH.fullmatch(connection.url.path) + ): + return raise Unauthenticated() diff --git a/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py b/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py index 8b3cab2bb91..a0c1315eea2 100644 --- a/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py +++ b/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py @@ -3,20 +3,25 @@ from __future__ import annotations import asyncio +import hmac import json +import os import subprocess from collections.abc import Callable from pathlib import Path from typing import Annotated, Any +from urllib.parse import urlsplit, urlunsplit from uuid import UUID, uuid4 import httpx -from fastapi import APIRouter, Depends, Query, Request, WebSocket +from fastapi import APIRouter, Depends, Header, Query, Request, WebSocket +from pydantic import BaseModel, ConfigDict, Field, SecretStr from starlette.responses import JSONResponse, Response, StreamingResponse from openhands.agent_server.config import Config from openhands.agent_server.conversation_registry import ConversationRegistry from openhands.agent_server.conversation_service import ConversationService +from openhands.agent_server.credential_binding import LocalVersionedCredentialBinding from openhands.agent_server.dependencies import ( get_config, get_conversation_registry, @@ -36,6 +41,7 @@ from openhands.agent_server.event_router import require_feature_enabled from openhands.agent_server.launch import ( forward_to_runtime, + is_codex_source, launch_error, launch_source, request_secrets, @@ -45,11 +51,21 @@ ConversationRuntimeInfo, ConversationRuntimeStatus, StartConversationRequest, + StoredConversation, UpdateSecretsRequest, ) from openhands.agent_server.persistence import PersistedSettings, run_store from openhands.agent_server.utils import safe_rmtree +from openhands.sdk.agent import ACPAgent +from openhands.sdk.agent.acp_file_credentials import CODEX_AUTH_SECRET_NAME +from openhands.sdk.conversation.persistence_const import BASE_STATE from openhands.sdk.conversation.request import ConversationContainerOptions +from openhands.sdk.conversation.state import ConversationState +from openhands.sdk.credential import ( + CredentialConflict, + CredentialNeedsReauthentication, + CredentialSyncError, +) from openhands.sdk.errors import ( Conflict, DomainError, @@ -57,6 +73,7 @@ Invalid, NotFound, NotSupported, + Unauthenticated, Unavailable, Unprocessable, UpstreamFailed, @@ -75,12 +92,181 @@ logger = get_logger(__name__) +_INTERNAL_SERVER_URL_ENV = "OH_INTERNAL_SERVER_URL" +_DEFAULT_INTERNAL_SERVER_URL = "http://127.0.0.1:8000" +_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1", "0.0.0.0", "::"}) + + +class RuntimeCredentialReplacement(BaseModel): + model_config = ConfigDict(extra="forbid") + + expected_version: str = Field(min_length=1, max_length=1024) + value: SecretStr + + +runtime_credential_broker_router = APIRouter( + tags=["Docker Runtime Credentials"], + include_in_schema=False, +) + + def get_registry(registry: ConversationRegistry) -> DockerConversationRegistry: if not isinstance(registry, DockerConversationRegistry): raise Unavailable("Docker conversation runtime is unavailable") return registry +async def _runtime_credential_binding( + registry: DockerConversationRegistry, + conversation_id: UUID, + secret_name: str, + api_key: str | None, +) -> LocalVersionedCredentialBinding: + """Authorize one runtime against its own host-side credential source.""" + if secret_name != CODEX_AUTH_SECRET_NAME or api_key is None: + raise Unauthenticated() + try: + identity = await run_store(registry.provisioning.load, conversation_id) + except ValueError as exc: + raise Unauthenticated() from exc + if not hmac.compare_digest(api_key, identity.api_key.get_secret_value()) or ( + identity.launched_agent_profile is not None + and not identity.launched_agent_profile.allows_secret(secret_name) + ): + raise Unauthenticated() + return LocalVersionedCredentialBinding(registry.stores.secrets, secret_name) + + +@runtime_credential_broker_router.get( + "/{conversation_id}/runtime-credential-bindings/{secret_name}" +) +async def load_runtime_credential( + conversation_id: UUID, + secret_name: str, + api_key: Annotated[str | None, Header(alias="X-Session-API-Key")] = None, + conversation_registry: ConversationRegistry = Depends(get_conversation_registry), +) -> JSONResponse: + binding = await _runtime_credential_binding( + get_registry(conversation_registry), conversation_id, secret_name, api_key + ) + try: + resolved = await binding.load() + except CredentialNeedsReauthentication as exc: + raise NotFound("Credential is missing. Please authenticate again.") from exc + except CredentialSyncError as exc: + raise UpstreamFailed("Credential store is unavailable") from exc + return JSONResponse({"value": resolved.value, "version": resolved.version}) + + +@runtime_credential_broker_router.put( + "/{conversation_id}/runtime-credential-bindings/{secret_name}" +) +async def replace_runtime_credential( + conversation_id: UUID, + secret_name: str, + replacement: RuntimeCredentialReplacement, + api_key: Annotated[str | None, Header(alias="X-Session-API-Key")] = None, + conversation_registry: ConversationRegistry = Depends(get_conversation_registry), +) -> JSONResponse: + binding = await _runtime_credential_binding( + get_registry(conversation_registry), conversation_id, secret_name, api_key + ) + try: + version = await binding.replace( + replacement.expected_version, replacement.value.get_secret_value() + ) + except CredentialConflict as exc: + raise Conflict("The canonical credential changed in another runtime") from exc + except CredentialNeedsReauthentication as exc: + raise NotFound("Credential is missing. Please authenticate again.") from exc + except CredentialSyncError as exc: + raise UpstreamFailed("Credential store is unavailable") from exc + return JSONResponse({"version": version}) + + +def _runtime_credential_url(conversation_id: UUID, secret_name: str) -> str: + """Return the outer broker URL as seen from a conversation container.""" + parsed = urlsplit(os.getenv(_INTERNAL_SERVER_URL_ENV, _DEFAULT_INTERNAL_SERVER_URL)) + hostname = parsed.hostname + if hostname in _LOOPBACK_HOSTS: + hostname = "host.docker.internal" + if hostname is None: + raise ValueError("OH_INTERNAL_SERVER_URL must be an absolute URL") + if ":" in hostname and not hostname.startswith("["): + hostname = f"[{hostname}]" + netloc = hostname + (f":{parsed.port}" if parsed.port is not None else "") + path = ( + f"/api/conversations/{conversation_id}" + f"/runtime-credential-bindings/{secret_name}" + ) + return urlunsplit((parsed.scheme, netloc, path, "", "")) + + +def _persisted_codex_binding_state( + registry: DockerConversationRegistry, conversation_id: UUID +) -> tuple[bool, bool, bool]: + """Return (is Codex, requires binding, profile allows binding).""" + conversation_dir = registry.conversation_dir(conversation_id) + context = cipher_context(registry.resolve_persisted_cipher(conversation_id)) + try: + stored = StoredConversation.model_validate_json( + (conversation_dir / "meta.json").read_text(), context=context + ) + except (OSError, ValueError): + # A failed first start can leave a provisioning identity without a + # complete conversation snapshot. The inner start remains authoritative. + return False, False, True + profile_allows = ( + stored.launched_agent_profile is None + or stored.launched_agent_profile.allows_secret(CODEX_AUTH_SECRET_NAME) + ) + required = CODEX_AUTH_SECRET_NAME in stored.required_runtime_credential_bindings + state_file = conversation_dir / BASE_STATE + if not state_file.is_file(): + return False, required, profile_allows + try: + state = ConversationState.model_validate_json( + state_file.read_text(), context=context + ) + except (OSError, ValueError): + return False, required, profile_allows + is_codex = isinstance(state.agent, ACPAgent) and state.agent.acp_server == "codex" + return is_codex, required, profile_allows + + +async def _activate_runtime_credential_bindings( + client: httpx.AsyncClient, + container: ConversationContainer, + conversation_id: UUID, + secret_names: set[str], +) -> httpx.Response | None: + for secret_name in sorted(secret_names): + response = await client.put( + f"{container.host}/api/conversations/{conversation_id}" + f"/credential-bindings/{secret_name}", + headers={"X-Session-API-Key": container.api_key}, + json={ + "url": _runtime_credential_url(conversation_id, secret_name), + "headers": {"X-Session-API-Key": container.api_key}, + }, + ) + if response.is_error: + logger.warning( + "docker_credential_binding_activation", + extra={ + "credential": secret_name, + "outcome": "rejected", + "status_code": response.status_code, + }, + ) + return response + logger.info( + "docker_credential_binding_activation", + extra={"credential": secret_name, "outcome": "success"}, + ) + return None + + async def _container( registry: DockerConversationRegistry, conversation_id: UUID ) -> ConversationContainer: @@ -145,6 +331,8 @@ async def detach() -> None: docker_conversation_router = APIRouter( prefix="/conversations", tags=["Docker Conversations"] ) +# Register the exact broker routes before the conversation catch-all below. +docker_conversation_router.include_router(runtime_credential_broker_router) def _worktree_git_paths(workspace_path: Path) -> dict[str, Path]: @@ -235,9 +423,13 @@ async def start_docker_conversation( raise Unprocessable(str(exc)) from exc release = None try: - payload, launched, options, worktree = await _prepare_forward( - body, registry, existing=existing - ) + ( + payload, + launched, + options, + worktree, + credential_bindings, + ) = await _prepare_forward(body, registry, existing=existing) identity = await run_store( registry.provisioning.create, conversation_id, host_workspace ) @@ -263,6 +455,34 @@ async def start_docker_conversation( working_dir=identity.workspace_path ).model_dump(mode="json") async with httpx.AsyncClient(timeout=60) as client: + activation_error = await _activate_runtime_credential_bindings( + client, + container, + conversation_id, + credential_bindings, + ) + if ( + existing + and activation_error is not None + and activation_error.status_code == 409 + ): + release() + release = None + await registry.stop(conversation_id) + container = await registry.get_or_create(conversation_id) + release = registry.acquire_lease(conversation_id) + activation_error = await _activate_runtime_credential_bindings( + client, + container, + conversation_id, + credential_bindings, + ) + if activation_error is not None: + if activation_error.status_code in {404, 422}: + raise Unprocessable( + "ChatGPT credential is unavailable. Please sign in again." + ) + activation_error.raise_for_status() response = await client.post( f"{container.host}/api/conversations", params={"include_skills": include_skills}, @@ -273,6 +493,10 @@ async def start_docker_conversation( raise launch_error(exc) from exc except ValueError as exc: raise Unprocessable(str(exc)) from exc + except DomainError: + if not existing: + await registry.stop(conversation_id) + raise except httpx.HTTPError as exc: if not existing: await registry.stop(conversation_id) @@ -303,6 +527,7 @@ async def _prepare_forward( LaunchedAgentProfile | None, ConversationContainerOptions | None, bool, + set[str], ]: """Resolve the start request with this host's stores; the container finalizes. @@ -334,6 +559,56 @@ async def _prepare_forward( config.cipher, ) ) + has_host_codex_credential = ( + await run_store(registry.stores.secrets.get_secret, CODEX_AUTH_SECRET_NAME) + is not None + ) + credential_bindings: set[str] = set() + is_codex_candidate = False + binding_required = False + profile_allows = True + if existing and start.conversation_id is not None: + is_codex_candidate, binding_required, profile_allows = await asyncio.to_thread( + _persisted_codex_binding_state, registry, start.conversation_id + ) + if profile_allows and ( + binding_required or (is_codex_candidate and has_host_codex_credential) + ): + credential_bindings.add(CODEX_AUTH_SECRET_NAME) + else: + allowed_secrets = ( + source.allowed_secrets if isinstance(source, ResolvedLaunch) else None + ) + is_codex_candidate = source is not None and is_codex_source(source) + profile_allows = ( + allowed_secrets is None or CODEX_AUTH_SECRET_NAME in allowed_secrets + ) + if is_codex_candidate and has_host_codex_credential and profile_allows: + credential_bindings.add(CODEX_AUTH_SECRET_NAME) + if is_codex_candidate or binding_required: + if credential_bindings: + reason = ( + "runtime_requirement" + if binding_required + else "host_credential_available" + ) + outcome = "selected" + elif not profile_allows: + reason = "profile_excluded" + outcome = "fallback" + else: + reason = "host_credential_missing" + outcome = "fallback" + logger.info( + "docker_credential_binding_selection", + extra={ + "credential": CODEX_AUTH_SECRET_NAME, + "outcome": outcome, + "reason": reason, + }, + ) + for secret_name in credential_bindings: + secrets.pop(secret_name, None) def payload(cipher: Cipher) -> dict[str, Any]: return forward_to_runtime( @@ -341,7 +616,7 @@ def payload(cipher: Cipher) -> dict[str, Any]: ) launched = source.profile if isinstance(source, ResolvedLaunch) else None - return payload, launched, start.container, start.worktree + return payload, launched, start.container, start.worktree, credential_bindings @docker_conversation_router.get( diff --git a/tests/agent_server/docker_runtime/test_mediation.py b/tests/agent_server/docker_runtime/test_mediation.py index 6a4e16b57bd..9cbb95fe545 100644 --- a/tests/agent_server/docker_runtime/test_mediation.py +++ b/tests/agent_server/docker_runtime/test_mediation.py @@ -16,6 +16,7 @@ from openhands.agent_server.launch import launch_source, target_launch_runtime from openhands.agent_server.persistence import PersistedSettings, ServerStores from openhands.sdk import LLM, Agent +from openhands.sdk.agent import ACPAgent from openhands.sdk.context import AgentContext from openhands.sdk.conversation.request import ( AgentLaunchAdditions, @@ -47,7 +48,12 @@ def _registry(runtime_config: Config) -> DockerConversationRegistry: return cast( DockerConversationRegistry, SimpleNamespace( - config=runtime_config, stores=ServerStores.from_config(runtime_config) + config=runtime_config, + stores=ServerStores.from_config(runtime_config), + conversation_dir=lambda conversation_id: ( + runtime_config.conversations_path / conversation_id.hex + ), + resolve_persisted_cipher=lambda _conversation_id: runtime_config.cipher, ), ) @@ -57,7 +63,9 @@ async def _forward( ) -> tuple[dict[str, Any], Any, RuntimeIdentity]: registry = _registry(runtime_config) body = request.model_dump(mode="json", context={"expose_secrets": True}) - payload, launched, _, _ = await _prepare_forward(body, registry, existing=existing) + payload, launched, _, _, _ = await _prepare_forward( + body, registry, existing=existing + ) provisioning = RuntimeProvisioningStore(runtime_config) identity = provisioning.create(uuid4()) return payload(identity.cipher), launched, identity @@ -73,7 +81,7 @@ async def test_forward_preserves_worktree_flag(tmp_path, monkeypatch, worktree): agent=Agent(llm=LLM(model="test", api_key=SecretStr("model-key"))), worktree=worktree, ) - payload, _, _, forwarded_worktree = await _prepare_forward( + payload, _, _, forwarded_worktree, _ = await _prepare_forward( request.model_dump(mode="json", context={"expose_secrets": True}), registry, existing=False, @@ -153,6 +161,27 @@ async def test_materializes_agent_context_secret_sources(tmp_path, monkeypatch): assert source.get_value() == "context-value" +@pytest.mark.asyncio +async def test_codex_without_host_credential_logs_plain_secret_fallback( + tmp_path, monkeypatch, caplog +): + request = StartConversationRequest( + workspace=LocalWorkspace(working_dir="/workspace"), + agent=ACPAgent(acp_command=["codex-acp"], acp_server="codex"), + ) + + with caplog.at_level("INFO"): + await _forward(request, config(tmp_path, monkeypatch)) + + record = next( + record + for record in caplog.records + if record.message == "docker_credential_binding_selection" + ) + assert record.outcome == "fallback" + assert record.reason == "host_credential_missing" + + @pytest.mark.asyncio async def test_every_encrypted_field_reaches_the_container_decryptable( tmp_path, monkeypatch @@ -173,7 +202,7 @@ async def test_every_encrypted_field_reaches_the_container_decryptable( body = request.model_dump(mode="json", context={"cipher": runtime_config.cipher}) registry = _registry(runtime_config) - payload, _, _, _ = await _prepare_forward(body, registry, existing=False) + payload, _, _, _, _ = await _prepare_forward(body, registry, existing=False) identity = RuntimeProvisioningStore(runtime_config).create(uuid4()) received = StartConversationRequest.model_validate( payload(identity.cipher), context={"cipher": identity.cipher} diff --git a/tests/agent_server/docker_runtime/test_routes.py b/tests/agent_server/docker_runtime/test_routes.py index 3d8658dabd4..770e447aee5 100644 --- a/tests/agent_server/docker_runtime/test_routes.py +++ b/tests/agent_server/docker_runtime/test_routes.py @@ -6,7 +6,7 @@ import httpx import pytest -from fastapi import FastAPI +from fastapi import APIRouter, Depends, FastAPI from fastapi.testclient import TestClient from pydantic import SecretStr from starlette.requests import Request @@ -15,6 +15,7 @@ from openhands.agent_server.api import add_domain_error_handler, create_app from openhands.agent_server.config import Config +from openhands.agent_server.dependencies import check_session_api_key from openhands.agent_server.docker_runtime import routers from openhands.agent_server.docker_runtime.provisioning import RuntimeProvisioningStore from openhands.agent_server.docker_runtime.registry import ( @@ -27,13 +28,22 @@ proxy_conversation, ) from openhands.agent_server.event_router import event_read_router -from openhands.agent_server.models import UpdateSecretsRequest +from openhands.agent_server.models import ( + StartConversationRequest, + StoredConversation, + UpdateSecretsRequest, +) from openhands.agent_server.persistence import PersistedSettings, ServerStores from openhands.agent_server.server_context import server_context_of +from openhands.sdk.agent import ACPAgent +from openhands.sdk.agent.acp_file_credentials import CODEX_AUTH_SECRET_NAME from openhands.sdk.conversation.request import ConversationContainerOptions +from openhands.sdk.conversation.state import ConversationState from openhands.sdk.git.utils import run_git_command from openhands.sdk.profiles.agent_profile import LaunchedAgentProfile -from openhands.sdk.secret import LookupSecret +from openhands.sdk.secret import LookupSecret, StaticSecret +from openhands.sdk.utils.pydantic_secrets import cipher_context, client_context +from openhands.sdk.workspace import LocalWorkspace from tests.agent_server.conftest import install_test_context @@ -63,6 +73,10 @@ def test_docker_mode_replaces_local_conversation_execution_routes(tmp_path): assert "/api/conversations/{conversation_id}/{tail:path}" in paths assert "/api/conversations/{conversation_id}/events/search" in paths assert "/api/conversations/{conversation_id}" in paths + assert ( + "/api/conversations/{conversation_id}/runtime-credential-bindings/{secret_name}" + in paths + ) assert "/api/host/bash/execute_bash_command" not in paths assert "/api/bash/execute_bash_command" in paths @@ -730,6 +744,197 @@ def _docker_start_app( return app, registry +def test_runtime_credential_broker_follows_host_rotation_and_writes_back( + tmp_path, monkeypatch +): + monkeypatch.setenv("OH_PERSISTENCE_DIR", str(tmp_path / "persistence")) + config = Config( + conversations_path=tmp_path / "conversations", + workspace_path=tmp_path / "workspaces", + secret_key=SecretStr("outer-key"), + session_api_keys=["outer-session"], + ) + registry = DockerConversationRegistry(config, ServerStores.from_config(config)) + identity = registry.provisioning.create(uuid4()) + registry.stores.secrets.set_secret(CODEX_AUTH_SECRET_NAME, "generation-0") + app = _app_with(registry, AsyncMock()) + add_domain_error_handler(app) + api_router = APIRouter(prefix="/api", dependencies=[Depends(check_session_api_key)]) + api_router.include_router( + routers.runtime_credential_broker_router, prefix="/conversations" + ) + app.include_router(api_router) + path = ( + f"/api/conversations/{identity.conversation_id}/" + f"runtime-credential-bindings/{CODEX_AUTH_SECRET_NAME}" + ) + headers = {"X-Session-API-Key": identity.api_key.get_secret_value()} + + with TestClient(app) as client: + initial = client.get(path, headers=headers) + registry.stores.secrets.set_secret( + CODEX_AUTH_SECRET_NAME, "generation-from-another-conversation" + ) + current = client.get(path, headers=headers) + writeback = client.put( + path, + headers=headers, + json={ + "expected_version": current.json()["version"], + "value": "generation-from-this-runtime", + }, + ) + rejected = client.get( + path, headers={"X-Session-API-Key": "another-runtime-key"} + ) + + assert initial.status_code == 200 + assert initial.json()["value"] == "generation-0" + assert current.status_code == 200 + assert current.json()["value"] == "generation-from-another-conversation" + assert current.json()["version"] != initial.json()["version"] + assert writeback.status_code == 200 + assert registry.stores.secrets.get_secret(CODEX_AUTH_SECRET_NAME) == ( + "generation-from-this-runtime" + ) + assert rejected.status_code == 401 + + +def test_docker_codex_start_activates_host_binding_before_forwarding( + tmp_path, monkeypatch, caplog +): + monkeypatch.setenv("OH_INTERNAL_SERVER_URL", "http://127.0.0.1:8123") + app, registry = _docker_start_app(tmp_path, monkeypatch) + conversation_id = uuid4() + registry.stores.secrets.set_secret(CODEX_AUTH_SECRET_NAME, "canonical") + calls: list[tuple[str, str, dict]] = [] + + async def get_or_create(_conversation_id): + identity = registry.provisioning.load(conversation_id) + return SimpleNamespace( + host="http://inner", + api_key=identity.api_key.get_secret_value(), + ) + + async def put(self, url, **kwargs): + calls.append(("PUT", url, kwargs)) + return httpx.Response(204, request=httpx.Request("PUT", url)) + + async def post(self, url, **kwargs): + calls.append(("POST", url, kwargs)) + return httpx.Response( + 201, + json={"id": str(conversation_id)}, + request=httpx.Request("POST", url), + ) + + monkeypatch.setattr(registry, "get_or_create", get_or_create) + monkeypatch.setattr(httpx.AsyncClient, "put", put) + monkeypatch.setattr(httpx.AsyncClient, "post", post) + agent = ACPAgent(acp_command=["codex-acp"], acp_server="codex") + + with caplog.at_level("INFO"): + with TestClient(app) as client: + response = client.post( + "/api/conversations", + json={ + "conversation_id": str(conversation_id), + "agent": agent.model_dump(mode="json"), + "secrets": { + CODEX_AUTH_SECRET_NAME: StaticSecret( + value=SecretStr("request-snapshot") + ).model_dump(mode="json", context=client_context("plaintext")) + }, + }, + ) + + assert response.status_code == 201 + assert [method for method, _, _ in calls] == ["PUT", "POST"] + activation = calls[0] + identity = registry.provisioning.load(conversation_id) + assert activation[1] == ( + "http://inner/api/conversations/" + f"{conversation_id}/credential-bindings/{CODEX_AUTH_SECRET_NAME}" + ) + assert activation[2]["json"] == { + "url": ( + "http://host.docker.internal:8123/api/conversations/" + f"{conversation_id}/runtime-credential-bindings/{CODEX_AUTH_SECRET_NAME}" + ), + "headers": { + "X-Session-API-Key": identity.api_key.get_secret_value(), + }, + } + forwarded = StartConversationRequest.model_validate( + calls[1][2]["json"], context=cipher_context(identity.cipher) + ) + assert CODEX_AUTH_SECRET_NAME not in forwarded.secrets + assert "docker_credential_binding_selection" in caplog.text + assert "docker_credential_binding_activation" in caplog.text + + +def test_existing_docker_codex_resume_reactivates_current_host_binding( + tmp_path, monkeypatch +): + monkeypatch.setenv("OH_INTERNAL_SERVER_URL", "http://127.0.0.1:8123") + app, registry = _docker_start_app(tmp_path, monkeypatch) + conversation_id = uuid4() + identity = registry.provisioning.create(conversation_id) + conversation_dir = registry.conversation_dir(conversation_id) + conversation_dir.mkdir(parents=True, exist_ok=True) + workspace = LocalWorkspace(working_dir=identity.workspace_path) + stored = StoredConversation(id=conversation_id, workspace=workspace) + (conversation_dir / "meta.json").write_text( + stored.model_dump_json(context=cipher_context(identity.cipher)) + ) + ConversationState.create( + id=conversation_id, + agent=ACPAgent(acp_command=["codex-acp"], acp_server="codex"), + workspace=workspace, + persistence_dir=str(conversation_dir), + cipher=identity.cipher, + ) + registry.stores.secrets.set_secret(CODEX_AUTH_SECRET_NAME, "rotated-on-the-host") + calls: list[tuple[str, str, dict]] = [] + + async def get_or_create(_conversation_id): + return SimpleNamespace( + host="http://inner", + api_key=identity.api_key.get_secret_value(), + ) + + async def put(self, url, **kwargs): + calls.append(("PUT", url, kwargs)) + return httpx.Response(204, request=httpx.Request("PUT", url)) + + async def post(self, url, **kwargs): + calls.append(("POST", url, kwargs)) + return httpx.Response( + 200, + json={"id": str(conversation_id)}, + request=httpx.Request("POST", url), + ) + + monkeypatch.setattr(registry, "get_or_create", get_or_create) + monkeypatch.setattr(httpx.AsyncClient, "put", put) + monkeypatch.setattr(httpx.AsyncClient, "post", post) + + with TestClient(app) as client: + response = client.post( + "/api/conversations", + json={ + "conversation_id": str(conversation_id), + "agent_profile_id": str(uuid4()), + }, + ) + + assert response.status_code == 200 + assert [method for method, _, _ in calls] == ["PUT", "POST"] + assert calls[0][1].endswith( + f"/{conversation_id}/credential-bindings/{CODEX_AUTH_SECRET_NAME}" + ) + + @pytest.mark.parametrize("existing", [False, True]) def test_a_rejected_start_stops_only_a_container_it_created( tmp_path, monkeypatch, existing From 20b3204c6a41fc79c22a4e120934256d2e01fa75 Mon Sep 17 00:00:00 2001 From: Vietpr Date: Wed, 25 Nov 2026 21:38:44 +0700 Subject: [PATCH 2/2] fix(agent-server): preserve active Docker turns --- .../agent_server/docker_runtime/registry.py | 4 + .../agent_server/docker_runtime/routers.py | 49 ++++++- .../docker_runtime/test_routes.py | 122 +++++++++++++++++- 3 files changed, 172 insertions(+), 3 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/docker_runtime/registry.py b/openhands-agent-server/openhands/agent_server/docker_runtime/registry.py index 800def79f37..bc83fbb3e88 100644 --- a/openhands-agent-server/openhands/agent_server/docker_runtime/registry.py +++ b/openhands-agent-server/openhands/agent_server/docker_runtime/registry.py @@ -323,6 +323,10 @@ def cleanup_stale_containers(self) -> None: def has_active_leases(self, conversation_id: UUID) -> bool: return self._leases.get(conversation_id, 0) > 0 + def idle_token(self, conversation_id: UUID) -> int: + """Snapshot runtime activity for a later ``stop_if_idle`` call.""" + return self._lease_generations.get(conversation_id, 0) + def release_lease(self, conversation_id: UUID) -> None: """Release a previously acquired lease on a container runtime.""" count = self._leases.get(conversation_id, 0) - 1 diff --git a/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py b/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py index a0c1315eea2..9e60b4ea9a6 100644 --- a/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py +++ b/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py @@ -60,7 +60,10 @@ from openhands.sdk.agent.acp_file_credentials import CODEX_AUTH_SECRET_NAME from openhands.sdk.conversation.persistence_const import BASE_STATE from openhands.sdk.conversation.request import ConversationContainerOptions -from openhands.sdk.conversation.state import ConversationState +from openhands.sdk.conversation.state import ( + ConversationExecutionStatus, + ConversationState, +) from openhands.sdk.credential import ( CredentialConflict, CredentialNeedsReauthentication, @@ -95,6 +98,15 @@ _INTERNAL_SERVER_URL_ENV = "OH_INTERNAL_SERVER_URL" _DEFAULT_INTERNAL_SERVER_URL = "http://127.0.0.1:8000" _LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1", "0.0.0.0", "::"}) +_CREDENTIAL_RESTART_SAFE_STATUSES = frozenset( + { + ConversationExecutionStatus.IDLE, + ConversationExecutionStatus.PAUSED, + ConversationExecutionStatus.FINISHED, + ConversationExecutionStatus.ERROR, + ConversationExecutionStatus.STUCK, + } +) class RuntimeCredentialReplacement(BaseModel): @@ -234,6 +246,23 @@ def _persisted_codex_binding_state( return is_codex, required, profile_allows +def _persisted_execution_status( + registry: DockerConversationRegistry, conversation_id: UUID +) -> ConversationExecutionStatus | None: + """Read the latest durable status before replacing a legacy runtime.""" + state_file = registry.conversation_dir(conversation_id) / BASE_STATE + if not state_file.is_file(): + return None + context = cipher_context(registry.resolve_persisted_cipher(conversation_id)) + try: + state = ConversationState.model_validate_json( + state_file.read_text(), context=context + ) + except (OSError, ValueError): + return None + return state.execution_status + + async def _activate_runtime_credential_bindings( client: httpx.AsyncClient, container: ConversationContainer, @@ -466,9 +495,25 @@ async def start_docker_conversation( and activation_error is not None and activation_error.status_code == 409 ): + execution_status = await asyncio.to_thread( + _persisted_execution_status, registry, conversation_id + ) + if execution_status not in _CREDENTIAL_RESTART_SAFE_STATUSES: + raise Conflict( + "Conversation is active; retry credential sync when it is idle" + ) + idle_token = registry.idle_token(conversation_id) release() release = None - await registry.stop(conversation_id) + stopped = await registry.stop_if_idle( + conversation_id, + idle_token, + container=container, + ) + if not stopped: + raise Conflict( + "Runtime is in use; retry credential sync when it is idle" + ) container = await registry.get_or_create(conversation_id) release = registry.acquire_lease(conversation_id) activation_error = await _activate_runtime_credential_bindings( diff --git a/tests/agent_server/docker_runtime/test_routes.py b/tests/agent_server/docker_runtime/test_routes.py index 770e447aee5..9df91567062 100644 --- a/tests/agent_server/docker_runtime/test_routes.py +++ b/tests/agent_server/docker_runtime/test_routes.py @@ -38,7 +38,10 @@ from openhands.sdk.agent import ACPAgent from openhands.sdk.agent.acp_file_credentials import CODEX_AUTH_SECRET_NAME from openhands.sdk.conversation.request import ConversationContainerOptions -from openhands.sdk.conversation.state import ConversationState +from openhands.sdk.conversation.state import ( + ConversationExecutionStatus, + ConversationState, +) from openhands.sdk.git.utils import run_git_command from openhands.sdk.profiles.agent_profile import LaunchedAgentProfile from openhands.sdk.secret import LookupSecret, StaticSecret @@ -744,6 +747,30 @@ def _docker_start_app( return app, registry +def _persist_codex_conversation( + registry: DockerConversationRegistry, + conversation_id, + execution_status: ConversationExecutionStatus = ConversationExecutionStatus.IDLE, +): + identity = registry.provisioning.create(conversation_id) + conversation_dir = registry.conversation_dir(conversation_id) + conversation_dir.mkdir(parents=True, exist_ok=True) + workspace = LocalWorkspace(working_dir=identity.workspace_path) + stored = StoredConversation(id=conversation_id, workspace=workspace) + (conversation_dir / "meta.json").write_text( + stored.model_dump_json(context=cipher_context(identity.cipher)) + ) + state = ConversationState.create( + id=conversation_id, + agent=ACPAgent(acp_command=["codex-acp"], acp_server="codex"), + workspace=workspace, + persistence_dir=str(conversation_dir), + cipher=identity.cipher, + ) + state.execution_status = execution_status + return identity + + def test_runtime_credential_broker_follows_host_rotation_and_writes_back( tmp_path, monkeypatch ): @@ -935,6 +962,99 @@ async def post(self, url, **kwargs): ) +def test_legacy_binding_conflict_does_not_restart_an_active_turn(tmp_path, monkeypatch): + app, registry = _docker_start_app(tmp_path, monkeypatch) + conversation_id = uuid4() + identity = _persist_codex_conversation( + registry, conversation_id, ConversationExecutionStatus.RUNNING + ) + registry.stores.secrets.set_secret(CODEX_AUTH_SECRET_NAME, "rotated-on-the-host") + container = SimpleNamespace( + host="http://inner", api_key=identity.api_key.get_secret_value() + ) + registry.stop_if_idle = AsyncMock() + + monkeypatch.setattr(registry, "get_or_create", AsyncMock(return_value=container)) + monkeypatch.setattr( + httpx.AsyncClient, + "put", + AsyncMock( + return_value=httpx.Response( + 409, request=httpx.Request("PUT", "http://inner/credential-binding") + ) + ), + ) + post = AsyncMock() + monkeypatch.setattr(httpx.AsyncClient, "post", post) + + with TestClient(app) as client: + response = client.post( + "/api/conversations", + json={ + "conversation_id": str(conversation_id), + "agent_profile_id": str(uuid4()), + }, + ) + + assert response.status_code == 409 + registry.stop_if_idle.assert_not_awaited() + post.assert_not_awaited() + + +@pytest.mark.parametrize("runtime_busy", [False, True]) +def test_legacy_binding_conflict_restarts_only_an_idle_runtime( + tmp_path, monkeypatch, runtime_busy +): + app, registry = _docker_start_app(tmp_path, monkeypatch) + conversation_id = uuid4() + identity = _persist_codex_conversation(registry, conversation_id) + registry.stores.secrets.set_secret(CODEX_AUTH_SECRET_NAME, "rotated-on-the-host") + old_container = SimpleNamespace( + host="http://old-inner", api_key=identity.api_key.get_secret_value() + ) + new_container = SimpleNamespace( + host="http://new-inner", api_key=identity.api_key.get_secret_value() + ) + get_or_create = AsyncMock(side_effect=[old_container, new_container]) + stop_if_idle = AsyncMock(return_value=not runtime_busy) + put_responses = iter([409, 204]) + + async def put(self, url, **kwargs): + status_code = next(put_responses) + return httpx.Response(status_code, request=httpx.Request("PUT", url)) + + post = AsyncMock( + return_value=httpx.Response( + 200, + json={"id": str(conversation_id)}, + request=httpx.Request("POST", "http://new-inner/api/conversations"), + ) + ) + monkeypatch.setattr(registry, "get_or_create", get_or_create) + monkeypatch.setattr(registry, "stop_if_idle", stop_if_idle) + monkeypatch.setattr(httpx.AsyncClient, "put", put) + monkeypatch.setattr(httpx.AsyncClient, "post", post) + + with TestClient(app) as client: + response = client.post( + "/api/conversations", + json={ + "conversation_id": str(conversation_id), + "agent_profile_id": str(uuid4()), + }, + ) + + stop_if_idle.assert_awaited_once_with(conversation_id, 1, container=old_container) + if runtime_busy: + assert response.status_code == 409 + assert get_or_create.await_count == 1 + post.assert_not_awaited() + else: + assert response.status_code == 200 + assert get_or_create.await_count == 2 + post.assert_awaited_once() + + @pytest.mark.parametrize("existing", [False, True]) def test_a_rejected_start_stops_only_a_container_it_created( tmp_path, monkeypatch, existing