Skip to content

fix(tools): mask secrets in every tool's observation at the shared chokepoint - #4788

Merged
VascoSch92 merged 2 commits into
mainfrom
vasco/security-4677-mask-tool-observations
Sep 1, 2026
Merged

VascoSch92 merged 2 commits into
mainfrom
vasco/security-4677-mask-tool-observations

Conversation

@VascoSch92

@VascoSch92 VascoSch92 commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

HUMAN:

Fix secrets leakage in tools obs.


AGENT:

Why

Sweeping openhands-tools for masking call sites returned exactly one file, terminal/impl.py:371. Of the 13 shipped tool packages, only terminal masked its output (plus mcp/tool.py:187 in the SDK). Which tool the model happened to pick decided whether a secret was masked:

cat .env            via bash          ->  MASKED
open .env           via file_editor   ->  RAW

There was no security boundary — just one tool that happened to carry the code.

Summary

  • Mask at ToolDefinition.__call__ (openhands-sdk/openhands/sdk/tool/tool.py), the single point every tool's observation passes through. It already receives conversation, and acall delegates to it, so the async path comes along for free.
  • Add SecretRegistry.mask_secrets_in_model, which rebuilds a model with every nested string masked (nested models, lists, tuples, dict values).
  • Add a guard test that fails when a new tool overrides __call__ without delegating to super().__call__ — the "tool Port over tests for LLM #14 is covered by default" property the issue asks for.

Issue Number

Fixes #4677

How to Test

uv run pytest tests/tools/test_tool_output_secret_masking.py tests/sdk/conversation/test_secret_registry_model_masking.py -q
# 13 passed

The four tools named in the acceptance criteria, driven end-to-end through a real LocalConversation with a registered secret (not by calling the masking helper directly):

--file_editor--  view .env      ->  "API_KEY=<secret-hidden>"   (file on disk unchanged)
--grep--         pattern echo   ->  pattern='<secret-hidden>'
--glob--         matched path   ->  ['.../note-<secret-hidden>.txt']
--apply_patch--  nested commit  ->  commit.changes['secrets.txt'].new_content='TOKEN=<secret-hidden>'

The guard test was negative-checked by adding a bypassing tool and confirming it fails with a usable message:

These ToolDefinition subclasses override __call__ without delegating to
super().__call__, so their output never reaches the secret-masking
chokepoint: ['tests.tools.test_guard_negative_tmp.SneakyTool']

Wider suites, re-run against the current HEAD:

uv run pytest tests/sdk tests/tools -q -p no:randomly
# 1 failed, 6950 passed, 24 skipped, 10 xfailed

The single failure is a tmux timing flake in tests/tools/terminal/test_terminal_session.py, not this change:

  • It passes on its own (uv run pytest "…::test_long_running_command_follow_by_execute" -q → 1 passed).
  • A previous full run failed a different test in the same file (test_command_backslash[tmux]), which is the signature of a flaky tmux harness rather than a real regression.
  • The file cannot reach the changed code path: it contains zero references to ToolDefinition, conversation or Conversation, and drives create_terminal_session directly. Its one secret-related test asserts a token is present in session.execute(...) output — correct, since calling the session directly bypasses ToolDefinition.__call__ and therefore the mask. That test passes.

pre-commit run --files <the four changed files> passes (ruff format, ruff lint, pycodestyle, pyright, import rules, tool registration).

Video/Screenshots

Not applicable — no user-facing surface. The observable behaviour is the tool output above.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

Why the whole model, not Observation.content. Masking content at the chokepoint looks sufficient and is not. to_llm_content is a property subclasses override, and several tools build what the model sees out of their own fields: tom_consult from suggestions/reasoning, SleeptimeComputeObservation from message, terminal from metadata.prefix/suffix/working_dir, task from _get_task_info(). ApplyPatchObservation is the clearest case — the secret lands in commit.changes[...].new_content, a nested model two levels below content. A content-only chokepoint would have passed review and still leaked, which is the same failure mode that produced this issue.

One correction to the issue's framing. The issue lists grep -r "API_KEY" . via grep -> RAW. The SDK's grep does not return file contents at all — GrepObservation.matches is a list of file paths, and GlobObservation.files likewise. The real leak on those two is the echoed pattern and any secret-bearing path, both of which this covers. Worth correcting so the acceptance criteria are read against what the tools actually return.

Self-review catch. The first cut of the recursive masker downgraded str-subclass enums: ActionType in apply_patch subclasses str, so isinstance(value, str) matched and mask() turned the enum member into a plain str, which surfaced as PydanticSerializationUnexpectedValue on apply_patch. Enum members are now returned untouched — their vocabulary is fixed, so they cannot hold a secret. Regression test: test_preserves_str_subclass_enum_members.

Audit of the other ways this could miss. Since the helper's promise is "covered by default", I checked the 26 Observation subclasses actually shipped for the surfaces a whole-model walk can still miss: none declare extra="allow" (extras live outside model_fields), none have set/frozenset fields, none have NamedTuple fields. Five carry a _diff_cache private attribute, which model_copy preserves — but it is populated lazily inside visualize, so it is None at mask time and the diff is rebuilt from masked fields. Verified end-to-end on a str_replace that writes a secret: _diff_cache is None at mask time, new_content comes back masked, model_dump_json() has no secret, the lazily-built visualize diff is masked, and the file on disk still holds the real value.

Rewriting the dispatch as a match (review feedback) surfaced two gaps of the same shape as the Enum one, fixed in 958e1af92: set/frozenset had no branch and fell through to the catch-all unmasked, and a NamedTuple matched the tuple branch and came back as a plain tuple. Neither is reachable today, both are now covered by tests verified to fail without the fix.

Known trade-off, needs your call — file_editor read/modify/write. A masked view means the model can no longer reconstruct old_str for a str_replace on a file containing a registered secret; the edit fails to match. This is the same trade-off terminal masking has had all along (cat .env is already masked today), and failing to match is loud rather than silent. But file_editor both reads and writes, so it is worth deciding deliberately rather than inheriting it. The file on disk is never modified by masking — only the returned observation is, which the file_editor test asserts.

Not addressed here. browser_use returns screenshots; a secret rendered into an image cannot be string-masked, so the tool named in the issue title is only partly covered. Also, screenshot_data is a str of base64, so it now gets scanned per registered secret — correct but wasteful on large screenshots. Say the word if you want an opt-out hook for fields like that.

Left in place deliberately. terminal/impl.py:371 and mcp/tool.py:187 now mask redundantly. Masking is idempotent, terminal masks before its full-output-save-to-disk path, and removing them is a behaviour change in tools with their own tests. Happy to strip them in a follow-up if you would rather have one code path.

…okepoint

Masking covered 1 of 13 tool packages: only terminal (plus MCP tool output
in the SDK). Which tool the model happened to pick decided whether a secret
reached its context — `cat .env` was masked, `open .env` through
file_editor was not.

Mask in ToolDefinition.__call__, the single point every tool's observation
passes through. It already receives the conversation, and acall delegates
to it, so the async path is covered too.

Masking Observation.content would not be enough: to_llm_content is an
overridable property and several tools build what the model sees out of
their own fields (tom_consult.suggestions, SleeptimeComputeObservation.
message, terminal metadata, task._get_task_info). ApplyPatchObservation is
the clearest case — the secret lands in commit.changes[...].new_content, a
nested model. So SecretRegistry.mask_secrets_in_model walks the whole
model: nested models, lists, tuples and dict values.

Enum members are returned untouched. A str-subclass enum such as
apply_patch's ActionType would otherwise be masked into a plain str and
break the field's serialization, and an enum's vocabulary cannot hold a
secret anyway.

A guard test fails when a new tool overrides __call__ without delegating to
super().__call__, so tool #14 is covered by default rather than by
remembering.

Fixes #4677
@github-actions

Copy link
Copy Markdown
Contributor

Endpoint audit

⚠️ 18 actionable Agent Server contract divergence(s) · report-only

Contract: pinned release artifact

Category Count
Actionable client-only calls 0
Actionable server-only operations 18
Documented non-divergences 13
Agent Server contract operations 129
Audited handwritten client endpoints 119

Actionable client-only calls (0)

none

Actionable server-only operations (18)

  • DELETE /api/canvas-extensions/installed/{}
  • DELETE /api/llm/provider-connections/{}
  • GET /api/canvas-extensions/installed
  • GET /api/canvas-extensions/installed/{}
  • GET /api/canvas-extensions/installed/{}/bundle
  • GET /api/conversations/{}/events
  • GET /api/file/archive
  • GET /api/git/commits
  • GET /api/git/commits/{}/changes
  • GET /api/init
  • GET /api/llm/provider-connections
  • PATCH /api/canvas-extensions/installed/{}
  • PATCH /api/llm/provider-connections/{}
  • POST /api/canvas-extensions/install
  • POST /api/conversations/{}/load_plugin
  • POST /api/file/create_directory
  • POST /api/init
  • POST /api/llm/provider-connections
Documented non-divergences (13)

Client calls intentionally absent from the filtered contract (11)

  • GET /
  • GET /alive
  • GET /health
  • GET /ready
  • GET /server_info

Reason: Operational Agent Server endpoints intentionally excluded from the filtered public release artifact.
Owner: OpenHands runtime maintainers

  • DELETE /api/meta-profiles/{}
  • GET /api/meta-profiles
  • GET /api/meta-profiles/{}
  • POST /api/meta-profiles/{}
  • POST /api/meta-profiles/{}/activate

Reason: Client-ahead API stacked on the pending Agent Server meta-profiles implementation.
Owner: OpenHands SDK maintainers
Tracking: #3744

  • POST /api/profiles/{}/validate

Reason: Client-ahead API stacked on the pending Agent Server pre-flight LLM validation endpoint.
Owner: OpenHands TypeScript client maintainers
Tracking: #4422

Server operations covered by an exposed browser URL (2)

  • GET /api/conversations/{}/workspace
  • GET /api/conversations/{}/workspace/{}

Reason: RemoteWorkspace.startWorkspaceSession exposes these authenticated URLs for browser iframe and file requests; they are not HttpClient method calls.
Owner: OpenHands TypeScript client maintainers

@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/conversation
   secret_registry.py131497%289, 291, 294, 303
openhands-sdk/openhands/sdk/tool
   tool.py3492892%94–95, 97, 107, 161, 163, 187, 195–198, 327, 431, 478, 551–552, 574–575, 601, 626, 630, 657–658, 731, 852, 909, 921–922
TOTAL418391205571% 

Review feedback: express the type dispatch as a match statement.

Auditing the branches while rewriting them turned up two more type gaps of
the same shape as the Enum one:

- set/frozenset had no branch at all, so a set[str] field fell through to
  the catch-all and was never masked.
- NamedTuple fields matched the tuple branch and came back as a plain
  tuple, losing their type exactly as a masked Enum member did.

Neither is reachable across the 26 Observation subclasses shipped today
(audited: no set fields, no NamedTuple fields, no extra="allow"), but the
whole point of this helper is that tool #14 is covered by default, so the
branches belong here rather than in a future bug report.
@VascoSch92
VascoSch92 marked this pull request as ready for review August 31, 2026 12:32
@all-hands-bot

Copy link
Copy Markdown
Collaborator

🚦 CI is currently failing on this PR's latest commit.

Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request @all-hands-bot as a reviewer to have it reviewed regardless of CI status.)

This is an automated check - no AI was used to generate this comment.

@VascoSch92
VascoSch92 requested a review from enyst August 31, 2026 16:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Security] Secret masking covers 1 tool out of 13 — the model reads raw secrets through file_editor, grep, glob, apply_patch and browser_use

3 participants