π OpenHands: AI-Driven Development
fix(security): redact MCP config secrets before logging (#13913)
OpenHands Bote11faa6dd196
diff --git a/openhands/runtime/action_execution_server.py b/openhands/runtime/action_execution_server.pyindex 9696e061b7..d33ff8c8e8 100644--- a/openhands/runtime/action_execution_server.py+++ b/openhands/runtime/action_execution_server.py@@ -14,7 +14,6 @@ NOTE: this will be executed inside the docker sandbox.import argparseimport asyncioimport base64-import jsonimport mimetypesimport osimport shutil@@ -82,6 +81,7 @@ from openhands.runtime.utils.bash import BashSessionfrom openhands.runtime.utils.files import insert_lines, read_linesfrom openhands.runtime.utils.memory_monitor import MemoryMonitorfrom openhands.runtime.utils.runtime_init import init_user_and_working_directory+from openhands.utils._redact_compat import redact_text_secretsfrom openhands.utils.async_utils import call_sync_from_async, wait_allif sys.platform == 'win32':@@ -871,7 +871,7 @@ if __name__ == '__main__':status_code=400, detail='Request must be a list of MCP tools to sync')logger.info(- f'Updating MCP server with tools: {json.dumps(mcp_tools_to_sync, indent=2)}'+ f'Updating MCP server with tools: {redact_text_secrets(str(mcp_tools_to_sync))}')mcp_tools_to_sync = [MCPStdioServerConfig(**tool) for tool in mcp_tools_to_sync]try:diff --git a/openhands/runtime/impl/action_execution/action_execution_client.py b/openhands/runtime/impl/action_execution/action_execution_client.pyindex 9d7765264a..8cfa386971 100644--- a/openhands/runtime/impl/action_execution/action_execution_client.py+++ b/openhands/runtime/impl/action_execution/action_execution_client.py@@ -55,6 +55,7 @@ from openhands.llm.llm_registry import LLMRegistryfrom openhands.runtime.base import Runtimefrom openhands.runtime.plugins import PluginRequirementfrom openhands.runtime.utils.request import send_request+from openhands.utils._redact_compat import redact_text_secretsfrom openhands.utils.http_session import HttpSessionfrom openhands.utils.tenacity_stop import stop_if_should_exit@@ -399,7 +400,7 @@ class ActionExecutionClient(Runtime):self.log('debug',- f'adding {len(new_servers)} new stdio servers to MCP config: {new_servers}',+ f'adding {len(new_servers)} new stdio servers to MCP config: {redact_text_secrets(str(new_servers))}',)# Only send update request if there are new servers@@ -444,7 +445,7 @@ class ActionExecutionClient(Runtime):)self.log('info',- f'Updated MCP config: {updated_mcp_config.sse_servers}',+ f'Updated MCP config: {redact_text_secrets(str(updated_mcp_config.sse_servers))}',)else:self.log('debug', 'No new stdio servers to update')@@ -478,7 +479,7 @@ class ActionExecutionClient(Runtime):updated_mcp_config = self.get_mcp_config()self.log('debug',- f'Creating MCP clients with servers: {updated_mcp_config.sse_servers}',+ f'Creating MCP clients with servers: {redact_text_secrets(str(updated_mcp_config.sse_servers))}',)# Create clients for this specific operationdiff --git a/openhands/utils/_redact_compat.py b/openhands/utils/_redact_compat.pyindex 34472d2a94..b920f850be 100644--- a/openhands/utils/_redact_compat.py+++ b/openhands/utils/_redact_compat.py@@ -123,11 +123,13 @@ def redact_api_key_literals(text: str) -> str:def redact_text_secrets(text: str) -> str:"""Redact secrets from a string representation of a config object."""- # api_key='...' patterns+ # api_key='...' patterns (attribute style)text = re.sub(r"api_key='[^']*'", "api_key='<redacted>'", text)text = re.sub(r'api_key="[^"]*"', 'api_key="<redacted>"', text)+ # 'api_key': '...' patterns (dict style from str())+ text = re.sub(r"('api_key':\s*')[^']*(')", r'\g<1><redacted>\2', text)- # Dict entries with sensitive key names+ # Dict entries with sensitive key names (uppercase)text = re.sub(r"('[A-Z_]*(?:KEY|SECRET|TOKEN|PASSWORD)[A-Z_]*':\s*')[^']*(')",r'\g<1><redacted>\2',diff --git a/tests/unit/utils/test_redact_compat.py b/tests/unit/utils/test_redact_compat.pynew file mode 100644index 0000000000..9bc4ddfcb8--- /dev/null+++ b/tests/unit/utils/test_redact_compat.py@@ -0,0 +1,120 @@+"""Tests for openhands.utils._redact_compat redaction utilities.++These tests verify that MCP config secrets are properly redacted before logging.+"""++from openhands.utils._redact_compat import (+ redact_api_key_literals,+ redact_text_secrets,+ redact_url_params,+)++# The redaction placeholder+REDACTED = '<redacted>'+++class TestRedactTextSecrets:+ """Tests for redact_text_secrets (string-based redaction)."""++ def test_redact_api_key_in_string_repr(self):+ """Test redacting api_key='...' patterns."""+ text = "MCPSSEServerConfig(url='http://localhost', api_key='secret123')"+ redacted = redact_text_secrets(text)+ assert "api_key='<redacted>'" in redacted+ assert 'secret123' not in redacted++ def test_redact_env_dict_in_string(self):+ """Test redacting env dict secrets in string representation."""+ text = "{'TAVILY_API_KEY': 'tvly-abc123', 'OTHER': 'visible'}"+ redacted = redact_text_secrets(text)+ assert 'tvly-abc123' not in redacted+ assert "'TAVILY_API_KEY': '<redacted>'" in redacted++ def test_redact_x_session_api_key_header(self):+ """Test redacting X-Session-API-Key header in string."""+ text = "{'X-Session-API-Key': 'sk-oh-sessionkey123'}"+ redacted = redact_text_secrets(text)+ assert 'sk-oh-sessionkey123' not in redacted+++class TestRedactApiKeyLiterals:+ """Tests for redact_api_key_literals (pattern-based token redaction)."""++ def test_redact_tavily_key(self):+ """Test that Tavily API keys are redacted."""+ text = 'Using key tvly-abc123secretkey for search'+ redacted = redact_api_key_literals(text)+ assert 'tvly-abc123secretkey' not in redacted+ assert '<redacted>' in redacted++ def test_redact_openai_key(self):+ """Test that OpenAI API keys are redacted.++ Note: The regex requires at least 20 chars after the prefix.+ """+ text = 'API key is sk-proj-abc123xyz456def789ghi012'+ redacted = redact_api_key_literals(text)+ assert 'sk-proj-abc123xyz456def789ghi012' not in redacted++ def test_redact_openhands_session_token(self):+ """Test that OpenHands session tokens are redacted."""+ text = 'Session: sk-oh-abc123sessiontoken456'+ redacted = redact_api_key_literals(text)+ assert 'sk-oh-abc123sessiontoken456' not in redacted+++class TestRedactUrlParams:+ """Tests for redact_url_params."""++ def test_redact_apikey_param(self):+ """Test redacting apiKey query parameter."""+ url = 'https://api.example.com/search?apiKey=secret123&query=test'+ redacted = redact_url_params(url)+ assert 'secret123' not in redacted+ # URL-encoded <redacted> is %3Credacted%3E+ assert 'apiKey=' in redacted+ assert 'query=test' in redacted++ def test_redact_token_param(self):+ """Test redacting token query parameter."""+ url = 'https://api.example.com?token=mytoken123'+ redacted = redact_url_params(url)+ assert 'mytoken123' not in redacted+ assert 'token=' in redacted+++class TestMCPConfigLoggingIntegration:+ """Integration tests simulating actual MCP config logging scenarios."""++ def test_mcp_stdio_server_logging_is_safe(self):+ """Simulate logging MCP stdio server configs as done in action_execution_server.py."""+ mcp_tools_to_sync = [+ {+ 'name': 'tavily',+ 'command': 'npx',+ 'args': ['-y', '@tavily/mcp-server'],+ 'env': {'TAVILY_API_KEY': 'tvly-realSecretKey123'},+ }+ ]++ # This is what the code does before logging - just str()+ log_output = redact_text_secrets(str(mcp_tools_to_sync))++ assert 'tvly-realSecretKey123' not in log_output+ assert REDACTED in log_output+ assert 'tavily' in log_output # Name should still be visible++ def test_mcp_sse_server_logging_is_safe(self):+ """Simulate logging MCP SSE server configs as done in action_execution_client.py."""+ sse_servers = [+ {+ 'url': 'http://localhost:8000/mcp/sse',+ 'api_key': 'sk-oh-realSessionKey456',+ }+ ]++ log_output = redact_text_secrets(str(sse_servers))++ assert 'sk-oh-realSessionKey456' not in log_output+ assert REDACTED in log_output+ assert 'http://localhost:8000/mcp/sse' in log_output # URL should be visible