Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Fix: Filter sensitive data from state messages

Cursor Agent8ba95aefa855
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 7e7af5591..d79903e70 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -422,17 +422,22 @@ class MessageManager:
def _set_message_with_type(self, message: BaseMessage, message_type: Literal['system', 'state']) -> None:
"""Replace a specific state message slot with a new message"""
- # Don't filter system and state messages - they should contain placeholder tags or normal conversation
+ # System messages don't need filtering - they only contain instructions/placeholders
+ # State messages need filtering - they include agent_history_description which contains
+ # action results with real sensitive values (after placeholder replacement during execution)
if message_type == 'system':
self.state.history.system_message = message
elif message_type == 'state':
+ if self.sensitive_data:
+ message = self._filter_sensitive_data(message)
self.state.history.state_message = message
else:
raise ValueError(f'Invalid state message type: {message_type}')
def _add_context_message(self, message: BaseMessage) -> None:
"""Add a contextual message specific to this step (e.g., validation errors, retry instructions, timeout warnings)"""
- # Don't filter context messages - they should contain normal conversation or error messages
+ # Context messages typically contain error messages and validation info, not action results
+ # with sensitive data, so filtering is not needed here
self.state.history.context_messages.append(message)
@time_execution_sync('--filter_sensitive_data')
diff --git a/tests/ci/security/test_sensitive_data.py b/tests/ci/security/test_sensitive_data.py
index d9cadbc97..a55ddc41c 100644
--- a/tests/ci/security/test_sensitive_data.py
+++ b/tests/ci/security/test_sensitive_data.py
@@ -2,7 +2,9 @@ import pytest
from pydantic import BaseModel, Field
from browser_use.agent.message_manager.service import MessageManager
-from browser_use.agent.views import MessageManagerState
+from browser_use.agent.views import ActionResult, AgentOutput, AgentStepInfo, MessageManagerState
+from browser_use.browser.views import BrowserStateSummary
+from browser_use.dom.views import SerializedDOMState
from browser_use.filesystem.file_system import FileSystem
from browser_use.llm import SystemMessage, UserMessage
from browser_use.llm.messages import ContentPartTextParam
@@ -269,3 +271,168 @@ def test_is_new_tab_page():
assert is_new_tab_page('http://google.com') is False
assert is_new_tab_page('') is False
assert is_new_tab_page('chrome://settings') is False
+
+
+def test_sensitive_data_filtered_from_action_results():
+ """
+ Test that sensitive data in action results is filtered before being sent to the LLM.
+
+ This tests the full flow:
+ 1. Agent outputs actions with <secret>password</secret> placeholder
+ 2. Placeholder gets replaced with real value 'secret_pass123' during action execution
+ 3. Action result contains: "Typed 'secret_pass123' into password field"
+ 4. When state messages are created, the real value should be replaced back to placeholder
+ 5. The LLM should never see the real password value
+ """
+ import os
+ import tempfile
+ import uuid
+
+ base_tmp = tempfile.gettempdir()
+ file_system_path = os.path.join(base_tmp, str(uuid.uuid4()))
+
+ sensitive_data: dict[str, str | dict[str, str]] = {'username': 'admin_user', 'password': 'secret_pass123'}
+
+ message_manager = MessageManager(
+ task='Login to the website',
+ system_message=SystemMessage(content='You are a browser automation agent'),
+ state=MessageManagerState(),
+ file_system=FileSystem(file_system_path),
+ sensitive_data=sensitive_data,
+ )
+
+ # Create browser state
+ dom_state = SerializedDOMState(_root=None, selector_map={})
+ browser_state = BrowserStateSummary(
+ dom_state=dom_state,
+ url='https://example.com/login',
+ title='Login Page',
+ tabs=[],
+ )
+
+ # Simulate action result containing sensitive data after placeholder replacement
+ # This represents what happens after typing a password into a form field
+ action_results = [
+ ActionResult(
+ long_term_memory="Successfully typed 'secret_pass123' into the password field",
+ error=None,
+ )
+ ]
+
+ # Create model output for step 1
+ model_output = AgentOutput(
+ evaluation_previous_goal='Navigated to login page',
+ memory='On login page, need to enter credentials',
+ next_goal='Submit login form',
+ action=[],
+ )
+
+ step_info = AgentStepInfo(step_number=1, max_steps=10)
+
+ # Create state messages - this should filter sensitive data
+ message_manager.create_state_messages(
+ browser_state_summary=browser_state,
+ model_output=model_output,
+ result=action_results,
+ step_info=step_info,
+ use_vision=False,
+ )
+
+ # Get messages that would be sent to LLM
+ messages = message_manager.get_messages()
+
+ # Extract all text content from messages
+ all_text = []
+ for msg in messages:
+ if isinstance(msg.content, str):
+ all_text.append(msg.content)
+ elif isinstance(msg.content, list):
+ for part in msg.content:
+ if isinstance(part, ContentPartTextParam):
+ all_text.append(part.text)
+
+ combined_text = '\n'.join(all_text)
+
+ # Verify the bug is fixed: plaintext password should NOT appear in messages
+ assert 'secret_pass123' not in combined_text, (
+ 'Sensitive data leaked! Real password value found in LLM messages. '
+ 'The _filter_sensitive_data method should replace it with <secret>password</secret>'
+ )
+
+ # Verify the filtered placeholder IS present (proves filtering happened)
+ assert '<secret>password</secret>' in combined_text, (
+ 'Filtering did not work correctly. Expected <secret>password</secret> placeholder in messages.'
+ )
+
+
+def test_sensitive_data_filtered_with_domain_specific_format():
+ """Test that domain-specific sensitive data format is also filtered from action results."""
+ import os
+ import tempfile
+ import uuid
+
+ base_tmp = tempfile.gettempdir()
+ file_system_path = os.path.join(base_tmp, str(uuid.uuid4()))
+
+ # Use domain-specific format
+ sensitive_data: dict[str, str | dict[str, str]] = {
+ 'example.com': {'api_key': 'sk-secret-api-key-12345'},
+ }
+
+ message_manager = MessageManager(
+ task='Use the API',
+ system_message=SystemMessage(content='You are a browser automation agent'),
+ state=MessageManagerState(),
+ file_system=FileSystem(file_system_path),
+ sensitive_data=sensitive_data,
+ )
+
+ dom_state = SerializedDOMState(_root=None, selector_map={})
+ browser_state = BrowserStateSummary(
+ dom_state=dom_state,
+ url='https://example.com/api',
+ title='API Page',
+ tabs=[],
+ )
+
+ # Action result with API key that should be filtered
+ action_results = [
+ ActionResult(
+ long_term_memory="Set API key to 'sk-secret-api-key-12345' in the input field",
+ error=None,
+ )
+ ]
+
+ model_output = AgentOutput(
+ evaluation_previous_goal='Opened API settings',
+ memory='Need to configure API key',
+ next_goal='Save settings',
+ action=[],
+ )
+
+ step_info = AgentStepInfo(step_number=1, max_steps=10)
+
+ message_manager.create_state_messages(
+ browser_state_summary=browser_state,
+ model_output=model_output,
+ result=action_results,
+ step_info=step_info,
+ use_vision=False,
+ )
+
+ messages = message_manager.get_messages()
+
+ all_text = []
+ for msg in messages:
+ if isinstance(msg.content, str):
+ all_text.append(msg.content)
+ elif isinstance(msg.content, list):
+ for part in msg.content:
+ if isinstance(part, ContentPartTextParam):
+ all_text.append(part.text)
+
+ combined_text = '\n'.join(all_text)
+
+ # API key should be filtered out
+ assert 'sk-secret-api-key-12345' not in combined_text, 'API key leaked into LLM messages!'
+ assert '<secret>api_key</secret>' in combined_text, 'API key placeholder not found in messages'