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
70 changes: 32 additions & 38 deletions openhands-sdk/openhands/sdk/agent/acp_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,21 @@
# Env vars that must be removed from the subprocess environment when a
# particular "dominant" env var is present.
#
# Rationale: some auth mechanisms are mutually exclusive and their env vars
# conflict. For example, CLAUDE_CONFIG_DIR activates Claude Code's OAuth
# credential-file flow. If ANTHROPIC_API_KEY or ANTHROPIC_BASE_URL are
# also present they redirect requests to a different endpoint (e.g. a proxy)
# that doesn't support OAuth bearer tokens, breaking authentication silently.
# When CLAUDE_CONFIG_DIR is detected we strip the conflicting vars so the
# subprocess can reach api.anthropic.com with its own OAuth token.
# Rationale: Claude Code's subscription auth uses CLAUDE_CODE_OAUTH_TOKEN, a
# bearer validated against api.anthropic.com. A co-present ANTHROPIC_API_KEY
# would take precedence over the token (silently bypassing the subscription),
# and an ANTHROPIC_BASE_URL would route the bearer to a proxy that rejects it —
# either silently breaks the intended OAuth auth. When the OAuth token is the
# active credential we strip both so the subprocess authenticates with the
# token against api.anthropic.com.
#
# Keyed on the credential itself (CLAUDE_CODE_OAUTH_TOKEN), NOT on
# CLAUDE_CONFIG_DIR: the config dir is a *location* lever (data-dir isolation,
# #1019) that is orthogonal to which credential is active. Keying the strip on
# it wrongly fired during API-key isolation and missed the conflict when the
# token arrived via env without isolation (#3588).
_ENV_CONFLICT_MAP: dict[str, frozenset[str]] = {
"CLAUDE_CONFIG_DIR": frozenset({"ANTHROPIC_API_KEY", "ANTHROPIC_BASE_URL"}),
"CLAUDE_CODE_OAUTH_TOKEN": frozenset({"ANTHROPIC_API_KEY", "ANTHROPIC_BASE_URL"}),
}

# Number of trailing characters of an ACP session id retained in log lines
Expand Down Expand Up @@ -1886,14 +1892,12 @@ def _isolate_acp_data_dir(
highest precedence and is honoured as the materialisation target too), so
leave it untouched.

Claude carve-out: ``CLAUDE_CONFIG_DIR`` also activates Claude Code's
OAuth credential-file flow, and :data:`_ENV_CONFLICT_MAP` then strips
``ANTHROPIC_API_KEY`` / ``ANTHROPIC_BASE_URL``. Relocating it while an API
key is the active credential (no OAuth token present) would delete a
working key + proxy URL and break auth, so skip Claude in that case;
codex/gemini have no such coupling. (Claude's transcripts are already
cwd-keyed, so the residual shared state is the mostly-inert global
config.)
Claude note: relocating ``CLAUDE_CONFIG_DIR`` is safe under either auth
mode. :data:`_ENV_CONFLICT_MAP` is keyed on the OAuth token
(``CLAUDE_CODE_OAUTH_TOKEN``), not on ``CLAUDE_CONFIG_DIR``, so setting
the config dir for isolation no longer strips a working
``ANTHROPIC_API_KEY`` — API-key Claude gets the same per-conversation
isolation (and pause/resume continuity) as OAuth Claude (#3588).

``HOME`` (gemini-cli's only lever — it hard-codes ``~/.gemini`` and
ignores ``XDG``) has a wider blast radius than the surgical
Expand All @@ -1904,26 +1908,18 @@ def _isolate_acp_data_dir(
need a narrower scope can pin ``HOME`` via ``acp_env`` (honoured below)
or leave isolation off for Gemini.

Ordering contract: this runs *after* the ``secret_registry`` injection
and the ``acp_env`` update in :meth:`_start_acp_server`, so the
credential vars it inspects (``ANTHROPIC_API_KEY`` /
``CLAUDE_CODE_OAUTH_TOKEN``) are already hydrated into ``env``. Calling it
earlier would misread the active credential and wrongly relocate Claude.
Ordering: this runs *after* the ``secret_registry`` injection and the
``acp_env`` update in :meth:`_start_acp_server` so an ``acp_env`` pin of
the data-dir var is visible and wins. Relocation is now credential-blind
(the auth-conflict strip is keyed on ``CLAUDE_CODE_OAUTH_TOKEN``, not on
the config dir), so the data-dir var it sets never affects auth.
"""
provider = detect_acp_provider_by_command(self.acp_command)
if provider is None or provider.data_dir_env_var is None:
return
env_var = provider.data_dir_env_var
if env_var in self.acp_env:
return
# Relies on the ordering contract above: ANTHROPIC_API_KEY /
# CLAUDE_CODE_OAUTH_TOKEN must already be hydrated into env.
if (
env_var == "CLAUDE_CONFIG_DIR"
and env.get("ANTHROPIC_API_KEY")
and "CLAUDE_CODE_OAUTH_TOKEN" not in env
):
return
data_dir = self._acp_file_secret_dir(state, provider.key)
data_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
env[env_var] = str(data_dir)
Expand Down Expand Up @@ -2091,18 +2087,16 @@ def _start_acp_server(self, state: ConversationState) -> None:

# Relocate the CLI's data/config root to a per-conversation directory so
# sandbox-sharing conversations don't race on a shared HOME (#1019).
# Ordering is load-bearing — this must run AFTER the registry /
# registry injection and the acp_env update above (so the credential
# vars its Claude carve-out inspects — ANTHROPIC_API_KEY /
# CLAUDE_CODE_OAUTH_TOKEN — are already in env, and an acp_env pin wins)
# and BEFORE the conflict-strip below (so a CLAUDE_CONFIG_DIR it sets is
# still subject to the strip).
# Runs after the registry injection and the acp_env update above so an
# acp_env pin of the data-dir var wins. Independent of the strip below
# (keyed on the OAuth token, not the data-dir var), so ordering relative
# to it no longer matters for correctness.
if self.acp_isolate_data_dir:
self._isolate_acp_data_dir(state, env)

# Strip env vars that conflict with an active auth mechanism.
# E.g. CLAUDE_CONFIG_DIR (OAuth credential file) conflicts with
# ANTHROPIC_API_KEY / ANTHROPIC_BASE_URL (API-key + proxy auth).
# Strip env vars that conflict with an active auth mechanism: an active
# CLAUDE_CODE_OAUTH_TOKEN must not coexist with ANTHROPIC_API_KEY (which
# takes precedence) or ANTHROPIC_BASE_URL (proxies the bearer). See #3588.
for dominant, conflicts in _ENV_CONFLICT_MAP.items():
if dominant in env:
for conflict in conflicts:
Expand Down
81 changes: 50 additions & 31 deletions tests/sdk/agent/test_acp_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -6585,15 +6585,16 @@ def test_agent_context_secret_overrides_ambient_os_environ(self, tmp_path):


class TestACPEnvConflictSuppression:
"""CLAUDE_CONFIG_DIR OAuth auth must not coexist with API-key env vars.
"""An active CLAUDE_CODE_OAUTH_TOKEN must not coexist with API-key env vars.

When CLAUDE_CONFIG_DIR is present in the subprocess environment the agent
uses a credential file for OAuth. If ANTHROPIC_API_KEY or
ANTHROPIC_BASE_URL are also present they redirect requests to a proxy that
does not support OAuth bearer tokens, breaking auth silently.
When CLAUDE_CODE_OAUTH_TOKEN is present the subprocess authenticates with
that bearer against api.anthropic.com. A co-present ANTHROPIC_API_KEY would
take precedence (bypassing the subscription) and an ANTHROPIC_BASE_URL would
route the bearer to a proxy that rejects it, breaking auth silently.

_start_acp_server must strip the conflicting vars regardless of where they
came from: acp_env, os.environ, secret_registry, or agent_context.secrets.
The strip is keyed on the token, not on CLAUDE_CONFIG_DIR (#3588).
"""

@staticmethod
Expand Down Expand Up @@ -6677,25 +6678,25 @@ async def _fake_filter(_src, _dst):

return captured

def test_claude_config_dir_suppresses_api_key_from_acp_env(self, tmp_path):
"""ANTHROPIC_API_KEY from acp_env is stripped when CLAUDE_CONFIG_DIR present."""
def test_oauth_token_suppresses_api_key_from_acp_env(self, tmp_path):
"""ANTHROPIC_API_KEY from acp_env is stripped when the OAuth token is set."""
agent = _make_agent(
acp_env={
"CLAUDE_CONFIG_DIR": "/tmp/claude-creds",
"CLAUDE_CODE_OAUTH_TOKEN": "oauth-tok",
"ANTHROPIC_API_KEY": "sk-conflict",
"ANTHROPIC_BASE_URL": "https://proxy.example.com",
}
)
env = self._run_start_capturing_env(agent, tmp_path)

assert env["CLAUDE_CONFIG_DIR"] == "/tmp/claude-creds"
assert env["CLAUDE_CODE_OAUTH_TOKEN"] == "oauth-tok"
assert "ANTHROPIC_API_KEY" not in env
assert "ANTHROPIC_BASE_URL" not in env

def test_claude_config_dir_suppresses_api_key_from_os_environ(self, tmp_path):
def test_oauth_token_suppresses_api_key_from_os_environ(self, tmp_path):
"""ANTHROPIC_API_KEY leaking in from os.environ is stripped too."""
agent = _make_agent(
acp_env={"CLAUDE_CONFIG_DIR": "/tmp/claude-creds"},
acp_env={"CLAUDE_CODE_OAUTH_TOKEN": "oauth-tok"},
)
env = self._run_start_capturing_env(
agent,
Expand All @@ -6706,46 +6707,45 @@ def test_claude_config_dir_suppresses_api_key_from_os_environ(self, tmp_path):
},
)

assert "CLAUDE_CONFIG_DIR" in env
assert "CLAUDE_CODE_OAUTH_TOKEN" in env
assert "ANTHROPIC_API_KEY" not in env
assert "ANTHROPIC_BASE_URL" not in env

def test_claude_config_dir_suppresses_api_key_from_registry(self, tmp_path):
"""ANTHROPIC_API_KEY injected via secret_registry is stripped too.
def test_oauth_token_suppresses_api_key_from_registry(self, tmp_path):
"""The token + conflicting vars all injected via secret_registry.

This is the channel provider creds now travel on (folded into
``agent_context.secrets`` by ``create_agent`` → lifted into the
registry by ``create_request``).
"""
agent = _make_agent(
acp_env={"CLAUDE_CONFIG_DIR": "/tmp/claude-creds"},
)
agent = _make_agent()
env = self._run_start_capturing_env(
agent,
tmp_path,
registry_secrets={
"CLAUDE_CODE_OAUTH_TOKEN": "oauth-from-registry",
"ANTHROPIC_API_KEY": "sk-from-registry",
"ANTHROPIC_BASE_URL": "https://proxy.example.com",
},
)

assert "CLAUDE_CONFIG_DIR" in env
assert env["CLAUDE_CODE_OAUTH_TOKEN"] == "oauth-from-registry"
assert "ANTHROPIC_API_KEY" not in env
assert "ANTHROPIC_BASE_URL" not in env

def test_claude_config_dir_suppresses_api_key_from_secrets(self, tmp_path):
"""ANTHROPIC_API_KEY drained from agent_context.secrets is stripped too.
def test_oauth_token_suppresses_api_key_from_secrets(self, tmp_path):
"""Conflicting vars drained from agent_context.secrets are stripped too.

Covers the canvas-local channel: provider creds folded into
``agent_context.secrets`` reach env via the drain, and must still be
stripped when CLAUDE_CONFIG_DIR is active.
stripped when the OAuth token is active.
"""
from pydantic import SecretStr

from openhands.sdk.secret import StaticSecret

agent = _make_agent(
acp_env={"CLAUDE_CONFIG_DIR": "/tmp/claude-creds"},
acp_env={"CLAUDE_CODE_OAUTH_TOKEN": "oauth-tok"},
agent_context=AgentContext(
secrets={
"ANTHROPIC_API_KEY": StaticSecret(
Expand All @@ -6760,19 +6760,35 @@ def test_claude_config_dir_suppresses_api_key_from_secrets(self, tmp_path):
with pytest.warns(DeprecationWarning, match=r"ACPAgent\.acp_env"):
env = self._run_start_capturing_env(agent, tmp_path)

assert "CLAUDE_CONFIG_DIR" in env
assert "CLAUDE_CODE_OAUTH_TOKEN" in env
assert "ANTHROPIC_API_KEY" not in env
assert "ANTHROPIC_BASE_URL" not in env

def test_no_suppression_without_claude_config_dir(self, tmp_path):
"""Without CLAUDE_CONFIG_DIR, ANTHROPIC_API_KEY passes through unchanged."""
def test_no_suppression_without_oauth_token(self, tmp_path):
"""Without the OAuth token, ANTHROPIC_API_KEY passes through unchanged."""
agent = _make_agent(
acp_env={"ANTHROPIC_API_KEY": "sk-valid"},
)
env = self._run_start_capturing_env(agent, tmp_path)

assert env.get("ANTHROPIC_API_KEY") == "sk-valid"
assert "CLAUDE_CONFIG_DIR" not in env
assert "CLAUDE_CODE_OAUTH_TOKEN" not in env

def test_config_dir_alone_does_not_suppress_api_key(self, tmp_path):
"""Regression (#3588): CLAUDE_CONFIG_DIR without the OAuth token must NOT
strip ANTHROPIC_API_KEY. The config dir is a location lever (data-dir
isolation), orthogonal to auth mode — keying the strip on it used to
delete a working API key during isolation."""
agent = _make_agent(
acp_env={
"CLAUDE_CONFIG_DIR": "/tmp/claude-isolated",
"ANTHROPIC_API_KEY": "sk-valid",
}
)
env = self._run_start_capturing_env(agent, tmp_path)

assert env["CLAUDE_CONFIG_DIR"] == "/tmp/claude-isolated"
assert env.get("ANTHROPIC_API_KEY") == "sk-valid"


class TestACPAgentCurrentModelIdProperty:
Expand Down Expand Up @@ -7650,23 +7666,26 @@ def test_composes_with_materialised_codex_auth(self, tmp_path):
encoding="utf-8"
) == '{"tokens": "x"}'

# --- Claude carve-out: must not knock out an active API key --------------
# --- Claude: isolation applies under either auth mode (#3588) ------------

def test_claude_skips_when_api_key_active(self, tmp_path):
def test_claude_isolates_under_api_key(self, tmp_path):
from openhands.sdk.secret import StaticSecret

agent = self._agent(["npx", "-y", "@agentclientprotocol/claude-agent-acp"])
state = self._H._state(tmp_path)
persist = state.persistence_dir
assert persist is not None
state.secret_registry.update_secrets(
{"ANTHROPIC_API_KEY": StaticSecret(value=SecretStr("sk-live"))}
)
with patch.dict("os.environ", {}, clear=True):
env = self._H._run_start(
agent, state, conn=self._H._make_conn(agent_name="claude-agent-acp")
)
# Setting CLAUDE_CONFIG_DIR would trip _ENV_CONFLICT_MAP and strip the
# key, so isolation is skipped and the working key survives.
assert "CLAUDE_CONFIG_DIR" not in env
# #3588: the conflict strip is keyed on CLAUDE_CODE_OAUTH_TOKEN, not on
# CLAUDE_CONFIG_DIR, so relocating the data dir no longer strips a working
# API key — API-key Claude gets the same per-conversation isolation.
assert Path(env["CLAUDE_CONFIG_DIR"]) == Path(persist) / "acp" / "claude-code"
assert env["ANTHROPIC_API_KEY"] == "sk-live"

def test_claude_isolates_under_oauth_token(self, tmp_path):
Expand Down
Loading