From f6964f03b895134995171b0ed4c99ac60b0890e4 Mon Sep 17 00:00:00 2001 From: haya-asif Date: Wed, 24 Jun 2026 18:58:00 +0500 Subject: [PATCH 1/3] fix(sdk): redact plugin/extension source credentials via the secret convention (#3752) --- .../sdk/conversation/conversation.py | 8 ++- .../conversation/impl/remote_conversation.py | 11 +++- .../sdk/extensions/installation/info.py | 25 ++++++- .../sdk/extensions/installation/metadata.py | 11 +++- openhands-sdk/openhands/sdk/plugin/types.py | 24 ++++++- .../openhands/sdk/utils/pydantic_secrets.py | 49 ++++++++++++++ .../remote/test_remote_conversation.py | 27 ++++++++ .../installation/test_installation_info.py | 25 +++++++ .../test_installation_metadata.py | 17 +++++ tests/sdk/git/test_url_redaction.py | 65 +++++++++++++++++++ .../test_cloud_workspace_automation_tags.py | 24 +++++++ 11 files changed, 279 insertions(+), 7 deletions(-) diff --git a/openhands-sdk/openhands/sdk/conversation/conversation.py b/openhands-sdk/openhands/sdk/conversation/conversation.py index 2bdf2b62a4d..b9f2f7ff369 100644 --- a/openhands-sdk/openhands/sdk/conversation/conversation.py +++ b/openhands-sdk/openhands/sdk/conversation/conversation.py @@ -20,6 +20,7 @@ from openhands.sdk.plugin import PluginSource from openhands.sdk.secret import SecretValue from openhands.sdk.tool.client_tool import ClientToolSpec +from openhands.sdk.utils.redact import redact_url_credentials from openhands.sdk.workspace import LocalWorkspace, RemoteWorkspace @@ -171,7 +172,12 @@ def __new__( # 2. Auto-generate plugins/skills tag from plugins parameter if plugins: - plugin_urls = [p.source_url for p in plugins if p.source_url] + # tags are a plain dict persisted verbatim — redact creds here. + plugin_urls = [ + redact_url_credentials(url) + for p in plugins + if (url := p.source_url) + ] if plugin_urls: effective_tags["plugins"] = ",".join(plugin_urls) logger.debug(f"Added plugins tag with {len(plugin_urls)} plugin(s)") diff --git a/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py b/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py index 2c010d7dcb6..941212258f8 100644 --- a/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py +++ b/openhands-sdk/openhands/sdk/conversation/impl/remote_conversation.py @@ -785,8 +785,15 @@ def __init__( "tool_module_qualnames": tool_qualnames, # Include agent definitions for subagent registration on server "agent_definitions": serialized_defs, - # Include plugins to load on server - "plugins": [p.model_dump() for p in plugins] if plugins else None, + # expose_secrets: send the real source so the server can clone. + "plugins": ( + [ + p.model_dump(mode="json", context={"expose_secrets": True}) + for p in plugins + ] + if plugins + else None + ), # Include hook_config for server-side hooks "hook_config": hook_config.model_dump() if hook_config else None, # Include client-defined tool specs (no server-side executor) diff --git a/openhands-sdk/openhands/sdk/extensions/installation/info.py b/openhands-sdk/openhands/sdk/extensions/installation/info.py index d1ef16ae601..fcddb0bbdd9 100644 --- a/openhands-sdk/openhands/sdk/extensions/installation/info.py +++ b/openhands-sdk/openhands/sdk/extensions/installation/info.py @@ -2,10 +2,22 @@ from datetime import UTC, datetime from pathlib import Path +from typing import Any -from pydantic import BaseModel, Field +from pydantic import ( + BaseModel, + Field, + FieldSerializationInfo, + ValidationInfo, + field_serializer, + field_validator, +) from openhands.sdk.extensions.installation.interface import ExtensionProtocol +from openhands.sdk.utils.pydantic_secrets import ( + serialize_credential_url, + validate_credential_url, +) class InstallationInfo(BaseModel): @@ -36,6 +48,17 @@ class InstallationInfo(BaseModel): ) install_path: Path = Field(description="Path where the extension is installed") + @field_validator("source", mode="before") + @classmethod + def _decrypt_source(cls, v: Any, info: ValidationInfo) -> Any: + """Decrypt at-rest ciphertext (see validate_credential_url).""" + return validate_credential_url(v, info) + + @field_serializer("source", when_used="always") + def _serialize_source(self, source: str, info: FieldSerializationInfo) -> str: + """Redact/expose/encrypt by context (see serialize_credential_url).""" + return serialize_credential_url(source, info) + @staticmethod def from_extension( extension: ExtensionProtocol, diff --git a/openhands-sdk/openhands/sdk/extensions/installation/metadata.py b/openhands-sdk/openhands/sdk/extensions/installation/metadata.py index b7e54613e06..18e71c0d80a 100644 --- a/openhands-sdk/openhands/sdk/extensions/installation/metadata.py +++ b/openhands-sdk/openhands/sdk/extensions/installation/metadata.py @@ -156,10 +156,17 @@ def load_from_dir(cls, installed_dir: Path) -> InstallationMetadata: return cls() def save_to_dir(self, installed_dir: Path) -> None: - """Save metadata to the installed extensions directory.""" + """Save metadata to the installed extensions directory. + + Written with ``expose_secrets`` so the stored ``source`` survives for + ``ExtensionManager.update()`` (no cipher in this layer); default dumps + still redact. + """ metadata_path = self.get_metadata_path(installed_dir) metadata_path.parent.mkdir(parents=True, exist_ok=True) - metadata_path.write_text(self.model_dump_json(indent=2)) + metadata_path.write_text( + self.model_dump_json(indent=2, context={"expose_secrets": "plaintext"}) + ) def validate_tracked(self, installed_dir: Path) -> list[InstallationInfo]: """Validate tracked extensions exist on disk. diff --git a/openhands-sdk/openhands/sdk/plugin/types.py b/openhands-sdk/openhands/sdk/plugin/types.py index 48fd4a62281..3e48face063 100644 --- a/openhands-sdk/openhands/sdk/plugin/types.py +++ b/openhands-sdk/openhands/sdk/plugin/types.py @@ -6,9 +6,20 @@ from typing import TYPE_CHECKING, Any import frontmatter -from pydantic import BaseModel, Field, field_validator +from pydantic import ( + BaseModel, + Field, + FieldSerializationInfo, + ValidationInfo, + field_serializer, + field_validator, +) from openhands.sdk.utils.path import to_posix_path +from openhands.sdk.utils.pydantic_secrets import ( + serialize_credential_url, + validate_credential_url, +) from openhands.sdk.utils.redact import redact_url_credentials @@ -64,6 +75,17 @@ def validate_repo_path(cls, v: str | None) -> str | None: ) return v + @field_validator("source", mode="before") + @classmethod + def _decrypt_source(cls, v: Any, info: ValidationInfo) -> Any: + """Decrypt at-rest ciphertext (see validate_credential_url).""" + return validate_credential_url(v, info) + + @field_serializer("source", when_used="always") + def _serialize_source(self, source: str, info: FieldSerializationInfo) -> str: + """Redact/expose/encrypt by context (see serialize_credential_url).""" + return serialize_credential_url(source, info) + @property def source_url(self) -> str | None: """Convert the plugin source to a canonical URL. diff --git a/openhands-sdk/openhands/sdk/utils/pydantic_secrets.py b/openhands-sdk/openhands/sdk/utils/pydantic_secrets.py index f9c7a5de038..8a3c4c2e0d4 100644 --- a/openhands-sdk/openhands/sdk/utils/pydantic_secrets.py +++ b/openhands-sdk/openhands/sdk/utils/pydantic_secrets.py @@ -5,6 +5,7 @@ from pydantic import SecretStr, ValidationInfo from openhands.sdk.utils.cipher import FERNET_TOKEN_PREFIX, Cipher +from openhands.sdk.utils.redact import redact_url_credentials REDACTED_SECRET_VALUE = "**********" @@ -195,3 +196,51 @@ def _decrypt_env(cls, value, info): k: decrypt_str_with_cipher_or_keep(cipher, v, description=description) for k, v in value.items() } + + +def serialize_credential_url(source: str, info) -> str: + """Serialize a source string that may embed credentials. + + Mirrors :func:`serialize_secret`'s context-driven behaviour, but for a + URL-shaped value: in ``redact`` mode only the userinfo is masked + (``https://****@host``) so a non-secret source (``github:owner/repo``, a + local path, a public URL) survives intact and useful in logs / state. + + - **plaintext** -> the real URL (trusted backend only). + - **encrypted** -> Fernet-encrypt via the context ``cipher`` (a ``gAAAAA…`` + token); raises :class:`MissingCipherError` if encrypted mode is resolved + without a cipher (mirrors :func:`serialize_secret`). + - **redact** (default, no context) -> :func:`redact_url_credentials`. + + Pair with :func:`validate_credential_url` (a ``field_validator(mode="before")``) + so the encrypted-at-rest token is decrypted back on load. + """ + mode = resolve_expose_mode(info.context) + if mode == "plaintext": + return source + if mode == "encrypted": + cipher: Cipher | None = info.context.get("cipher") if info.context else None + if cipher is None: + raise MissingCipherError( + "Cannot encrypt credentialed source: no cipher configured. " + "Set OH_SECRET_KEY environment variable." + ) + token = cipher.encrypt(SecretStr(source)) + assert token is not None # encrypt() returns None only for a None input + return token + return redact_url_credentials(source) + + +def validate_credential_url(value: Any, info): + """Load-side counterpart of :func:`serialize_credential_url`. + + Decrypts an at-rest Fernet token back to the real URL when a ``cipher`` is + in context. No-ops on plaintext, non-token and non-str values, so it is safe + as a ``field_validator(mode="before")`` on every construction path. Unlike + :func:`validate_secret`, a redacted URL is kept as-is rather than collapsed + to ``None`` — a credential-free URL is still a usable source. + """ + cipher: Cipher | None = info.context.get("cipher") if info.context else None + if cipher is None: + return value + return decrypt_str_with_cipher_or_keep(cipher, value, description="plugin source") diff --git a/tests/sdk/conversation/remote/test_remote_conversation.py b/tests/sdk/conversation/remote/test_remote_conversation.py index 409b5aa38b3..64c030c2d97 100644 --- a/tests/sdk/conversation/remote/test_remote_conversation.py +++ b/tests/sdk/conversation/remote/test_remote_conversation.py @@ -251,6 +251,33 @@ def test_remote_conversation_sends_observability_fields(self, mock_ws_client): assert payload["observability_tags"] == ["sdk", "remote"] assert payload["user_id"] == "test-user-42" + @patch( + "openhands.sdk.conversation.impl.remote_conversation.WebSocketCallbackClient" + ) + def test_remote_conversation_sends_real_plugin_source(self, mock_ws_client): + """The create payload must carry the real plugin source (credential + + ${VAR} placeholder) so the server can clone a private plugin (B2).""" + from openhands.sdk.plugin import PluginSource + + conversation_id = str(uuid.uuid4()) + mock_client_instance = self.setup_mock_client(conversation_id=conversation_id) + mock_ws_client.return_value = Mock() + + source = "https://x-token-auth:${MY_TOKEN}@host/org/repo.git" + RemoteConversation( + agent=self.agent, + workspace=self.workspace, + plugins=[PluginSource(source=source)], + ) + + create_call = next( + call + for call in mock_client_instance.request.call_args_list + if call[0][0] == "POST" and call[0][1] == "/api/conversations" + ) + payload = create_call.kwargs["json"] + assert payload["plugins"][0]["source"] == source + @patch( "openhands.sdk.conversation.impl.remote_conversation.WebSocketCallbackClient" ) diff --git a/tests/sdk/extensions/installation/test_installation_info.py b/tests/sdk/extensions/installation/test_installation_info.py index c334c51e3cf..473168e1252 100644 --- a/tests/sdk/extensions/installation/test_installation_info.py +++ b/tests/sdk/extensions/installation/test_installation_info.py @@ -3,6 +3,7 @@ from pathlib import Path from openhands.sdk.extensions.installation import InstallationInfo +from openhands.sdk.utils.cipher import Cipher @dataclass @@ -34,3 +35,27 @@ def test_installation_info_from_extension(): assert info.repo_path is None assert datetime.fromisoformat(info.installed_at) + + +def test_source_redacted_by_default_exposed_under_context(): + """Default dumps mask the credential; expose_secrets keeps the real source.""" + cred = "https://oauth2:SUPER_SECRET@github.com/org/repo.git" + info = InstallationInfo(name="x", source=cred, install_path=Path("/tmp/x")) + assert info.source == cred # raw in memory + assert "SUPER_SECRET" not in info.model_dump_json() # default redacts + assert info.model_dump(context={"expose_secrets": "plaintext"})["source"] == cred + + +def test_source_encrypts_at_rest_under_cipher(): + """A cipher context encrypts the source and decrypts it back on load.""" + cipher = Cipher("k") + cred = "https://oauth2:SUPER_SECRET@github.com/org/repo.git" + info = InstallationInfo(name="x", source=cred, install_path=Path("/tmp/x")) + token = info.model_dump(context={"cipher": cipher})["source"] + assert token.startswith("gAAAAA") + assert "SUPER_SECRET" not in token + back = InstallationInfo.model_validate( + {"name": "x", "source": token, "install_path": "/tmp/x"}, + context={"cipher": cipher}, + ) + assert back.source == cred diff --git a/tests/sdk/extensions/installation/test_installation_metadata.py b/tests/sdk/extensions/installation/test_installation_metadata.py index bf9d662192b..1bba894e69a 100644 --- a/tests/sdk/extensions/installation/test_installation_metadata.py +++ b/tests/sdk/extensions/installation/test_installation_metadata.py @@ -226,6 +226,23 @@ def test_load_from_dir_and_save_to_dir(tmp_path: Path): assert metadata == loaded_metadata +def test_installed_json_keeps_source_for_update(tmp_path: Path): + """.installed.json keeps the real source so ExtensionManager.update() can + re-clone (this layer has no cipher); a default dump still redacts.""" + installation_dir = tmp_path / "installed" + installation_dir.mkdir() + cred = "https://oauth2:SUPER_SECRET@github.com/org/repo.git" + info = InstallationInfo( + name="ext", source=cred, install_path=installation_dir / "ext" + ) + InstallationMetadata(extensions={"ext": info}).save_to_dir(installation_dir) + + reloaded = InstallationMetadata.load_from_dir(installation_dir) + assert reloaded.extensions["ext"].source == cred # update() re-clones from this + + assert "SUPER_SECRET" not in info.model_dump_json() # default dump redacts + + def test_load_from_dir_invalid_json(tmp_path: Path): """Test loading invalid JSON returns empty metadata.""" installation_dir = tmp_path / "installed" diff --git a/tests/sdk/git/test_url_redaction.py b/tests/sdk/git/test_url_redaction.py index 084948844b0..38bdbe6b5ca 100644 --- a/tests/sdk/git/test_url_redaction.py +++ b/tests/sdk/git/test_url_redaction.py @@ -12,6 +12,7 @@ run_git_command, ) # re-exported for compat from openhands.sdk.plugin.types import PluginSource, ResolvedPluginSource +from openhands.sdk.utils.cipher import Cipher from openhands.sdk.utils.redact import ( redact_url_credentials as redact_url_credentials_central, ) @@ -194,6 +195,70 @@ def test_serialization_does_not_expose_credentials(self): assert "****" in json_str +class TestPluginSourceCredentialRedaction: + """PluginSource.source hooks into the SDK secret convention (redact / expose + / encrypt-at-rest) while keeping the URL shape in redact mode.""" + + CRED = "https://oauth2:SUPER_SECRET@gitlab.com/org/repo.git" + REDACTED = "https://****@gitlab.com/org/repo.git" + PLACEHOLDER = "https://x-token-auth:${MY_TOKEN}@host/repo.git" + + def test_default_dump_redacts_only_the_credential(self): + # No context -> redact, but keep the URL shape (not a full ********** mask). + assert PluginSource(source=self.CRED).model_dump()["source"] == self.REDACTED + assert "SUPER_SECRET" not in PluginSource(source=self.CRED).model_dump_json() + + def test_in_memory_value_is_raw_for_fetch(self): + # The attribute keeps the real URL so the plugin can still be cloned. + assert PluginSource(source=self.CRED).source == self.CRED + + def test_plaintext_exposes_real_url(self): + ps = PluginSource(source=self.CRED) + assert ps.model_dump(context={"expose_secrets": True})["source"] == self.CRED + + def test_placeholder_survives_expose(self): + # ${VAR} is not a secret; it must survive trusted dumps for expansion. + ps = PluginSource(source=self.PLACEHOLDER) + assert ( + ps.model_dump(context={"expose_secrets": True})["source"] + == self.PLACEHOLDER + ) + + def test_cipher_encrypts_at_rest_and_round_trips(self): + # Regression guard for the meta.json cleartext blocker: a cipher context + # must ENCRYPT (a gAAAAA token, no cleartext) and decrypt back on load. + cipher = Cipher("test-secret-key") + token = PluginSource(source=self.CRED).model_dump(context={"cipher": cipher})[ + "source" + ] + assert token.startswith("gAAAAA") + assert "SUPER_SECRET" not in token + reloaded = PluginSource.model_validate( + {"source": token}, context={"cipher": cipher} + ) + assert reloaded.source == self.CRED + + @pytest.mark.parametrize( + "source", + [ + "github:owner/repo", + "/path/to/local/plugin", + "git@github.com:owner/repo.git", + "https://github.com/owner/repo.git", + ], + ) + def test_non_credential_sources_unchanged(self, source): + assert PluginSource(source=source).model_dump()["source"] == source + cipher = Cipher("k") + token = PluginSource(source=source).model_dump(context={"cipher": cipher})[ + "source" + ] + back = PluginSource.model_validate( + {"source": token}, context={"cipher": cipher} + ) + assert back.source == source + + class TestRedactUrlCredentialsCentralModule: """Verify redact_url_credentials is accessible from the central redact module.""" diff --git a/tests/workspace/test_cloud_workspace_automation_tags.py b/tests/workspace/test_cloud_workspace_automation_tags.py index 1f315250060..5b2335fe11f 100644 --- a/tests/workspace/test_cloud_workspace_automation_tags.py +++ b/tests/workspace/test_cloud_workspace_automation_tags.py @@ -375,6 +375,30 @@ def test_plugins_added_as_urls_in_tags(self): ) assert "https://github.com/OpenHands/review-skill" in plugin_urls + def test_credentials_redacted_in_plugins_tag(self): + """A credential in a plugin source must not reach the persisted tag (B3).""" + from unittest.mock import MagicMock + + from openhands.sdk.conversation.conversation import Conversation + from openhands.sdk.plugin import PluginSource + from openhands.sdk.workspace import RemoteWorkspace + + mock_workspace = MagicMock(spec=RemoteWorkspace) + mock_workspace.default_conversation_tags = {} + + plugins = [ + PluginSource(source="https://oauth2:SUPER_SECRET@github.com/org/repo.git") + ] + with patch( + "openhands.sdk.conversation.impl.remote_conversation.RemoteConversation" + ) as mock_convo_class: + mock_convo_class.return_value = MagicMock() + Conversation(agent=MagicMock(), workspace=mock_workspace, plugins=plugins) + tag = mock_convo_class.call_args.kwargs["tags"]["plugins"] + + assert "SUPER_SECRET" not in tag + assert tag == "https://****@github.com/org/repo.git" + def test_local_plugins_not_included_in_tags(self): """Should not include local path plugins in tags.""" from unittest.mock import MagicMock From 9aa5c7d12948d6007215f9b792d720023985dbc4 Mon Sep 17 00:00:00 2001 From: haya-asif Date: Thu, 25 Jun 2026 14:48:57 +0500 Subject: [PATCH 2/3] test(sdk): regression guards for credentialed extension update and plugin-load logs --- .../remote/test_remote_conversation.py | 4 +-- .../test_local_conversation_plugins.py | 34 +++++++++++++++++++ .../installation/test_installation_manager.py | 21 ++++++++++++ tests/sdk/git/test_url_redaction.py | 4 +-- .../test_cloud_workspace_automation_tags.py | 14 ++++---- 5 files changed, 65 insertions(+), 12 deletions(-) diff --git a/tests/sdk/conversation/remote/test_remote_conversation.py b/tests/sdk/conversation/remote/test_remote_conversation.py index 64c030c2d97..5b7574f7127 100644 --- a/tests/sdk/conversation/remote/test_remote_conversation.py +++ b/tests/sdk/conversation/remote/test_remote_conversation.py @@ -255,8 +255,8 @@ def test_remote_conversation_sends_observability_fields(self, mock_ws_client): "openhands.sdk.conversation.impl.remote_conversation.WebSocketCallbackClient" ) def test_remote_conversation_sends_real_plugin_source(self, mock_ws_client): - """The create payload must carry the real plugin source (credential + - ${VAR} placeholder) so the server can clone a private plugin (B2).""" + """The create payload carries the real plugin source (credential and + ${VAR} placeholder intact) so the server can clone a private plugin.""" from openhands.sdk.plugin import PluginSource conversation_id = str(uuid.uuid4()) diff --git a/tests/sdk/conversation/test_local_conversation_plugins.py b/tests/sdk/conversation/test_local_conversation_plugins.py index 02c50258e58..fd398440764 100644 --- a/tests/sdk/conversation/test_local_conversation_plugins.py +++ b/tests/sdk/conversation/test_local_conversation_plugins.py @@ -795,6 +795,40 @@ def test_plugin_hooks_combined_with_explicit_hooks( # (The actual hook_processor is internal, but we trust the merging works) conversation.close() + def test_plugin_load_log_never_leaks_credentials( + self, tmp_path: Path, basic_agent, caplog: pytest.LogCaptureFixture + ): + """Plugin-load logs must never contain the source credential. + + The serializer only covers model dumps, not f-string log lines, so the + load path has to keep the raw source out of its log messages. + """ + plugin_dir = create_test_plugin( + tmp_path / "plugin", + name="test-plugin", + skills=[{"name": "s", "content": "c"}], + ) + workspace = tmp_path / "workspace" + workspace.mkdir() + conversation = LocalConversation( + agent=basic_agent, + workspace=workspace, + plugins=[ + PluginSource(source="https://oauth2:LEAKME@host.example.com/o/r.git") + ], + visualizer=None, + ) + with patch( + "openhands.sdk.conversation.impl.local_conversation." + "fetch_plugin_with_resolution", + return_value=(plugin_dir, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"), + ): + with caplog.at_level(logging.DEBUG): + conversation._ensure_plugins_loaded() + + assert "LEAKME" not in caplog.text + conversation.close() + def test_hook_sub_conversations_receive_persistence_base_dir( self, tmp_path: Path, basic_agent ): diff --git a/tests/sdk/extensions/installation/test_installation_manager.py b/tests/sdk/extensions/installation/test_installation_manager.py index 02961bad07f..04135ef7256 100644 --- a/tests/sdk/extensions/installation/test_installation_manager.py +++ b/tests/sdk/extensions/installation/test_installation_manager.py @@ -1,5 +1,6 @@ import shutil from pathlib import Path +from unittest.mock import patch import pytest from pydantic import BaseModel @@ -103,6 +104,26 @@ def test_install_from_local_path( assert mock_extension.name in metadata.extensions +def test_update_reclones_with_credentialed_source( + manager: InstallationManager[MockExtension], + mock_extension_dir: Path, + mock_extension: MockExtension, +): + """update() re-clones using the real credential stored in .installed.json + (a redacted source there would make a private-extension update fail to clone).""" + cred = "https://oauth2:SUPER_SECRET@github.com/org/repo.git" + with patch( + "openhands.sdk.extensions.installation.manager.fetch_with_resolution", + return_value=(mock_extension_dir, "abc123"), + ) as mock_fetch: + manager.install(source=cred, force=True) # records cred in .installed.json + mock_fetch.reset_mock() + manager.update(mock_extension.name) # re-fetch from the stored source + + assert mock_fetch.call_count == 1 + assert mock_fetch.call_args.kwargs["source"] == cred + + def test_install_already_exist_raises_error( manager: InstallationManager[MockExtension], mock_extension_dir: Path, diff --git a/tests/sdk/git/test_url_redaction.py b/tests/sdk/git/test_url_redaction.py index 38bdbe6b5ca..2556b985d13 100644 --- a/tests/sdk/git/test_url_redaction.py +++ b/tests/sdk/git/test_url_redaction.py @@ -225,8 +225,8 @@ def test_placeholder_survives_expose(self): ) def test_cipher_encrypts_at_rest_and_round_trips(self): - # Regression guard for the meta.json cleartext blocker: a cipher context - # must ENCRYPT (a gAAAAA token, no cleartext) and decrypt back on load. + # A cipher context encrypts the source (gAAAAA token, no cleartext) and + # decrypts it back on load. cipher = Cipher("test-secret-key") token = PluginSource(source=self.CRED).model_dump(context={"cipher": cipher})[ "source" diff --git a/tests/workspace/test_cloud_workspace_automation_tags.py b/tests/workspace/test_cloud_workspace_automation_tags.py index 5b2335fe11f..23a30628dd4 100644 --- a/tests/workspace/test_cloud_workspace_automation_tags.py +++ b/tests/workspace/test_cloud_workspace_automation_tags.py @@ -2,10 +2,14 @@ import json import os -from unittest.mock import patch +from unittest.mock import MagicMock, patch import pytest +from openhands.sdk.conversation.conversation import Conversation +from openhands.sdk.plugin import PluginSource +from openhands.sdk.workspace import RemoteWorkspace + class TestDefaultConversationTags: """Tests for the default_conversation_tags property.""" @@ -376,13 +380,7 @@ def test_plugins_added_as_urls_in_tags(self): assert "https://github.com/OpenHands/review-skill" in plugin_urls def test_credentials_redacted_in_plugins_tag(self): - """A credential in a plugin source must not reach the persisted tag (B3).""" - from unittest.mock import MagicMock - - from openhands.sdk.conversation.conversation import Conversation - from openhands.sdk.plugin import PluginSource - from openhands.sdk.workspace import RemoteWorkspace - + """A credential in a plugin source must not reach the persisted tag.""" mock_workspace = MagicMock(spec=RemoteWorkspace) mock_workspace.default_conversation_tags = {} From eafb78df06427380be7c13d5b276a2b3cd04eb2d Mon Sep 17 00:00:00 2001 From: haya-asif Date: Thu, 25 Jun 2026 15:21:15 +0500 Subject: [PATCH 3/3] docs(sdk): keep credential-redaction docstrings brief --- .../sdk/extensions/installation/metadata.py | 7 +---- .../openhands/sdk/utils/pydantic_secrets.py | 28 +++---------------- .../test_local_conversation_plugins.py | 7 ++--- 3 files changed, 7 insertions(+), 35 deletions(-) diff --git a/openhands-sdk/openhands/sdk/extensions/installation/metadata.py b/openhands-sdk/openhands/sdk/extensions/installation/metadata.py index 18e71c0d80a..ee5d4783d0b 100644 --- a/openhands-sdk/openhands/sdk/extensions/installation/metadata.py +++ b/openhands-sdk/openhands/sdk/extensions/installation/metadata.py @@ -156,12 +156,7 @@ def load_from_dir(cls, installed_dir: Path) -> InstallationMetadata: return cls() def save_to_dir(self, installed_dir: Path) -> None: - """Save metadata to the installed extensions directory. - - Written with ``expose_secrets`` so the stored ``source`` survives for - ``ExtensionManager.update()`` (no cipher in this layer); default dumps - still redact. - """ + """Save metadata to the installed extensions directory.""" metadata_path = self.get_metadata_path(installed_dir) metadata_path.parent.mkdir(parents=True, exist_ok=True) metadata_path.write_text( diff --git a/openhands-sdk/openhands/sdk/utils/pydantic_secrets.py b/openhands-sdk/openhands/sdk/utils/pydantic_secrets.py index 8a3c4c2e0d4..c61c47f6587 100644 --- a/openhands-sdk/openhands/sdk/utils/pydantic_secrets.py +++ b/openhands-sdk/openhands/sdk/utils/pydantic_secrets.py @@ -199,22 +199,9 @@ def _decrypt_env(cls, value, info): def serialize_credential_url(source: str, info) -> str: - """Serialize a source string that may embed credentials. - - Mirrors :func:`serialize_secret`'s context-driven behaviour, but for a - URL-shaped value: in ``redact`` mode only the userinfo is masked - (``https://****@host``) so a non-secret source (``github:owner/repo``, a - local path, a public URL) survives intact and useful in logs / state. - - - **plaintext** -> the real URL (trusted backend only). - - **encrypted** -> Fernet-encrypt via the context ``cipher`` (a ``gAAAAA…`` - token); raises :class:`MissingCipherError` if encrypted mode is resolved - without a cipher (mirrors :func:`serialize_secret`). - - **redact** (default, no context) -> :func:`redact_url_credentials`. - - Pair with :func:`validate_credential_url` (a ``field_validator(mode="before")``) - so the encrypted-at-rest token is decrypted back on load. - """ + """Serialize a credential-bearing URL by context: the real value under + ``expose_secrets``, an encrypted token under a ``cipher``, else only the + userinfo redacted (``https://****@host``).""" mode = resolve_expose_mode(info.context) if mode == "plaintext": return source @@ -232,14 +219,7 @@ def serialize_credential_url(source: str, info) -> str: def validate_credential_url(value: Any, info): - """Load-side counterpart of :func:`serialize_credential_url`. - - Decrypts an at-rest Fernet token back to the real URL when a ``cipher`` is - in context. No-ops on plaintext, non-token and non-str values, so it is safe - as a ``field_validator(mode="before")`` on every construction path. Unlike - :func:`validate_secret`, a redacted URL is kept as-is rather than collapsed - to ``None`` — a credential-free URL is still a usable source. - """ + """Decrypt an at-rest cipher token back to the URL; no-op without a cipher.""" cipher: Cipher | None = info.context.get("cipher") if info.context else None if cipher is None: return value diff --git a/tests/sdk/conversation/test_local_conversation_plugins.py b/tests/sdk/conversation/test_local_conversation_plugins.py index fd398440764..56acf17449d 100644 --- a/tests/sdk/conversation/test_local_conversation_plugins.py +++ b/tests/sdk/conversation/test_local_conversation_plugins.py @@ -798,11 +798,8 @@ def test_plugin_hooks_combined_with_explicit_hooks( def test_plugin_load_log_never_leaks_credentials( self, tmp_path: Path, basic_agent, caplog: pytest.LogCaptureFixture ): - """Plugin-load logs must never contain the source credential. - - The serializer only covers model dumps, not f-string log lines, so the - load path has to keep the raw source out of its log messages. - """ + """Plugin-load logs must never contain the source credential (the + serializer covers model dumps, not f-string log lines).""" plugin_dir = create_test_plugin( tmp_path / "plugin", name="test-plugin",