diff --git a/openhands-sdk/openhands/sdk/conversation/secret_registry.py b/openhands-sdk/openhands/sdk/conversation/secret_registry.py index 418e7eba54a..1ca3ebdd381 100644 --- a/openhands-sdk/openhands/sdk/conversation/secret_registry.py +++ b/openhands-sdk/openhands/sdk/conversation/secret_registry.py @@ -1,11 +1,12 @@ """Secrets manager for handling sensitive data in conversations.""" import time -from collections.abc import Collection, Mapping +from collections.abc import Callable, Collection, Mapping +from enum import Enum from threading import RLock -from typing import Final +from typing import Any, Final -from pydantic import Field, PrivateAttr, SecretStr +from pydantic import BaseModel, Field, PrivateAttr, SecretStr from openhands.sdk.logger import get_logger from openhands.sdk.secret import SecretSource, SecretValue, StaticSecret @@ -18,6 +19,46 @@ FAILED_LOOKUP_RETRY_SECONDS: Final[float] = 60.0 +def _mask_value(value: Any, mask: Callable[[str], str]) -> Any: + """Recursively mask every ``str`` reachable from ``value``.""" + match value: + case Enum(): + # A str-subclass enum is a str, but masking it would downgrade the + # member to a plain str and break the field's serialization. Its + # vocabulary is fixed, so it can never hold a secret anyway. + return value + case str(): + return mask(value) + case BaseModel(): + return _mask_model(value, mask) + case list(): + return [_mask_value(item, mask) for item in value] + case tuple(): + items = [_mask_value(item, mask) for item in value] + # Rebuild a NamedTuple through its own constructor; tuple(items) + # would downgrade it the same way masking an Enum member does. + return type(value)(*items) if hasattr(value, "_fields") else tuple(items) + case set() | frozenset(): + return type(value)(_mask_value(item, mask) for item in value) + case dict(): + return {key: _mask_value(item, mask) for key, item in value.items()} + case _: + return value + + +def _mask_model[ModelT: BaseModel](model: ModelT, mask: Callable[[str], str]) -> ModelT: + """Rebuild ``model`` with every nested string masked. + + ``model_copy`` is used rather than a validate round-trip so private + attributes survive and no field is re-coerced. + """ + updates = { + name: _mask_value(getattr(model, name), mask) + for name in type(model).model_fields + } + return model.model_copy(update=updates) + + class SecretRegistry(OpenHandsModel): """Manages secrets and injects them into bash commands when needed. @@ -178,6 +219,16 @@ def mask_secrets_in_output(self, text: str) -> str: return masked_text + def mask_secrets_in_model[ModelT: BaseModel](self, model: ModelT) -> ModelT: + """Return ``model`` with secret values masked in every nested string. + + Masking one known text field is not enough for tool output: + ``Observation.to_llm_content`` is overridable, and several tools build + what the model sees out of their own fields rather than ``content``. + Walking the whole model is what keeps tool #14 covered by default. + """ + return _mask_model(model, self.mask_secrets_in_output) + def get_secret_infos(self) -> list[dict[str, str | None]]: """Get secret information (name and description) for prompt inclusion. diff --git a/openhands-sdk/openhands/sdk/tool/tool.py b/openhands-sdk/openhands/sdk/tool/tool.py index b94d44ceb8c..40ab0647e44 100644 --- a/openhands-sdk/openhands/sdk/tool/tool.py +++ b/openhands-sdk/openhands/sdk/tool/tool.py @@ -621,20 +621,27 @@ def __call__( # Coerce output only if we declared a model; else wrap in base Observation if self.observation_type: if isinstance(result, self.observation_type): - return result - return self.observation_type.model_validate(result) + observation = result + else: + observation = self.observation_type.model_validate(result) + elif isinstance(result, Observation): + observation = result + elif isinstance(result, BaseModel): + observation = Observation.model_validate(result.model_dump()) + elif isinstance(result, dict): + observation = Observation.model_validate(result) else: - # When no output schema is defined, wrap the result in Observation - if isinstance(result, Observation): - return result - elif isinstance(result, BaseModel): - return Observation.model_validate(result.model_dump()) - elif isinstance(result, dict): - return Observation.model_validate(result) raise TypeError( "Output must be dict or BaseModel when no output schema is defined" ) + # Every tool's output funnels through here, so masking once keeps a new + # tool covered by default instead of by remembering to patch it. + if conversation is None: + return observation + registry = conversation.state.secret_registry + return registry.mask_secrets_in_model(observation) + async def acall( self, action: ActionT, conversation: "LocalConversation | None" = None ) -> Observation: diff --git a/tests/sdk/conversation/test_secret_registry_model_masking.py b/tests/sdk/conversation/test_secret_registry_model_masking.py new file mode 100644 index 00000000000..81284934ac5 --- /dev/null +++ b/tests/sdk/conversation/test_secret_registry_model_masking.py @@ -0,0 +1,124 @@ +"""Unit tests for SecretRegistry.mask_secrets_in_model (issue #4677).""" + +from enum import Enum +from typing import NamedTuple + +from pydantic import BaseModel, SecretStr + +from openhands.sdk.conversation.secret_registry import SecretRegistry + + +SECRET = "sk-supersecret-value" +MASK = "" + + +class Kind(str, Enum): + ADD = "add" + + +class Span(NamedTuple): + label: str + line: int + + +class Inner(BaseModel): + note: str + kind: Kind = Kind.ADD + + +class Outer(BaseModel): + title: str + inner: Inner + items: list[str] = [] + mapping: dict[str, str] = {} + count: int = 0 + blob: bytes = b"" + opaque: SecretStr | None = None + tags: set[str] = set() + span: Span | None = None + + +def _registry() -> SecretRegistry: + registry = SecretRegistry() + registry.update_secrets({"TOKEN": SECRET}) + registry.get_secret_value("TOKEN") # resolve -> tracked for masking + return registry + + +def test_masks_nested_models_lists_and_dict_values(): + model = Outer( + title=f"title {SECRET}", + inner=Inner(note=f"note {SECRET}"), + items=[f"a {SECRET}", "b"], + mapping={"k": f"v {SECRET}"}, + ) + + masked = _registry().mask_secrets_in_model(model) + + assert masked.title == f"title {MASK}" + assert masked.inner.note == f"note {MASK}" + assert masked.items == [f"a {MASK}", "b"] + assert masked.mapping == {"k": f"v {MASK}"} + assert SECRET not in masked.model_dump_json() + + +def test_leaves_non_string_values_alone(): + model = Outer(title="clean", inner=Inner(note="clean"), count=7, blob=b"raw") + + masked = _registry().mask_secrets_in_model(model) + + assert masked.count == 7 + assert masked.blob == b"raw" + + +def test_preserves_str_subclass_enum_members(): + """A str-subclass enum must stay an enum member. + + Masking it would downgrade it to a plain ``str`` and break the field's + serialization, and its vocabulary can never hold a secret anyway. + """ + model = Outer(title="clean", inner=Inner(note="clean", kind=Kind.ADD)) + + masked = _registry().mask_secrets_in_model(model) + + assert masked.inner.kind is Kind.ADD + assert isinstance(masked.inner.kind, Kind) + + +def test_secretstr_is_not_walked_as_a_string(): + model = Outer(title="clean", inner=Inner(note="clean"), opaque=SecretStr(SECRET)) + + masked = _registry().mask_secrets_in_model(model) + + assert isinstance(masked.opaque, SecretStr) + assert masked.opaque.get_secret_value() == SECRET + + +def test_returns_input_unchanged_when_nothing_is_registered(): + model = Outer(title=f"title {SECRET}", inner=Inner(note="clean")) + + masked = SecretRegistry().mask_secrets_in_model(model) + + assert masked.title == f"title {SECRET}" + + +def test_masks_set_members(): + """A ``set`` field is walked like any other container.""" + model = Outer( + title="clean", inner=Inner(note="clean"), tags={f"t {SECRET}", "plain"} + ) + + masked = _registry().mask_secrets_in_model(model) + + assert masked.tags == {f"t {MASK}", "plain"} + + +def test_preserves_namedtuple_type(): + """A NamedTuple keeps its type, like an Enum keeps its member.""" + model = Outer(title="clean", inner=Inner(note="clean"), span=Span(f"s {SECRET}", 3)) + + masked = _registry().mask_secrets_in_model(model) + + assert isinstance(masked.span, Span) + assert masked.span.label == f"s {MASK}" + assert masked.span.line == 3 diff --git a/tests/tools/test_tool_output_secret_masking.py b/tests/tools/test_tool_output_secret_masking.py new file mode 100644 index 00000000000..fdee6067dcf --- /dev/null +++ b/tests/tools/test_tool_output_secret_masking.py @@ -0,0 +1,172 @@ +"""Tool output is masked at the shared chokepoint (issue #4677). + +``ToolDefinition.__call__`` is the one place every tool's observation passes +through, so masking there covers a new tool by default rather than by +remembering to patch it. +""" + +import importlib +import inspect +import pkgutil +from pathlib import Path + +import pytest +from pydantic import SecretStr + +from openhands.sdk.agent import Agent +from openhands.sdk.conversation.impl.local_conversation import LocalConversation +from openhands.sdk.llm import LLM +from openhands.sdk.tool import Tool, ToolDefinition, register_tool +from openhands.tools.apply_patch.definition import ( + ApplyPatchAction, + ApplyPatchObservation, + ApplyPatchTool, +) +from openhands.tools.file_editor import FileEditorTool +from openhands.tools.file_editor.definition import FileEditorAction +from openhands.tools.glob import GlobTool +from openhands.tools.glob.definition import GlobAction, GlobObservation +from openhands.tools.grep import GrepTool +from openhands.tools.grep.definition import GrepAction, GrepObservation + + +SECRET = "sk-supersecret-value" +MASK = "" + +_TOOLS = { + "FileEditorTool": FileEditorTool, + "GrepTool": GrepTool, + "GlobTool": GlobTool, + "ApplyPatchTool": ApplyPatchTool, +} + + +@pytest.fixture +def conversation(tmp_path: Path) -> LocalConversation: + for name, cls in _TOOLS.items(): + register_tool(name, cls) + llm = LLM(model="gpt-4o-mini", api_key=SecretStr("test-key"), usage_id="test-llm") + agent = Agent(llm=llm, tools=[Tool(name=name) for name in _TOOLS]) + convo = LocalConversation(agent, workspace=str(tmp_path)) + convo._ensure_agent_ready() + convo.update_secrets({"TOKEN": SECRET}) + return convo + + +def test_file_editor_view_masks_file_contents( + conversation: LocalConversation, tmp_path: Path +): + """The headline case: reading a secret-bearing file no longer leaks it.""" + env = tmp_path / ".env" + env.write_text(f"API_KEY={SECRET}\n") + + action = FileEditorAction(command="view", path=str(env)) + observation = conversation.agent.tools_map["file_editor"](action, conversation) + + assert SECRET not in observation.text + assert f"API_KEY={MASK}" in observation.text + # The file itself is untouched — only the returned record is masked. + assert env.read_text() == f"API_KEY={SECRET}\n" + + +def test_grep_masks_the_echoed_pattern(conversation: LocalConversation, tmp_path: Path): + """``grep`` returns paths, not file contents — the leak is the echoed pattern.""" + action = GrepAction(pattern=SECRET, path=str(tmp_path)) + observation = conversation.agent.tools_map["grep"](action, conversation) + + assert isinstance(observation, GrepObservation) + assert observation.pattern == MASK + assert SECRET not in observation.text + + +def test_glob_masks_a_matched_path(conversation: LocalConversation, tmp_path: Path): + """``glob`` returns paths, so a secret-bearing filename is the leak.""" + (tmp_path / f"note-{SECRET}.txt").write_text("hi\n") + + action = GlobAction(pattern="*.txt", path=str(tmp_path)) + observation = conversation.agent.tools_map["glob"](action, conversation) + + assert isinstance(observation, GlobObservation) + assert observation.files and all(SECRET not in f for f in observation.files) + assert SECRET not in observation.text + + +def test_apply_patch_masks_nested_commit_content(conversation: LocalConversation): + """The nested-model case ``Observation.content`` masking would have missed. + + The secret lands in ``commit.changes[...].new_content``, not in ``content``. + """ + patch = ( + f"*** Begin Patch\n*** Add File: secrets.txt\n+TOKEN={SECRET}\n*** End Patch" + ) + action = ApplyPatchAction(patch=patch) + observation = conversation.agent.tools_map["apply_patch"](action, conversation) + + assert isinstance(observation, ApplyPatchObservation) + assert observation.commit is not None + change = observation.commit.changes["secrets.txt"] + assert change.new_content == f"TOKEN={MASK}" + assert SECRET not in observation.model_dump_json() + + +def test_no_conversation_means_no_masking(tmp_path: Path): + """Called without a conversation there is no registry, so nothing is masked.""" + for name, cls in _TOOLS.items(): + register_tool(name, cls) + llm = LLM(model="gpt-4o-mini", api_key=SecretStr("test-key"), usage_id="test-llm") + agent = Agent(llm=llm, tools=[Tool(name="FileEditorTool")]) + convo = LocalConversation(agent, workspace=str(tmp_path)) + convo._ensure_agent_ready() + + env = tmp_path / ".env" + env.write_text(f"API_KEY={SECRET}\n") + action = FileEditorAction(command="view", path=str(env)) + observation = convo.agent.tools_map["file_editor"](action, None) + + assert SECRET in observation.text + + +def _all_tool_definition_subclasses() -> set[type[ToolDefinition]]: + """Import every shipped tool package, then collect ToolDefinition subclasses.""" + import openhands.tools + + for module in pkgutil.walk_packages( + openhands.tools.__path__, prefix="openhands.tools." + ): + try: + importlib.import_module(module.name) + except Exception: # optional extras must not fail the guard + continue + + def walk(cls): + for sub in cls.__subclasses__(): + yield sub + yield from walk(sub) + + return set(walk(ToolDefinition)) + + +def test_no_tool_bypasses_the_masking_chokepoint(): + """Fails when a new tool overrides __call__ without delegating to super(). + + This is the property the issue asks for: tool #14 is covered by default. + An override that builds its own Observation and returns it silently opts + out of masking, so it has to go through ``super().__call__``. + """ + offenders = [] + for cls in _all_tool_definition_subclasses(): + override = cls.__dict__.get("__call__") + if override is None: + continue + try: + source = inspect.getsource(override) + except (OSError, TypeError): # pragma: no cover - source always available + continue + if "super().__call__" not in source: + offenders.append(f"{cls.__module__}.{cls.__qualname__}") + + assert not offenders, ( + "These ToolDefinition subclasses override __call__ without delegating to " + "super().__call__, so their output never reaches the secret-masking " + f"chokepoint: {sorted(offenders)}" + )