Skip to content

fix(acp): route provider creds through secret_registry; deprecate acp_env - #3464

Merged
simonrosenberg merged 7 commits into
mainfrom
fix-acp-route-creds-via-secret-registry
Jun 2, 2026
Merged

simonrosenberg merged 7 commits into
mainfrom
fix-acp-route-creds-via-secret-registry

Conversation

@simonrosenberg

@simonrosenberg simonrosenberg commented Jun 2, 2026 •

Copy link
Copy Markdown
Member

Problem

ACP folds provider credentials (llm.api_key/base_url) into acp_env, which is persisted inside agent_settings. SaaS stores dump agent_settings via model_dump(mode='json') with no cipher context, so acp_env is redacted to ********** at persist — silently dropping cloud-injected creds. acp_env is also not masked in subprocess output. The regular agent flows credentials through state.secret_registry — the cipher-protected channel that round-trips across the StartConversationRequest boundary.

What this PR does

1. Re-route provider creds onto agent_context.secrets (at-rest fix)

ACPAgentSettings.create_agent() folds provider creds (api_key→api_key_env_var, base_url→base_url_env_var) into agent_context.secrets (wrapped as StaticSecret) instead of acp_env. There they ride the StoredConversation.secrets + agent-server Cipher boundary like the LLM api_key, so they're no longer redacted at persist. resolve_acp_env() no longer folds provider env in — it returns only the user's explicit acp_env.

2. Keep the agent_context.secrets → env drain

_start_acp_server still injects agent_context.secrets into the subprocess env (fill-if-absent, after the state.secret_registry loop). This is required, not legacy:

  • An ACP subprocess is a black box the SDK can't name-scan per command (unlike the regular agent's bash tool), so credentials must be injected upfront.
  • It's the only channel that delivers creds on paths that don't call the Python create_request lift — notably canvas-local, which builds the request in TypeScript and relies on the server's create_agent() to fold llm.api_key into agent_context.secrets. The agent-server seeds the registry only from request.secrets (no server-side agent_context.secrets→registry merge), so without the drain the canvas provider key would never reach the CLI.
  • On the OpenHands cloud path the creds are already in the registry (via the create_request lift), so the drain skips them — no double-injection.

3. Deprecate acp_env (deprecated_in=1.24.0, removed_in=1.29.0)

Now that creds flow through the registry, acp_env is a redundant, persist-unsafe channel. warn_deprecated("ACPAgentSettings.acp_env" / "ACPAgent.acp_env", …) fires once per code path when a non-empty acp_env is used; empty acp_env is silent and the field still works. This registers the qualified-name deprecation metadata that check_sdk_api_breakage.py requires (5-minor-release runway) so a follow-up PR can delete acp_env cleanly at ≥1.29.0. (skip-acp-check doesn't cover field removals, and the checker reads the runway from the baseline release — so it must be added now.) Schema unchanged → canvas / ts-client / OpenHands unaffected; non-breaking.

Validation (real API calls)

Validated end-to-end against claude-agent-acp through the eval LLM proxy, on both request-build paths, with the provider key not in acp_env or os.environ:

  • OpenHands path (create_agent → create_request → request.secrets → registry): real call returns the correct answer.
  • Canvas path (key only in agent_context.secrets, registry empty, no create_request): the restored drain delivers the key → real call succeeds. (This is the path an earlier drain-removal regressed; now fixed + verified.)
  • Negative control: a broken key returns 401 Invalid proxy server token — proving the registry/drain-injected creds are what authenticate (not a cached login).

Fixes a correctness bug by construction

Moving creds off acp_env onto agent_context.secrets eliminates the cloud at-rest drop (saas_settings_store.py:130-131). On agent_context.secrets they ride the Cipher boundary like the LLM api_key.

Already on main (no work here)

Backend builder collapse — _acp_provider_env / _SERVER_KEY_MAP / _sdk_supports_acp_secrets gone; the ACP path builds via create_agent() + create_request; the old silent llm= / base_url bugs are fixed (#14401).


Implements pre-cloud refactor P0-1 of OpenHands/agent-canvas#2113. Part of OpenHands/OpenHands#15746. Deleting acp_env entirely is the deferred follow-up (now unblocked by the deprecation). Pairs with file-secret materialisation (OpenHands/agent-canvas#2115).

🤖 Generated with Claude Code


Agent Server images for this PR

• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server

Variants & Base Images

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python amd64, arm64 nikolaik/python-nodejs:python3.13-nodejs22-slim Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:2699452-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-2699452-python \
  ghcr.io/openhands/agent-server:2699452-python

All tags pushed for this build

ghcr.io/openhands/agent-server:2699452-golang-amd64
ghcr.io/openhands/agent-server:26994524505e829ec32221312371c5b7594a3012-golang-amd64
ghcr.io/openhands/agent-server:fix-acp-route-creds-via-secret-registry-golang-amd64
ghcr.io/openhands/agent-server:2699452-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:2699452-golang-arm64
ghcr.io/openhands/agent-server:26994524505e829ec32221312371c5b7594a3012-golang-arm64
ghcr.io/openhands/agent-server:fix-acp-route-creds-via-secret-registry-golang-arm64
ghcr.io/openhands/agent-server:2699452-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:2699452-java-amd64
ghcr.io/openhands/agent-server:26994524505e829ec32221312371c5b7594a3012-java-amd64
ghcr.io/openhands/agent-server:fix-acp-route-creds-via-secret-registry-java-amd64
ghcr.io/openhands/agent-server:2699452-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:2699452-java-arm64
ghcr.io/openhands/agent-server:26994524505e829ec32221312371c5b7594a3012-java-arm64
ghcr.io/openhands/agent-server:fix-acp-route-creds-via-secret-registry-java-arm64
ghcr.io/openhands/agent-server:2699452-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:2699452-python-amd64
ghcr.io/openhands/agent-server:26994524505e829ec32221312371c5b7594a3012-python-amd64
ghcr.io/openhands/agent-server:fix-acp-route-creds-via-secret-registry-python-amd64
ghcr.io/openhands/agent-server:2699452-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:2699452-python-arm64
ghcr.io/openhands/agent-server:26994524505e829ec32221312371c5b7594a3012-python-arm64
ghcr.io/openhands/agent-server:fix-acp-route-creds-via-secret-registry-python-arm64
ghcr.io/openhands/agent-server:2699452-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:2699452-golang
ghcr.io/openhands/agent-server:26994524505e829ec32221312371c5b7594a3012-golang
ghcr.io/openhands/agent-server:fix-acp-route-creds-via-secret-registry-golang
ghcr.io/openhands/agent-server:2699452-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:2699452-java
ghcr.io/openhands/agent-server:26994524505e829ec32221312371c5b7594a3012-java
ghcr.io/openhands/agent-server:fix-acp-route-creds-via-secret-registry-java
ghcr.io/openhands/agent-server:2699452-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:2699452-python
ghcr.io/openhands/agent-server:26994524505e829ec32221312371c5b7594a3012-python
ghcr.io/openhands/agent-server:fix-acp-route-creds-via-secret-registry-python
ghcr.io/openhands/agent-server:2699452-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim

About Multi-Architecture Support

  • Each variant tag (e.g., 2699452-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., 2699452-python-amd64) are also available if needed

ACP folded provider credentials (llm.api_key/base_url) into `acp_env`,
which is persisted inside `agent_settings`. SaaS stores dump
`agent_settings` via `model_dump(mode='json')` with no cipher context, so
`acp_env` is redacted to `**********` at persist — silently dropping
cloud-injected creds. `acp_env` is also not masked in subprocess output.

Re-route consumption onto `state.secret_registry` — the single,
cipher-protected channel the regular agent uses — while KEEPING the public
`acp_env` field as the user-facing arbitrary-env-var input (non-breaking;
canvas / ts-client / OpenHands schema unchanged).

- `ACPAgentSettings.create_agent()` folds provider creds into
  `agent_context.secrets` (wrapped as StaticSecret) instead of `acp_env`.
  They ride the canonical `agent_context.secrets` -> `create_request` ->
  `request.secrets` -> `state.secret_registry` lift, encrypted across the
  conversation-start boundary, exactly like the LLM api_key.
- `resolve_acp_env()` no longer folds provider env in; it returns only the
  user's explicit `acp_env` entries.
- `_start_acp_server` drops the direct `agent_context.secrets` -> env drain;
  `agent_context.secrets` is now prompt-only (advertised, injected via the
  registry), matching the regular agent. `acp_env` injection is kept.

Fixes the cloud at-rest credential drop by construction. Implements
pre-cloud refactor P0-1 of OpenHands/agent-canvas#1022. Pairs with #1020.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@github-actions

github-actions Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@simonrosenberg simonrosenberg self-assigned this Jun 2, 2026

all-hands-bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

@github-actions

github-actions Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/agent
   acp_agent.py9639889%486–488, 646–647, 689, 691, 695, 699, 719, 782–783, 788, 855, 1074, 1077–1078, 1095–1096, 1125, 1130, 1206, 1216, 1569–1572, 1576–1578, 1581–1585, 1587, 1797, 1811–1812, 1815–1817, 1825, 1829, 1833–1834, 1840–1841, 1853–1854, 1857, 1891, 1895–1897, 1901–1902, 1934, 2156–2158, 2161–2162, 2202, 2342, 2346, 2354–2356, 2394–2395, 2398, 2406–2408, 2410, 2412, 2416, 2419, 2428–2430, 2432, 2468–2469, 2487–2490, 2493, 2497–2499, 2501, 2505–2506, 2711–2712
openhands-sdk/openhands/sdk/settings
   model.py5594591%86, 336, 346–349, 352, 365, 369, 375, 385, 391, 396, 599, 610, 624, 626, 628, 630, 632, 634, 636, 911, 913, 1226, 1336, 1375, 1402, 1438–1441, 1467, 1591, 1636, 1668, 1678, 1680, 1685, 1703, 1716, 1718, 1720, 1722, 1729
TOTAL28720826371% 

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean, security-focused refactor that correctly consolidates the ACP credential path.

Previously, provider credentials flowed through two separate channels into the subprocess env: as entries in acp_env (serialised unencrypted in AgentSettings dumps) and via a direct drain from agent_context.secrets inside _start_acp_server. Both paths are removed in favour of the cipher-protected state.secret_registry channel that the regular (non-ACP) agent has always used.

The implementation in create_agent() is correct:

  • Provider creds are wrapped as StaticSecret and merged into agent_context.secrets (user-supplied secrets win via {**provider_secrets, **existing}).
  • When no caller agent_context exists a minimal one is synthesised with current_datetime=None to preserve the datetime-suppression behaviour of the absent-context path.
  • Custom servers with no api_key_env_var produce an empty resolve_provider_env(), leave agent_context as None, and the if provider_secrets: guard correctly skips the merge.

Test coverage is thorough — the end-to-end test_acp_create_request_lifts_provider_creds_into_request_secrets test is particularly valuable as it validates the full pipeline from create_agent() through create_request() to request.secrets.

One minor type-annotation suggestion inline.

This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation

Address PR review: every value is a StaticSecret, so the dict[str, Any]
annotation was broader than necessary.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

all-hands-bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a well-scoped, security-positive refactor. The prior bot review covered the core architecture; a few additional observations below.

acp_env override semantics are preserved correctly. A user who explicitly sets a provider credential in acp_env (e.g. to point the subprocess at a different API key) still wins, because the spawn-time precedence is acp_env > os.environ > default_environment > state.secret_registry. Provider creds now arrive at the bottom of that ladder via the registry, so explicit user overrides are untouched.

Synthesized AgentContext is carefully minimal. When agent_context is None but provider secrets exist, create_agent() synthesizes AgentContext(current_datetime=None, secrets=...). Passing current_datetime=None preserves the "no datetime injection" semantics of the absent-context case; all other fields take their zero defaults. The only behavioural change is that provider creds now travel through the cipher-protected channel instead of being absent entirely.

resolve_acp_env() is now a clean single-responsibility method. It returns dict(self.acp_env) — the user's explicit, arbitrary env vars — with no implicit coupling to provider config. This makes the field's semantics unambiguous in both the settings schema and any future callers.

Prior inline suggestion addressed. The dict[str, Any] annotation flagged in the earlier review has been tightened to dict[str, StaticSecret] in a536aa070.

Overall: logic is correct, the test suite validates the full pipeline end-to-end (including the create_request lift into request.secrets), and the non-breaking constraint on acp_env is honoured. LGTM.

This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 QA Report: PARTIAL

ACP provider credential routing works through the SDK request/secret-registry path, but I could not complete a real third-party ACP subprocess launch in this environment.

Does this PR achieve its stated goal?

Yes for the core SDK routing goal I could exercise. On origin/main, a fake provider API key was placed in agent.acp_env, persisted as **********, and did not reach request.secrets or Conversation.state.secret_registry; on the PR commit, the same key was absent from acp_env, wrapped as an AgentContext StaticSecret, lifted into request.secrets, and available from state.secret_registry. I also verified explicit context secrets win on ANTHROPIC_API_KEY collision. I could not verify the final handoff into a real Claude Code/Codex ACP subprocess because no compatible ACP server was available and dummy subprocesses hang during ACP initialization.

Phase Result
Environment Setup ✅ uv run python created the project environment, installed packages, and imported openhands.sdk successfully.
CI Status ⚠️ At review time: 20 passing checks, 1 failing check (Python API), 7 pending agent-server/QA checks.
Functional Verification ✅ SDK settings → request → local conversation secret-registry behavior verified before/after; ⚠️ real external ACP subprocess launch not verified.
Functional Verification

Test 1: Provider API key moves out of acp_env and into request.secrets / state.secret_registry

Step 1 — Reproduce / establish baseline (without the fix):
Checked out origin/main and ran OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_acp_probe.py, which creates ACPAgentSettings(acp_server="claude-code", llm.api_key="sk-provider", acp_env={"MY_CUSTOM_VAR":"custom-value"}), calls create_agent(), builds a StartConversationRequest, then creates a local Conversation with request.secrets.

Relevant output:

{
  "agent_acp_env": {
    "ANTHROPIC_API_KEY": "sk-provider",
    "MY_CUSTOM_VAR": "custom-value"
  },
  "conversation_registry_ANTHROPIC_API_KEY": null,
  "persisted_agent_acp_env": {
    "ANTHROPIC_API_KEY": "**********",
    "MY_CUSTOM_VAR": "**********"
  },
  "request_secret_values": {},
  "resolve_acp_env": {
    "ANTHROPIC_API_KEY": "sk-provider",
    "MY_CUSTOM_VAR": "custom-value"
  }
}

This confirms the reported old behavior: provider credentials are folded into acp_env, persistence redacts them, and the canonical request/registry secret path is empty.

Step 2 — Apply the PR's changes:
Checked out a536aa07070f27e4204016a15760054d59ef4cb3.

Step 3 — Re-run with the fix in place:
Ran the same probe command.

Relevant output:

{
  "agent_acp_env": {
    "MY_CUSTOM_VAR": "custom-value"
  },
  "agent_context_secrets": {
    "ANTHROPIC_API_KEY": {
      "type": "StaticSecret",
      "value": "sk-provider"
    }
  },
  "conversation_registry_ANTHROPIC_API_KEY": "sk-provider",
  "persisted_agent_acp_env": {
    "MY_CUSTOM_VAR": "**********"
  },
  "request_secret_values": {
    "ANTHROPIC_API_KEY": "sk-provider"
  },
  "resolve_acp_env": {
    "MY_CUSTOM_VAR": "custom-value"
  }
}

This shows the provider key no longer rides acp_env; it is lifted into request.secrets and available from Conversation.state.secret_registry, while explicit user acp_env remains present.

Test 2: Explicit context secret wins on provider-key collision

On the PR commit, I created ACPAgentSettings with llm.api_key="sk-provider" plus agent_context.secrets["ANTHROPIC_API_KEY"] = StaticSecret("sk-explicit-context"), then built the request and local conversation.

Relevant output:

{
  "agent_acp_env": {},
  "agent_context_secret_value": "sk-explicit-context",
  "registry_secret_value": "sk-explicit-context",
  "request_secret_value": "sk-explicit-context"
}

This confirms explicit context secrets take precedence over provider-derived credentials and still flow through the request/registry path.

Unable to Verify

I attempted to exercise the final ACP subprocess environment handoff with a real child process by setting acp_command to a Python command that writes ANTHROPIC_API_KEY and MY_CUSTOM_VAR from its environment. Calling _start_acp_server hung because the dummy child does not speak the ACP initialization protocol; retrying with a short acp_prompt_timeout=0.2 still timed out before returning control. I did not install or run Claude Code/Codex because the environment lacks real provider credentials and an interactive ACP server setup.

Future QA runs would benefit from AGENTS.md guidance for a local minimal ACP-compatible server fixture, or documented steps for running a real ACP server non-interactively with test credentials.

Issues Found

None from functional QA. Note: CI currently reports a failing Python API check, which I did not investigate because this QA pass did not run or analyze CI test jobs.

This QA review was generated by an AI agent (OpenHands) on behalf of the user.

Final verdict: PARTIAL

@simonrosenberg simonrosenberg added the acp About ACP label Jun 2, 2026
Now that provider creds (and the regular secret channel) flow through
state.secret_registry, acp_env is a redundant, persist-unsafe channel. Mark
it deprecated so a future PR can delete it once the API-breakage checker's
5-minor-release runway has elapsed.

- warn_deprecated("ACPAgentSettings.acp_env" / "ACPAgent.acp_env",
  deprecated_in="1.24.0", removed_in="1.29.0") fires when a non-empty acp_env
  is actually used (resolve_acp_env / _start_acp_server); empty acp_env is
  silent. This registers the qualified-name deprecation metadata the
  check_sdk_api_breakage.py runway requires for a clean removal at >=1.29.0.
- Field descriptions on both classes note the deprecation + migration path
  (metadata-only; non-breaking).
- The field still works (still injected at spawn) — this commit only warns.

Tests: assert the warning fires on use and stays silent when acp_env is empty.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@simonrosenberg

Copy link
Copy Markdown
Member Author

Added 4b3bbdcbb: deprecate acp_env (deprecated_in=1.24.0, removed_in=1.29.0) so a follow-up can delete it cleanly.

Why this is needed: I traced .github/scripts/check_sdk_api_breakage.py — removing a public class member (and ACPAgentSettings is in openhands.sdk.__all__, with its acp_env field modeled by griffe as a class Attribute) requires a 5-minor-release deprecation runway registered via warn_deprecated('Cls.member', deprecated_in=, removed_in=). skip-acp-check does not cover field removals (only the agent-client-protocol dependency bump). The checker reads the runway metadata from the baseline release, so adding it now lets a future PR delete acp_env at ≥1.29.0 without tripping the gate.

This commit only warns when a non-empty acp_env is used (resolve_acp_env / _start_acp_server); empty acp_env is silent, and the field still works. Tests cover both. Non-breaking.

Also: validated the credential re-route end-to-end with real API calls through claude-agent-acp — good key → answer billed; broken key → 401 Invalid proxy server token — proving the registry-injected creds (not acp_env, not os.environ, not a cached login) are what authenticate.

all-hands-bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ QA Report: PASS

The SDK credential-routing behavior works as described: provider credentials now leave acp_env and reach the conversation secrets boundary used to populate state.secret_registry.

Does this PR achieve its stated goal?

Yes. I exercised the user-facing SDK settings path with realistic ACP settings on both main and the PR branch. On main, the provider credential appeared in agent.acp_env, serialized as **********, and was absent from StartConversationRequest.secrets; on the PR branch, the same provider credential appeared in agent_context.secrets and request.secrets while acp_env contained only the explicit user env var. I also verified the documented collision behavior: an explicit agent_context.secrets["ANTHROPIC_API_KEY"] wins over the provider-derived secret.

Phase Result
Environment Setup ✅ uv run created the project environment and SDK imports succeeded.
CI Status 🟡 Core checks queried via GitHub were passing; QA Changes and several Agent Server build jobs were still in progress at query time.
Functional Verification ✅ Before/after SDK execution confirmed provider creds route through request.secrets, not persisted acp_env.
Functional Verification

Test 1: Provider credential moves from redacted acp_env to conversation secrets

Step 1 — Reproduce / establish baseline without the fix:

Ran git checkout --detach origin/main && OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/acp_qa_probe.py on main (2e946e90):

{
  "provider_and_user_env": {
    "agent_acp_env": {
      "ANTHROPIC_API_KEY": "sk-provider",
      "MY_CUSTOM_VAR": "custom-value"
    },
    "agent_context_secrets": {
      "GITHUB_TOKEN": "ghp-context"
    },
    "request_secrets": {
      "GITHUB_TOKEN": "ghp-context"
    },
    "serialized_agent_acp_env": {
      "ANTHROPIC_API_KEY": "**********",
      "MY_CUSTOM_VAR": "**********"
    }
  }
}

This confirms the reported bug path: the provider key is placed in acp_env, becomes redacted in the JSON dump, and does not appear in request.secrets, so it cannot ride the cipher-protected conversation secrets channel.

Step 2 — Apply the PR's changes:

Checked out fix-acp-route-creds-via-secret-registry at 4b3bbdcbb3babf3d7f438d05bd351ce63496f64f.

Step 3 — Re-run with the fix in place:

Ran OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/acp_qa_probe.py:

{
  "provider_and_user_env": {
    "agent_acp_env": {
      "MY_CUSTOM_VAR": "custom-value"
    },
    "agent_context_secrets": {
      "ANTHROPIC_API_KEY": "sk-provider",
      "GITHUB_TOKEN": "ghp-context"
    },
    "request_secrets": {
      "ANTHROPIC_API_KEY": "sk-provider",
      "GITHUB_TOKEN": "ghp-context"
    },
    "serialized_agent_acp_env": {
      "MY_CUSTOM_VAR": "**********"
    }
  }
}

This shows the fix works at the SDK boundary: the provider credential no longer persists through acp_env; it is folded into agent_context.secrets and lifted into StartConversationRequest.secrets, the path that populates state.secret_registry server-side.

Test 2: Explicit context secrets win provider collisions

Step 1 — Baseline behavior:

On main, the collision scenario still left the provider value in acp_env even though request.secrets used the explicit context value:

{
  "explicit_context_collision": {
    "agent_acp_env": {
      "ANTHROPIC_API_KEY": "sk-provider"
    },
    "agent_context_secrets": {
      "ANTHROPIC_API_KEY": "ctx-wins"
    },
    "request_secrets": {
      "ANTHROPIC_API_KEY": "ctx-wins"
    },
    "serialized_agent_acp_env": {
      "ANTHROPIC_API_KEY": "**********"
    }
  }
}

Step 2 — Re-run on the PR branch:

The same collision scenario on the PR branch produced:

{
  "explicit_context_collision": {
    "agent_acp_env": {},
    "agent_context_secrets": {
      "ANTHROPIC_API_KEY": "ctx-wins"
    },
    "request_secrets": {
      "ANTHROPIC_API_KEY": "ctx-wins"
    },
    "serialized_agent_acp_env": {}
  }
}

This confirms explicit context secrets continue to win and the provider fallback is no longer duplicated into persisted ACP env.

CI status observed

Ran gh pr checks 3464 --repo OpenHands/software-agent-sdk --json name,state,workflow,link --jq .... At query time, Run tests, pre-commit, API breakage checks, docstrings, deprecation deadlines, and review-thread gate were successful; the QA Changes workflow and several Agent Server build/push jobs were still in progress.

Issues Found

None.

This review was created by an AI agent (OpenHands) on behalf of the user.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a well-reasoned, security-positive fix. Moving provider credentials from the unencrypted acp_env channel (which gets serialized as ********** in cipher-less store dumps) to the cipher-protected state.secret_registry path is the right call, and the implementation correctly matches the flow the regular (non-ACP) agent has always used.

The core logic in create_agent() is sound: wrapping provider creds as StaticSecret and merging them into agent_context.secrets with {**provider_secrets, **existing} (caller secrets win) is correct. The synthesized AgentContext(current_datetime=None, ...) when no caller context exists preserves the previous "no context" semantics precisely. Test coverage across all meaningful cases (provider-only, caller-only, combined, empty, synthesized context, registry-as-sole-source) is solid and the renamed test classes/methods accurately document the new invariants.

One behaviour worth noting, detailed inline.

This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation

Deleting the agent_context.secrets -> env drain in _start_acp_server (relying
on create_request to lift agent_context.secrets -> request.secrets ->
state.secret_registry) regressed the canvas-local path:

- canvas builds StartConversationRequest in TypeScript and sets the provider
  key on llm.api_key (agent-server-adapter.ts:598-600); it never calls the
  Python create_request lift.
- the agent-server seeds the registry ONLY from request.secrets
  (event_service.py:762); there is no server-side agent_context.secrets ->
  registry merge.

So on canvas the folded ANTHROPIC_API_KEY landed in agent_context.secrets,
was never lifted into the registry, and -- with the drain gone -- never
reached the CLI (auth failure). Verified end-to-end: with the registry empty
and the key only in agent_context.secrets, the restored drain delivers it and
a real claude-agent-acp call succeeds.

Keep the create_agent at-rest fix (provider creds -> agent_context.secrets,
off the redacted acp_env). Restore the drain: it runs AFTER the registry loop
and is fill-if-absent, so OpenHands (creds already in the registry) skips it
and canvas backfills -- no double-injection. An ACP subprocess is a black box
the SDK can't name-scan per command, so upfront injection is required; the
drain is the correct mechanism, not a shim. It can be removed only once a
server-side agent_context.secrets -> registry lift exists on every path.

Revert the tests that asserted the drain was gone.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

all-hands-bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

create_agent() now passes dict(self.acp_env) instead of resolve_acp_env(), so
the create_agent path warns only once (ACPAgent.acp_env at spawn). resolve_acp_env()
keeps its ACPAgentSettings.acp_env warning for explicit callers of that public
method. Addresses PR review (double-warn).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall Assessment

This is a correct, well-scoped security fix. Moving provider credentials off acp_env (where they are redacted to ********** by cipher-less store dumps) onto agent_context.secrets (where they ride the StoredConversation.secrets + Cipher boundary) eliminates a silent credential-drop that the PR description accurately diagnoses. The create_agent() implementation is clean: wrapping provider creds as StaticSecret, merging with {**provider_secrets, **existing} (caller wins), and synthesizing a minimal AgentContext(current_datetime=None, ...) when none exists are all correct choices. Test coverage across the meaningful cases is solid.

One unresolved concern and one new observation below.


🟠 Double deprecation warning on the ACPAgentSettings.create_agent() path

The existing inline comments on model.py:1205 and acp_agent.py:1365 correctly identify this, but no fix has landed yet. Here is the concrete mechanism and a proposed resolution:

When a caller uses ACPAgentSettings with a non-empty acp_env:

  1. create_agent() calls acp_env=self.resolve_acp_env() → fires ACPAgentSettings.acp_env deprecated (first warning)
  2. The returned ACPAgent later calls _start_acp_server() → fires ACPAgent.acp_env deprecated (second warning)

Two differently-named warnings for the same API misuse is confusing and undermines the migration message. The test test_acp_create_agent_folds_provider_creds_into_agent_context_secrets also silently emits the first of these warnings without pytest.warns (no filterwarnings = error in the project config, so it passes, but it is noise).

Proposed fix (model.py, inside create_agent()’s return ACPAgent(...) block): replace acp_env=self.resolve_acp_env() with acp_env=dict(self.acp_env). The resolve_acp_env() method keeps its own warning for callers who invoke it directly; _start_acp_server() fires the ACPAgent.acp_env warning as the single deprecation signal for the create_agent() path. No other logic changes are needed.


🟡 base_url travels through the secrets channel

An API base URL (e.g. ANTHROPIC_BASE_URL) is a routing endpoint, not a credential, yet resolve_provider_env() maps llm.base_url → base_url_env_var alongside api_key, and create_agent() wraps both as StaticSecret into agent_context.secrets. This is an improvement over the prior state (where it was masked in acp_env serialization), and co-locating it with api_key keeps the injection logic simple. Worth a deliberate note in case a future audit of state.secret_registry expects only genuine secrets, or if the base URL needs to be readable in logs for debugging.


This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ QA Report: PASS

ACP provider credentials now route through agent_context / request.secrets instead of persisted acp_env, while explicit ACP env vars still remain available.

Does this PR achieve its stated goal?

Yes. I exercised the SDK as a Python caller would: creating ACPAgentSettings, materializing an ACPAgent, and building a StartConversationRequest. On the base commit, fake provider credentials appeared in agent.acp_env, serialized to **********, and were absent from request.secrets; on this PR, the same credentials appear as StaticSecret entries in agent_context.secrets and request.secrets, while acp_env contains only the explicit user env var. I also verified explicit context secrets win on key collision.

Phase Result
Environment Setup ✅ uv run python built/imported the SDK successfully
CI Status 🟡 Latest snapshot: SDK/pre-commit/core checks passing; image build jobs still pending
Functional Verification ✅ Before/after SDK execution confirms the credential routing change
Functional Verification

Test 1: Provider credentials move out of acp_env and into request secrets

Step 1 — Reproduce baseline without the fix:
Ran git checkout e00da77d776d5dc5394d7c6ecbbc6be0605c09ee && OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_acp_routing.py:

{
  "normal_provider": {
    "agent_acp_env": {
      "ANTHROPIC_API_KEY": "sk-qa-provider",
      "ANTHROPIC_BASE_URL": "https://qa-proxy.example.test",
      "QA_USER_ENV": "visible-value"
    },
    "request_secret_keys": ["GITHUB_TOKEN"],
    "serialized_agent_acp_env": {
      "ANTHROPIC_API_KEY": "**********",
      "ANTHROPIC_BASE_URL": "**********",
      "QA_USER_ENV": "**********"
    }
  }
}

This confirms the reported bug shape: provider credentials were folded into acp_env, then redacted by plain JSON serialization, and did not appear in the request secret channel.

Step 2 — Apply the PR changes:
Checked out 41cecba4c57fb68812f6fedb187015e9c172b8f2.

Step 3 — Re-run with the fix in place:
Ran OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_acp_routing.py:

{
  "normal_provider": {
    "agent_acp_env": {"QA_USER_ENV": "visible-value"},
    "agent_context_secret_keys": [
      "ANTHROPIC_API_KEY",
      "ANTHROPIC_BASE_URL",
      "GITHUB_TOKEN"
    ],
    "request_secret_keys": [
      "ANTHROPIC_API_KEY",
      "ANTHROPIC_BASE_URL",
      "GITHUB_TOKEN"
    ],
    "request_secrets": {
      "ANTHROPIC_API_KEY": {"type": "StaticSecret", "value": "sk-qa-provider"},
      "ANTHROPIC_BASE_URL": {"type": "StaticSecret", "value": "https://qa-proxy.example.test"},
      "GITHUB_TOKEN": {"type": "StaticSecret", "value": "ghp_qa"}
    },
    "serialized_agent_acp_env": {"QA_USER_ENV": "**********"}
  }
}

This shows the provider API key and base URL now travel via agent_context.secrets and request.secrets; only the explicit user env var remains in acp_env.

Test 2: Explicit context secrets still take precedence

Baseline: the explicit context value reached request.secrets, but the provider value still also appeared in agent_acp_env:

{
  "explicit_context_wins": {
    "agent_acp_env": {"ANTHROPIC_API_KEY": "sk-provider-should-not-win"},
    "request_secrets": {
      "ANTHROPIC_API_KEY": {"type": "StaticSecret", "value": "sk-explicit-context"}
    }
  }
}

With the PR: the explicit context value is the only routed value and agent_acp_env is empty:

{
  "explicit_context_wins": {
    "agent_acp_env": {},
    "request_secrets": {
      "ANTHROPIC_API_KEY": {"type": "StaticSecret", "value": "sk-explicit-context"}
    },
    "serialized_agent_acp_env": {}
  }
}

This confirms the documented collision behavior: explicit context secrets win over provider-derived credentials.

Unable to Verify

I did not perform a real Claude Code/Codex authentication flow because that requires external ACP CLIs and provider credentials. I attempted a dummy ACP subprocess capture, but the dummy process was not a full ACP server and did not reach the env-capture point through startup handshaking. The verified SDK boundary (ACPAgentSettings.create_agent() → ConversationSettings.create_request() → request.secrets) is the user-facing path described by the PR for moving credentials into state.secret_registry.

Issues Found

None.

This QA review was generated by an AI agent (OpenHands) on behalf of the user.

@simonrosenberg
simonrosenberg requested review from enyst and neubig June 2, 2026 18:16
@simonrosenberg simonrosenberg changed the title fix(acp): route provider creds through secret_registry, not acp_env fix(acp): route provider creds through secret_registry; deprecate acp_env Jun 2, 2026
@enyst

enyst commented Jun 2, 2026

Copy link
Copy Markdown
Member

@OpenHands /codereview this PR and also explain to me clearly and concisely how it looks and works now. Pay attention to the Griffe API check, seems it's passing, is deprecation correct and at the right level though? But also the rest. Respond directly as a comment to PR.

@enyst

enyst commented Jun 2, 2026

Copy link
Copy Markdown
Member

Sorry, maybe I misunderstand, I don't think the precedence question is about acp_env?

@simonrosenberg

Copy link
Copy Markdown
Member Author

Sorry, maybe I misunderstand, I don't think the precedence question is about acp_env?

true! Pushing a fix to enforce acp_env > registry > drain > os.environ > default_environment. if that makes sense?

…fixes (review)

Addresses enyst's /codereview.

Precedence (the main concern): provider/conversation creds used to ride acp_env
(applied after os.environ) and thus won over an ambient ANTHROPIC_API_KEY etc.
Routing them through state.secret_registry / agent_context.secrets as fill-if-absent
*after* env.update(os.environ) let an ambient process env var silently beat the
explicit credential — and since this PR also deprecates acp_env, that left no way
to override an ambient var. Reordered _start_acp_server so the registry and the
agent_context drain OVERRIDE os.environ; acp_env stays highest. New precedence:

    acp_env > state.secret_registry > agent_context.secrets > os.environ > default_environment

The registry still wins over the drain on collision; both skip keys a higher tier
will set to avoid a redundant LookupSecret.get_value() HTTP call.

Docs: corrected the ACPAgentSettings.agent_context description (it claimed secrets
reach env "not by a direct ACPAgent drain" — the PR relies on that drain for
canvas-local); documented the new precedence in _start_acp_server and the test
class docstring.

Tests: made the three env-capture harnesses hermetic (clear os.environ so the
runner's ambient GITHUB_TOKEN/ANTHROPIC_API_KEY can't shadow values under test —
the failure enyst reproduced), and added tests that a registry secret and an
agent_context.secrets value each override a same-named ambient os.environ var.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@simonrosenberg

simonrosenberg commented Jun 2, 2026 •

Copy link
Copy Markdown
Member Author

AGENT

@enyst addressed in 86d1d9ba7.

Precedence (your main concern): you're right — routing creds through the registry/drain as fill-if-absent after env.update(os.environ) let an ambient var beat the explicit credential, and since this PR deprecates acp_env that left no override path. Reordered _start_acp_server so conversation creds override ambient os.environ:

acp_env > state.secret_registry > agent_context.secrets > os.environ > default_environment

Registry still wins over the drain on collision; both skip keys a higher tier will set to avoid a redundant LookupSecret.get_value() call. This restores the pre-PR llm.api_key-wins behavior and matches the regular agent (per-command secrets override inherited env).

Docs: fixed the ACPAgentSettings.agent_context description (it wrongly said "not by a direct ACPAgent drain"); documented the new precedence in _start_acp_server + the test class docstring.

Tests: made the three env-capture harnesses hermetic (clear os.environ so an ambient GITHUB_TOKEN/ANTHROPIC_API_KEY can't shadow values under test — the failure you reproduced), and added tests that a registry secret and an agent_context.secrets value each override a same-named ambient os.environ var. Full ACP suite now passes even with those vars exported (GITHUB_TOKEN=… ANTHROPIC_API_KEY=… uv run pytest …).

Griffe / field deprecation: confirmed correct as you noted. On your caveat about resolve_acp_env() needing its own removal metadata: create_agent no longer calls it (passes dict(self.acp_env) directly), so it's now only an explicit-caller helper. I left it un-decorated in this PR; I'll register @deprecated("ACPAgentSettings.resolve_acp_env", …) in the acp_env-deletion follow-up that actually removes it (the Griffe runway reads from the baseline, so adding it in that PR's predecessor release is sufficient) — happy to add it here instead if you'd prefer.

all-hands-bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall Assessment

This is a correct, well-scoped security fix with excellent test coverage. Moving provider credentials off acp_env onto agent_context.secrets eliminates the at-rest credential drop caused by cipher-context-free model_dump(mode='json') in SaaS stores — the root cause is accurately diagnosed and the chosen fix is the right one. The dual-channel injection design (registry + canvas-local drain) is clearly reasoned and the dual-warning concern from a previous review was cleanly resolved (9d62d99).

What the PR gets right

Security fix is architecturally correct. Provider creds now ride the same cipher-protected StoredConversation.secrets + Cipher boundary as the LLM api_key. The acp_env redaction-at-persist bug is fixed by construction, not patched.

Precedence inversion for os.environ is intentional and correct. The old fill-if-absent semantics let an ambient server os.environ silently override a conversation-supplied credential — wrong for remote/cloud deployments. The new order (acp_env > secret_registry > agent_context.secrets > os.environ) correctly makes per-conversation secrets authoritative. Tests test_registry_secret_overrides_ambient_os_environ and test_agent_context_secret_overrides_ambient_os_environ verify this.

Hermetic test isolation. Switching to patch.dict("os.environ", ..., clear=True) across all three test harnesses was overdue — the old approach let real env vars (e.g. a developer's ANTHROPIC_API_KEY) silently affect assertion outcomes. Good cleanup.

Deprecation runway. deprecated_in=1.24.0, removed_in=1.29.0 satisfies the 5-minor-release check_sdk_api_breakage.py runway, the field description is updated, and both warn sites guard on non-empty to keep the zero-usage path silent.

AgentContext synthesis. Creating AgentContext(current_datetime=None, secrets=...) when the caller supplies no context is the right approach — it avoids suddenly injecting datetime into the agent prompt on paths that previously suppressed it.

Minor issues

Two stale docstring fragments weren't updated to match the new precedence semantics:

  1. Stale precedence ladder in test_registry_secret_takes_precedence_over_agent_context_secret (line 5571): says acp_env > existing base env > secret_registry > agent_context.secrets — "existing base env" (os.environ) no longer sits between acp_env and the registry; the correct order is now acp_env > secret_registry > agent_context.secrets > os.environ.

  2. TestACPEnvConflictSuppression class docstring (line 5672): updated to say "came from: acp_env, os.environ, or secret_registry" — but the drain (agent_context.secrets) still exists and test_claude_config_dir_suppresses_api_key_from_secrets still exercises it. The list should still include agent_context.secrets.

Both are documentation-only nits; they don't affect runtime behaviour. Happy to approve as-is or after a one-liner fix — your call.

This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation

Comment thread tests/sdk/agent/test_acp_agent.py Resolved
Comment thread tests/sdk/agent/test_acp_agent.py Resolved
Two docstrings lagged the precedence change:
- test_registry_secret_takes_precedence_over_agent_context_secret still showed
  'acp_env > existing base env > secret_registry > agent_context.secrets'; updated
  to 'acp_env > secret_registry > agent_context.secrets > os.environ'.
- TestACPEnvConflictSuppression listed sources 'acp_env, os.environ, or
  secret_registry'; re-added agent_context.secrets (the drain + its test exist).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

all-hands-bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall Assessment

This PR is in excellent shape. It correctly fixes a real security bug: provider credentials placed in acp_env were silently dropped to ********** when model_dump(mode='json') ran without a cipher context (e.g. in SaaS at-rest storage). Routing them through agent_context.secrets → state.secret_registry puts them on the same cipher-protected channel as the LLM's own api_key. The iterative review cycle tightened the implementation across all seven commits, and the final commit (2699452450) addresses the two docstring nits raised in the previous review pass.

What holds up well

Security fix is architecturally sound. Wrapping provider credentials as StaticSecret(value=SecretStr(...)) before folding them into agent_context.secrets is the right move — they ride the create_request → request.secrets → state.secret_registry boundary (encrypted), exactly like the regular agent's credentials.

Precedence inversion for os.environ is correct. The old fill-if-absent order let an ambient server os.environ silently win over a conversation-supplied credential. The new order (acp_env > secret_registry > agent_context.secrets > os.environ) makes per-conversation secrets authoritative, which is the right semantic for cloud/remote deployments.

Hermetic test isolation is now complete. All three test harnesses use patch.dict("os.environ", ..., clear=True), and I confirmed test_claude_config_dir_suppresses_api_key_from_os_environ properly injects its ambient keys via extra_os_env — the test still exercises what its name says.

test_claude_config_dir_suppresses_api_key_from_registry closes the coverage gap for the new credential channel: provider creds that flow through the registry are correctly suppressed by the CLAUDE_CONFIG_DIR conflict logic.

Deprecation runway. deprecated_in=1.24.0, removed_in=1.29.0 satisfies the 5-minor-release SDK API breakage policy; the if self.acp_env: guard keeps the zero-usage path silent; and the double-warning issue on the create_agent path is cleanly resolved by passing dict(self.acp_env) directly instead of calling resolve_acp_env().

One observation (non-blocking)

The canvas-local drain (agent_context.secrets → direct env injection) is retained because canvas builds the conversation request in TypeScript and never calls create_request, so the secrets aren't lifted into state.secret_registry. The code and tests cover this path correctly. It would be worth filing a follow-up ticket to eliminate this two-channel design once a server-side agent_context.secrets → registry lift exists — the comment thread in _start_acp_server already calls this out, so it's tracked.

This is merge-ready.

This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ QA Report: PASS

Verified the ACP credential-routing changes with public SDK flows and an actual spawned ACP subprocess; the PR achieves its stated goal.

Does this PR achieve its stated goal?

Yes. On the baseline commit, provider credentials were folded into ACPAgent.acp_env and did not appear in StartConversationRequest.secrets; on the PR commit, the same user flow leaves acp_env with only explicit user env and routes provider api_key/base_url through agent_context.secrets into request.secrets. I also spawned an ACP subprocess and confirmed state.secret_registry now overrides an ambient same-named os.environ value (from-registry wins over ambient-should-lose), while explicit acp_env still works and emits the new deprecation warning.

Phase Result
Environment Setup ✅ uv sync --dev completed successfully earlier in this QA run; no tests/linters were run.
CI Status ⚠️ gh pr checks reported 32 successful, 3 skipped, 1 pending (QA Changes by OpenHands), 0 failing.
Functional Verification ✅ Settings/request credential routing, subprocess env precedence, and acp_env deprecation behavior were verified before/after.
Functional Verification

Test 1: Provider credentials move out of acp_env and into conversation secrets

Step 1 — Reproduce / establish baseline (without the fix):
Checked out merge-base e00da77d and ran:

OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_acp_settings.py

Relevant output:

{
  "agent_acp_env": {
    "ANTHROPIC_API_KEY": "sk-provider",
    "ANTHROPIC_BASE_URL": "https://proxy.example.test",
    "CUSTOM_ENV": "custom-value"
  },
  "agent_context_secret_keys": ["GITHUB_TOKEN"],
  "request_secret_keys": ["GITHUB_TOKEN"],
  "warnings": []
}

This confirms the bug-prone baseline behavior: provider creds are in acp_env, and the conversation request secrets contain only the caller-provided context secret.

Step 2 — Apply the PR's changes:
Checked out PR head 26994524.

Step 3 — Re-run with the fix in place:
Ran the same command:

OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_acp_settings.py

Relevant output:

{
  "agent_acp_env": {"CUSTOM_ENV": "custom-value"},
  "agent_context_secret_keys": [
    "ANTHROPIC_API_KEY",
    "ANTHROPIC_BASE_URL",
    "GITHUB_TOKEN"
  ],
  "request_secret_keys": [
    "ANTHROPIC_API_KEY",
    "ANTHROPIC_BASE_URL",
    "GITHUB_TOKEN"
  ]
}

This shows the fix works for the public settings/request path: provider credentials no longer persist through acp_env; they are lifted through agent_context.secrets into StartConversationRequest.secrets.

Test 2: Spawned ACP subprocess receives registry credentials ahead of ambient env

Step 1 — Reproduce / establish baseline (without the fix):
On merge-base e00da77d, ran a script that starts ACPAgent._start_acp_server() with:

  • ambient os.environ["ANTHROPIC_API_KEY"] = "ambient-should-lose"
  • state.secret_registry["ANTHROPIC_API_KEY"] = "from-registry"
  • an agent_context.secrets fallback and explicit acp_env
rm -rf /tmp/qa_base_cap; mkdir -p /tmp/qa_base_cap; \
timeout 8s env QA_CAPTURE_DIR=/tmp/qa_base_cap OPENHANDS_SUPPRESS_BANNER=1 \
  uv run python /tmp/qa_acp_spawn_capture.py; \
echo EXIT:$?; cat /tmp/qa_base_cap/env.json

Relevant output:

EXIT:124
{"AMBIENT_ONLY": "ambient-value", "ANTHROPIC_API_KEY": "ambient-should-lose", "CAPTURE_PATH": "/tmp/qa_base_cap/env.json", "CONTEXT_ONLY": "from-context-only", "CUSTOM": "from-acp-env"}

The timeout is expected for this capture harness after the subprocess writes its env snapshot. The captured environment confirms the old precedence bug: ambient os.environ wins over the per-conversation registry secret.

Step 2 — Apply the PR's changes:
Checked out PR head 26994524.

Step 3 — Re-run with the fix in place:
Ran the same capture:

rm -rf /tmp/qa_pr_cap; mkdir -p /tmp/qa_pr_cap; \
timeout 8s env QA_CAPTURE_DIR=/tmp/qa_pr_cap OPENHANDS_SUPPRESS_BANNER=1 \
  uv run python /tmp/qa_acp_spawn_capture.py; \
echo EXIT:$?; cat /tmp/qa_pr_cap/env.json

Relevant output:

EXIT:124
{"AMBIENT_ONLY": "ambient-value", "ANTHROPIC_API_KEY": "from-registry", "CAPTURE_PATH": "/tmp/qa_pr_cap/env.json", "CONTEXT_ONLY": "from-context-only", "CUSTOM": "from-acp-env"}

This confirms the changed runtime behavior at the actual subprocess boundary: state.secret_registry supplies the provider credential and overrides the same-named ambient server env var; agent_context.secrets still drains context-only secrets; explicit acp_env still reaches the subprocess.

Test 3: acp_env still works but now warns

Step 1 — Reproduce / establish baseline (without the fix):
On merge-base e00da77d, ran a warnings-capture script for ACPAgentSettings(acp_env=...).resolve_acp_env().

Output:

resolved= {'CUSTOM_ENV': 'custom-value'}
warnings= []

Step 2 — Apply the PR's changes:
Checked out PR head 26994524.

Step 3 — Re-run with the fix in place:
Ran the same warnings-capture script.

Output:

resolved= {'CUSTOM_ENV': 'custom-value'}
warnings= ['ACPAgentSettings.acp_env is deprecated as of 1.24.0 and will be removed in 1.29.0. Provide arbitrary ACP subprocess env vars through the conversation secrets channel (agent_context.secrets / StartConversationRequest.secrets, which route through state.secret_registry) instead.']

This verifies the deprecation is user-visible while preserving the existing explicit acp_env behavior.

Issues Found

None.

This review was created by an AI agent (OpenHands) on behalf of the user.

@enyst

enyst commented Jun 2, 2026

Copy link
Copy Markdown
Member

@OpenHands read all top level comments so you get an idea what we decided here, and /codereview this PR. Post your review with gh api as a review, approved if you think it has no major issues. (don't hold it for nits)

@openhands-ai

openhands-ai Bot commented Jun 2, 2026

Copy link
Copy Markdown

I'm on it! enyst can track my progress at all-hands.dev

@enyst enyst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Taste Rating: Good taste

I read through the top-level thread and the final shape matches the decisions there: acp_env remains only as the deprecated explicit override, conversation/provider credentials are authoritative over ambient server env, and the final precedence is:

acp_env > state.secret_registry > agent_context.secrets > os.environ > default_environment

The implementation is clean and focused:

  • Provider llm.api_key / llm.base_url are folded into agent_context.secrets as StaticSecrets instead of persisted acp_env, so they can ride the cipher-protected request/stored-conversation secret path.
  • The direct agent_context.secrets drain is intentionally retained for canvas-local / non-create_request paths; the comments now make the two-channel design clear.
  • The precedence regression called out earlier is fixed: registry/drain values now override ambient os.environ, while acp_env remains the highest-priority deprecated path.
  • The Griffe/API-check deprecation level is correct for the public fields: ACPAgentSettings.acp_env and ACPAgent.acp_env have warn_deprecated(... deprecated_in="1.24.0", removed_in="1.29.0"), which provides the required 5-minor runway for future field removal. The double-warning create-agent path was also cleaned up.
  • Tests cover the settings/request lift, registry injection, drain injection, collision precedence, ambient env override, conflict stripping, and empty/non-empty warning behavior.

Validation I ran locally:

GITHUB_TOKEN=ambient-gh ANTHROPIC_API_KEY=ambient-anthropic uv run pytest \
  tests/sdk/agent/test_acp_agent.py \
  -k 'TestACPSecretsEnvInjection or TestACPSecretRegistryEnvInjection or TestACPEnvConflictSuppression'
# 20 passed

uv run pytest tests/sdk/test_settings.py \
  -k 'acp_create_request_lifts_provider_creds_into_request_secrets or acp_resolve_acp_env_returns_only_user_entries or acp_create_agent_folds_provider_creds_into_agent_context_secrets or acp_create_agent_synthesizes_context_for_provider_creds or acp_create_agent_no_provider_creds_keeps_context_none or acp_env_emits_deprecation_warning or acp_env_empty_does_not_warn'
# 7 passed

I also checked PR checks: all current checks are successful.

[RISK ASSESSMENT]

  • [Overall PR] ⚠️ Risk Assessment: 🟡 MEDIUM

This is auth/secret-routing code, so the blast radius is security-sensitive. The design is nevertheless straightforward, backward-compatible for non-empty acp_env, covered by targeted tests and QA, and it removes a real at-rest credential loss. No major issues found.

VERDICT:
✅ Worth merging — approving.

KEY INSIGHT:
Moving provider credentials from a serialized env dict into the existing secret-registry path fixes the persistence bug at the data-flow boundary instead of patching serialization symptoms.

This review was generated by an AI agent (OpenHands) on behalf of the requester.

@openhands-ai

This comment was marked as duplicate.

@simonrosenberg

Copy link
Copy Markdown
Member Author

@enyst thanks for the review!

@simonrosenberg
simonrosenberg merged commit c5a7875 into main Jun 2, 2026
44 of 45 checks passed
@simonrosenberg
simonrosenberg deleted the fix-acp-route-creds-via-secret-registry branch June 2, 2026 20:55
simonrosenberg pushed a commit that referenced this pull request Jun 2, 2026
The regular terminal masks every observation via
secret_registry.mask_secrets_in_output(); ACP masked nothing, so a
subprocess that echoed an injected credential (env, a failing curl
printing an Authorization header) landed in the persisted event stream
and WebSocket relay in cleartext — the largest credential-leak surface,
widened on cloud where subscription tokens are injected.

Route ACP output through the registry mask before emitting:
- streamed AgentMessageChunk text (on_token + accumulated_text) and
  AgentThoughtChunk text
- tool-call title/raw_input/raw_output/content, masked at ingestion so
  the started event, the single terminal event (#3465 dedup), and the
  flush/supersede path all carry masked values and the accumulator never
  holds plaintext
- the joined response_text/thought_text in _finalize_successful_turn
  (persistence boundary), which also catches secrets split across
  stream chunks

Complete the mask set for the channels that bypass get_secret_value:
seed _exported_values for the agent_context.secrets drain and the
(deprecated, #3464) acp_env via a new SecretRegistry.track_exported_value
with a minimum-length guard so trivially short non-secret config
(e.g. VERBOSITY=1) is not masked. The state.secret_registry channel
auto-seeds via get_secret_value.

A failing masker falls back to the original value (crash-safe), matching
the terminal tool contract. The live on_token relay still forwards a
secret split mid-value across chunks as fragments; the persisted stream
is fully masked.

Implements pre-cloud refactor P0-2 (OpenHands/agent-canvas#1023).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
simonrosenberg pushed a commit that referenced this pull request Jun 3, 2026
The regular terminal masks every observation via
secret_registry.mask_secrets_in_output(); ACP masked nothing, so a
subprocess that echoed an injected credential (env, a failing curl
printing an Authorization header) landed in the persisted event stream
and WebSocket relay in cleartext — the largest credential-leak surface,
widened on cloud where subscription tokens are injected.

Route ACP output through the registry mask before emitting:
- streamed AgentMessageChunk text (on_token + accumulated_text) and
  AgentThoughtChunk text
- tool-call title/raw_input/raw_output/content, masked at ingestion so
  the started event, the single terminal event (#3465 dedup), and the
  flush/supersede path all carry masked values and the accumulator never
  holds plaintext
- the joined response_text/thought_text in _finalize_successful_turn
  (persistence boundary), which also catches secrets split across
  stream chunks

The mask set is the registry's _exported_values, seeded by
get_secret_value when _start_acp_server reads state.secret_registry —
the canonical channel that #3464 routes provider creds and (on the
caller/cloud path) agent_context.secrets through. No new SecretRegistry
API; the deprecated acp_env / canvas-local drain are out of scope.

A failing masker falls back to the original value (crash-safe), matching
the terminal tool contract. The live on_token relay still forwards a
secret split mid-value across chunks as fragments; the persisted stream
is fully masked (follow-up: OpenHands/agent-canvas#1049).

Implements pre-cloud refactor P0-2 (OpenHands/agent-canvas#1023).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
simonrosenberg pushed a commit that referenced this pull request Jun 3, 2026
The regular terminal masks every observation via
secret_registry.mask_secrets_in_output(); ACP masked nothing, so a
subprocess that echoed an injected credential (env, a failing curl
printing an Authorization header) landed in the persisted event stream
and WebSocket relay in cleartext — the largest credential-leak surface,
widened on cloud where subscription tokens are injected.

Bind the registry masker onto the bridge once in _start_acp_server
(conversation-stable; a pure read of _exported_values with none of the
cross-thread/state-lock hazards that make on_event/on_token per-turn)
and route ACP output through it before emitting:
- streamed AgentMessageChunk text (on_token + accumulated_text) and
  AgentThoughtChunk text
- tool-call title/raw_input/raw_output/content, masked at ingestion so
  the started event, the single terminal event (#3465 dedup), and the
  flush/supersede path all carry masked values and the accumulator never
  holds plaintext
- the ask_agent() fork accumulator + its joined return value, which is
  relayed to the caller/UI (binding the masker once is what makes this
  reachable even when ask_agent runs while no turn is active)
- the joined response_text/thought_text in _finalize_successful_turn
  (persistence boundary), which also catches secrets split across chunks

The mask set is the registry's _exported_values, seeded by
get_secret_value when _start_acp_server reads state.secret_registry —
the canonical channel that #3464 routes provider creds and (on the
caller/cloud path) agent_context.secrets through. No new SecretRegistry
API; the deprecated acp_env / canvas-local drain are out of scope.

A failing masker falls back to the original value (crash-safe), matching
the terminal tool contract. The live on_token relay still forwards a
secret split mid-value across chunks as fragments; the persisted stream
is fully masked (follow-up: OpenHands/agent-canvas#1049).

Implements pre-cloud refactor P0-2 (OpenHands/agent-canvas#1023).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
pengzhang-create pushed a commit to Pyromind-Dynamics/software-agent-sdk that referenced this pull request Aug 13, 2026
…_env (OpenHands#3464)

Co-authored-by: Debug Agent <debug@example.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

acp About ACP

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants