Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
simplify _replace_secrets func to take page obj directly
Nick Sweeting3f614ab9df22
diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.pyindex f16758951..4d5c26574 100644--- a/browser_use/controller/registry/service.py+++ b/browser_use/controller/registry/service.py@@ -151,7 +151,15 @@ class Registry(Generic[Context]):is_pydantic = Falseif sensitive_data:- validated_params = self._replace_sensitive_data(validated_params, sensitive_data, browser_session)+ # Get current URL if browser_session is provided+ current_url = None+ if browser_session:+ if browser_session.agent_current_page:+ current_url = browser_session.agent_current_page.url+ else:+ current_page = await browser_session.get_current_page()+ current_url = current_page.url if current_page else None+ validated_params = self._replace_sensitive_data(validated_params, sensitive_data, current_url)# Check if the action requires special parameters and validate they're providedif (@@ -241,9 +249,7 @@ class Registry(Generic[Context]):url_info = f' on {current_url}' if current_url and current_url != 'about:blank' else ''logger.info(f'🔒 Using sensitive data placeholders: {", ".join(sorted(placeholders_used))}{url_info}')- def _replace_sensitive_data(- self, params: BaseModel, sensitive_data: dict[str, Any], browser_session: BrowserSession = None- ) -> BaseModel:+ def _replace_sensitive_data(self, params: BaseModel, sensitive_data: dict[str, Any], current_url: str = None) -> BaseModel:"""Replaces sensitive data placeholders in params with actual values.@@ -251,7 +257,7 @@ class Registry(Generic[Context]):params: The parameter object containing <secret>placeholder</secret> tagssensitive_data: Dictionary of sensitive data, either in old format {key: value}or new format {domain_pattern: {key: value}}- browser_session: Optional browser session to get the current URL for domain matching+ current_url: Optional current URL for domain matchingReturns:BaseModel: The parameter object with placeholders replaced by actual values@@ -263,17 +269,6 @@ class Registry(Generic[Context]):# Set to track successfully replaced placeholdersreplaced_placeholders = set()- # Determine current URL if browser_session is provided- current_url = None- if browser_session:- try:- # Get current URL from browser session - do this synchronously to avoid complications- loop = asyncio.get_event_loop()- current_page = loop.run_until_complete(browser_session.get_current_page())- current_url = current_page.url if current_page else None- except Exception as e:- logger.debug(f'Failed to get current URL from browser session: {e}')-# Process sensitive data based on format and current URLapplicable_secrets = {}@@ -281,21 +276,18 @@ class Registry(Generic[Context]):if isinstance(content, dict):# New format: {domain_pattern: {key: value}}# Only include secrets for domains that match the current URL- if current_url is None:- # No URL available, include all secrets for all domains- applicable_secrets.update(content)- elif current_url != 'about:blank':- # Don't expose domain-specific secrets on about:blank+ if current_url and current_url != 'about:blank':+ # it's a real url, check it using our custom allowed_domains scheme://*.example.com glob matchingif match_url_with_domain_pattern(current_url, domain_or_key):applicable_secrets.update(content)else:- # Old format: {key: value}+ # Old format: {key: value}, expose to all domains (only allowed for legacy reasons)applicable_secrets[domain_or_key] = content# Filter out empty valuesapplicable_secrets = {k: v for k, v in applicable_secrets.items() if v}- def replace_secrets(value):+ def recursively_replace_secrets(value: str | dict | list) -> str | dict | list:if isinstance(value, str):matches = secret_pattern.findall(value)@@ -310,13 +302,13 @@ class Registry(Generic[Context]):return valueelif isinstance(value, dict):- return {k: replace_secrets(v) for k, v in value.items()}+ return {k: recursively_replace_secrets(v) for k, v in value.items()}elif isinstance(value, list):- return [replace_secrets(v) for v in value]+ return [recursively_replace_secrets(v) for v in value]return valueparams_dump = params.model_dump()- processed_params = replace_secrets(params_dump)+ processed_params = recursively_replace_secrets(params_dump)# Log sensitive data usageself._log_sensitive_data_usage(replaced_placeholders, current_url)diff --git a/tests/ci/test_sensitive_data.py b/tests/ci/test_sensitive_data.pyindex 2bffe22f2..1d1637750 100644--- a/tests/ci/test_sensitive_data.py+++ b/tests/ci/test_sensitive_data.py@@ -92,13 +92,21 @@ def test_simple_domain_specific_sensitive_data(registry, caplog):'other_data': 'non_secret_value', # Old format mixed with new}- # Without a browser_session, it should still replace known keys+ # Without a URL, domain-specific secrets should NOT be exposedresult = registry._replace_sensitive_data(params, sensitive_data)- assert 'example_user' in result.text+ assert '<secret>username</secret>' in result.text # Should NOT be replaced without URLassert '<secret>password</secret>' in result.text # Password is missing in sensitive_data+ assert 'username' in caplog.text # Both should be logged as missingassert 'password' in caplog.textcaplog.clear()+ # Test with a matching URL - domain-specific secrets should be exposed+ result = registry._replace_sensitive_data(params, sensitive_data, 'https://example.com/login')+ assert 'example_user' in result.text # Should be replaced with matching URL+ assert '<secret>password</secret>' in result.text # Password is still missing+ assert 'password' in caplog.text # Only password should be logged as missing+ caplog.clear()+def test_match_url_with_domain_pattern():"""Test that the domain pattern matching utility works correctly"""