Repository navigation
fix(tools): mask secrets in every tool's observation at the shared chokepoint - #4788
Conversation
…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
Endpoint auditContract: pinned release artifact
Actionable client-only calls (0)none Actionable server-only operations (18)
Documented non-divergences (13)Client calls intentionally absent from the filtered contract (11)
Reason: Operational Agent Server endpoints intentionally excluded from the filtered public release artifact.
Reason: Client-ahead API stacked on the pending Agent Server meta-profiles implementation.
Reason: Client-ahead API stacked on the pending Agent Server pre-flight LLM validation endpoint. Server operations covered by an exposed browser URL (2)
Reason: RemoteWorkspace.startWorkspaceSession exposes these authenticated URLs for browser iframe and file requests; they are not HttpClient method calls. |
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
||||||||||||||||||||||||||||||
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.
|
🚦 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 This is an automated check - no AI was used to generate this comment. |
HUMAN:
Fix secrets leakage in tools obs.
AGENT:
Why
Sweeping
openhands-toolsfor masking call sites returned exactly one file,terminal/impl.py:371. Of the 13 shipped tool packages, onlyterminalmasked its output (plusmcp/tool.py:187in the SDK). Which tool the model happened to pick decided whether a secret was masked:There was no security boundary — just one tool that happened to carry the code.
Summary
ToolDefinition.__call__(openhands-sdk/openhands/sdk/tool/tool.py), the single point every tool's observation passes through. It already receivesconversation, andacalldelegates to it, so the async path comes along for free.SecretRegistry.mask_secrets_in_model, which rebuilds a model with every nested string masked (nested models, lists, tuples, dict values).__call__without delegating tosuper().__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
The four tools named in the acceptance criteria, driven end-to-end through a real
LocalConversationwith a registered secret (not by calling the masking helper directly):The guard test was negative-checked by adding a bypassing tool and confirming it fails with a usable message:
Wider suites, re-run against the current HEAD:
The single failure is a tmux timing flake in
tests/tools/terminal/test_terminal_session.py, not this change:uv run pytest "…::test_long_running_command_follow_by_execute" -q→ 1 passed).test_command_backslash[tmux]), which is the signature of a flaky tmux harness rather than a real regression.ToolDefinition,conversationorConversation, and drivescreate_terminal_sessiondirectly. Its one secret-related test asserts a token is present insession.execute(...)output — correct, since calling the session directly bypassesToolDefinition.__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
Notes
Why the whole model, not
Observation.content. Maskingcontentat the chokepoint looks sufficient and is not.to_llm_contentis a property subclasses override, and several tools build what the model sees out of their own fields:tom_consultfromsuggestions/reasoning,SleeptimeComputeObservationfrommessage,terminalfrommetadata.prefix/suffix/working_dir,taskfrom_get_task_info().ApplyPatchObservationis the clearest case — the secret lands incommit.changes[...].new_content, a nested model two levels belowcontent. Acontent-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'sgrepdoes not return file contents at all —GrepObservation.matchesis a list of file paths, andGlobObservation.fileslikewise. The real leak on those two is the echoedpatternand 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:
ActionTypeinapply_patchsubclassesstr, soisinstance(value, str)matched andmask()turned the enum member into a plainstr, which surfaced asPydanticSerializationUnexpectedValueonapply_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
Observationsubclasses actually shipped for the surfaces a whole-model walk can still miss: none declareextra="allow"(extras live outsidemodel_fields), none haveset/frozensetfields, none have NamedTuple fields. Five carry a_diff_cacheprivate attribute, whichmodel_copypreserves — but it is populated lazily insidevisualize, so it isNoneat mask time and the diff is rebuilt from masked fields. Verified end-to-end on astr_replacethat writes a secret:_diff_cacheisNoneat mask time,new_contentcomes back masked,model_dump_json()has no secret, the lazily-builtvisualizediff 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 in958e1af92:set/frozensethad no branch and fell through to the catch-all unmasked, and a NamedTuple matched thetuplebranch 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_editorread/modify/write. A maskedviewmeans the model can no longer reconstructold_strfor astr_replaceon a file containing a registered secret; the edit fails to match. This is the same trade-offterminalmasking has had all along (cat .envis already masked today), and failing to match is loud rather than silent. Butfile_editorboth 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 thefile_editortest asserts.Not addressed here.
browser_usereturns 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_datais astrof 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:371andmcp/tool.py:187now 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.