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
add support for nested sensitive_data
Nick Sweeting187641f69561
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex 37f198c54..fd65b5967 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -26,7 +26,8 @@ class MessageManagerSettings(BaseModel):image_tokens: int = 800include_attributes: list[str] = []message_context: str | None = None- sensitive_data: dict[str, str] | None = None+ # Support both old format {key: value} and new format {domain: {key: value}}+ sensitive_data: dict[str, str | dict[str, str]] | None = Noneavailable_file_paths: list[str] | None = None@@ -218,16 +219,26 @@ class MessageManager:if not self.settings.sensitive_data:return value- # Create a dictionary with all key-value pairs from sensitive_data where value is not None or empty- valid_sensitive_data = {k: v for k, v in self.settings.sensitive_data.items() if v}+ # Collect all sensitive values from both old and new formats+ sensitive_values: dict[str, str] = {}++ # Process all sensitive data entries+ for domain_or_key, content in self.settings.sensitive_data.items():+ if isinstance(content, dict):+ # New format: {domain: {key: value}}+ for key, val in content.items():+ if val: # Skip empty values+ sensitive_values[key] = val+ elif content: # Old format: {key: value}+ sensitive_values[domain_or_key] = content# If there are no valid sensitive data entries, just return the original value- if not valid_sensitive_data:+ if not sensitive_values:logger.warning('No valid entries found in sensitive_data dictionary')return value# Replace all valid sensitive data values with their placeholder tags- for key, val in valid_sensitive_data.items():+ for key, val in sensitive_values.items():value = value.replace(val, f'<secret>{key}</secret>')return valuediff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex f0d7b85d7..eb3a024be 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -107,7 +107,7 @@ class Agent(Generic[Context]):browser_session: BrowserSession | None = None,controller: Controller[Context] = Controller(),# Initial agent run parameters- sensitive_data: dict[str, str] | None = None,+ sensitive_data: dict[str, str | dict[str, str]] | None = None,initial_actions: list[dict[str, dict[str, Any]]] | None = None,# Cloud Callbacksregister_new_step_callback: (@@ -299,24 +299,66 @@ class Agent(Generic[Context]):profile=browser_profile, browser=browser, browser_context=browser_context)- if self.sensitive_data and not self.browser_profile.allowed_domains:- logger.error(- '⚠️⚠️⚠️ Agent(sensitive_data=••••••••) was provided but BrowserSession(allowed_domains=[...]) is not locked down! ⚠️⚠️⚠️\n'- ' ☠️ If the agent visits a malicious website and encounters a prompt-injection attack, your sensitive_data may be exposed!\n\n'- ' https://docs.browser-use.com/customize/browser-settings#restrict-urls\n'- 'Waiting 10 seconds before continuing... Press [Ctrl+C] to abort.'- )- if sys.stdin.isatty():- try:- time.sleep(10)- except KeyboardInterrupt:- print(- '\n\n 🛑 Exiting now... set BrowserSession(allowed_domains=["example.com", "example.org"]) to only domains you trust to see your sensitive_data.'- )- sys.exit(0)- else:- pass # no point waiting if we're not in an interactive shell- logger.warning('‼️ Continuing with insecure settings for now... but this will become a hard error in the future!')+ if self.sensitive_data:+ # Check if sensitive_data has domain-specific credentials+ has_domain_specific_credentials = any(isinstance(v, dict) for v in self.sensitive_data.values())++ # If no allowed_domains are configured, show a security warning+ if not self.browser_profile.allowed_domains:+ logger.error(+ '⚠️⚠️⚠️ Agent(sensitive_data=••••••••) was provided but BrowserSession(allowed_domains=[...]) is not locked down! ⚠️⚠️⚠️\n'+ ' ☠️ If the agent visits a malicious website and encounters a prompt-injection attack, your sensitive_data may be exposed!\n\n'+ ' https://docs.browser-use.com/customize/browser-settings#restrict-urls\n'+ 'Waiting 10 seconds before continuing... Press [Ctrl+C] to abort.'+ )+ if sys.stdin.isatty():+ try:+ time.sleep(10)+ except KeyboardInterrupt:+ print(+ '\n\n 🛑 Exiting now... set BrowserSession(allowed_domains=["example.com", "example.org"]) to only domains you trust to see your sensitive_data.'+ )+ sys.exit(0)+ else:+ pass # no point waiting if we're not in an interactive shell+ logger.warning('‼️ Continuing with insecure settings for now... but this will become a hard error in the future!')++ # If we're using domain-specific credentials, validate domain patterns+ elif has_domain_specific_credentials:+ # For domain-specific format, ensure all domain patterns are included in allowed_domains+ domain_patterns = [k for k, v in self.sensitive_data.items() if isinstance(v, dict)]++ # Validate each domain pattern against allowed_domains+ for domain_pattern in domain_patterns:+ is_allowed = False+ for allowed_domain in self.browser_profile.allowed_domains:+ # Special cases that don't require URL matching+ if domain_pattern == allowed_domain or allowed_domain == '*':+ is_allowed = True+ break++ # Need to create example URLs to compare the patterns+ # Extract the domain parts, ignoring scheme+ pattern_domain = domain_pattern.split('://')[-1] if '://' in domain_pattern else domain_pattern+ allowed_domain_part = allowed_domain.split('://')[-1] if '://' in allowed_domain else allowed_domain++ # Check if pattern is covered by an allowed domain+ # Example: "google.com" is covered by "*.google.com"+ if pattern_domain == allowed_domain_part or (+ allowed_domain_part.startswith('*.')+ and (+ pattern_domain == allowed_domain_part[2:]+ or pattern_domain.endswith('.' + allowed_domain_part[2:])+ )+ ):+ is_allowed = True+ break++ if not is_allowed:+ logger.warning(+ f'⚠️ Domain pattern "{domain_pattern}" in sensitive_data is not covered by any pattern in allowed_domains={self.browser_profile.allowed_domains}\n'+ f' This may be a security risk as credentials could be used on unintended domains.'+ )# Callbacksself.register_new_step_callback = register_new_step_callbackdiff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex c2f6c8b0a..3d06755a5 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -8,7 +8,6 @@ import osimport reimport timefrom dataclasses import dataclass-from fnmatch import fnmatchfrom functools import wrapsfrom pathlib import Pathfrom typing import Any, Self@@ -31,7 +30,7 @@ from browser_use.browser.views import (from browser_use.dom.clickable_element_processor.service import ClickableElementProcessorfrom browser_use.dom.service import DomServicefrom browser_use.dom.views import DOMElementNode, SelectorMap-from browser_use.utils import time_execution_async, time_execution_sync+from browser_use.utils import match_url_with_domain_pattern, time_execution_async, time_execution_sync# Check if running in DockerIN_DOCKER = os.environ.get('IN_DOCKER', 'false').lower()[0] in 'ty1'@@ -1161,57 +1160,24 @@ class BrowserSession(BaseModel):if not self.browser_profile.allowed_domains:return True # allowed_domains are not configured, allow everything by default- allowed_domain = None- try:- parsed_url = urlparse(url)-- # Special case: Always allow 'about:blank' new tab page- if url == 'about:blank':- return True-- # Extract only the hostname and scheme components (without http basic auth user:pass@ prefix or :port suffix)- scheme = parsed_url.scheme.lower() if parsed_url.scheme else ''- domain = parsed_url.hostname.lower() if parsed_url.hostname else ''- assert scheme and domain-- for allowed_domain in self.browser_profile.allowed_domains:- allowed_domain = allowed_domain.lower()- if '://' in allowed_domain:- allowed_scheme, allowed_domain = allowed_domain.split('://', 1)- else:- allowed_scheme = 'http*'-- # if scheme doesn't match, skip checking domain- if not fnmatch(scheme, allowed_scheme):- continue+ # Special case: Always allow 'about:blank' new tab page+ if url == 'about:blank':+ return True- # Check for exact match- if allowed_domain == '*' or domain == allowed_domain:+ for allowed_domain in self.browser_profile.allowed_domains:+ try:+ if match_url_with_domain_pattern(url, allowed_domain, log_warnings=True):+ # If it's a pattern with wildcards, show a warning+ if '*' in allowed_domain:+ parsed_url = urlparse(url)+ domain = parsed_url.hostname.lower() if parsed_url.hostname else ''+ _show_glob_warning(domain, allowed_domain)return True+ except AssertionError:+ # This would only happen if about:blank is passed to match_url_with_domain_pattern,+ # which shouldn't occur since we check for it above+ continue- # Handle glob patterns- if '*' in allowed_domain:- bare_domain = allowed_domain.replace('.*', '').replace('*.', '')- if '*' in bare_domain:- logger.error(- f'⛔️ allowed_domains only supports *.abc or abc.* style patterns, ignoring allowed_domains=[{allowed_domain}]'- )- continue-- # Special handling so that *.google.com also matches bare google.com- if len(allowed_domain) > 2 and allowed_domain.startswith('*.'):- parent_domain = allowed_domain[2:]- if domain == parent_domain or fnmatch(domain, parent_domain):- _show_glob_warning(domain, allowed_domain)- return True-- # Normal case: match domain abc.google.com against pattern *.google.com- if fnmatch(domain, allowed_domain):- _show_glob_warning(domain, allowed_domain)- return True- except Exception as e:- failing_domain = allowed_domain or ', '.join(self.browser_profile.allowed_domains)- logger.error(f'⛔️ Error checking if page URL is in allowed_domains=[{failing_domain}]: {type(e).__name__}: {e}')return Falseasync def _check_and_handle_navigation(self, page: Page) -> None:diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.pyindex d502c2f5e..35cb00935 100644--- a/browser_use/controller/registry/service.py+++ b/browser_use/controller/registry/service.py@@ -1,5 +1,6 @@import asyncioimport logging+import refrom collections.abc import Callablefrom inspect import iscoroutinefunction, signaturefrom typing import Any, Generic, Optional, TypeVar@@ -18,7 +19,7 @@ from browser_use.telemetry.views import (ControllerRegisteredFunctionsTelemetryEvent,RegisteredFunction,)-from browser_use.utils import time_execution_async+from browser_use.utils import match_url_with_domain_pattern, time_execution_asyncContext = TypeVar('Context')@@ -104,7 +105,7 @@ class Registry(Generic[Context]):params: dict,browser_session: BrowserSession | None = None,page_extraction_llm: BaseChatModel | None = None,- sensitive_data: dict[str, str] | None = None,+ sensitive_data: dict[str, str | dict[str, str]] | None = None,available_file_paths: list[str] | None = None,#context: Context | None = None,@@ -128,7 +129,7 @@ class Registry(Generic[Context]):parameter_names = [param.name for param in parameters]if sensitive_data:- validated_params = self._replace_sensitive_data(validated_params, sensitive_data)+ validated_params = self._replace_sensitive_data(validated_params, sensitive_data, browser_session)# Check if the action requires browserif (@@ -182,26 +183,65 @@ class Registry(Generic[Context]):except Exception as e:raise RuntimeError(f'Error executing action {action_name}: {str(e)}') from e- def _replace_sensitive_data(self, params: BaseModel, sensitive_data: dict[str, str]) -> BaseModel:- """Replaces the sensitive data in the params"""- # if there are any str with <secret>placeholder</secret> in the params, replace them with the actual value from sensitive_data+ def _replace_sensitive_data(+ self, params: BaseModel, sensitive_data: dict[str, Any], browser_session: BrowserSession = None+ ) -> BaseModel:+ """+ Replaces sensitive data placeholders in params with actual values.- import logging- import re+ Args:+ params: The parameter object containing <secret>placeholder</secret> tags+ sensitive_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- logger = logging.getLogger(__name__)+ Returns:+ BaseModel: The parameter object with placeholders replaced by actual values+ """secret_pattern = re.compile(r'<secret>(.*?)</secret>')# Set to track all missing placeholders across the full objectall_missing_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 URL+ applicable_secrets = {}++ for domain_or_key, content in sensitive_data.items():+ 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 match_url_with_domain_pattern(current_url, domain_or_key):+ applicable_secrets.update(content)+ else:+ # Old format: {key: value}+ applicable_secrets[domain_or_key] = content++ # Filter out empty values+ applicable_secrets = {k: v for k, v in applicable_secrets.items() if v}+def replace_secrets(value):if isinstance(value, str):matches = secret_pattern.findall(value)for placeholder in matches:- if placeholder in sensitive_data and sensitive_data[placeholder]:- value = value.replace(f'<secret>{placeholder}</secret>', sensitive_data[placeholder])+ if placeholder in applicable_secrets:+ value = value.replace(f'<secret>{placeholder}</secret>', applicable_secrets[placeholder])else:# Keep track of missing placeholdersall_missing_placeholders.add(placeholder)diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex afa556561..14de88acc 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -761,7 +761,7 @@ class Controller(Generic[Context]):return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)# preserve undecorated function as util so other functions can use it by passing browser_session in manually- async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):+ async def _select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):page = await browser_session.get_current_page()await page.keyboard.press('Enter') # make sure we dont delete current cell contents if we were last editing@@ -779,17 +779,17 @@ class Controller(Generic[Context]):await page.keyboard.press('Escape') # to make sure the popup still closes in the case where the jump failedreturn ActionResult(extracted_content=f'Selected cell {cell_or_range}', include_in_memory=False)- # ^^ decorates the undecorated util function so it can be used as an action- @self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['sheets.google.com'])(- select_cell_or_range- )+ @self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['sheets.google.com'])+ def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):+ return _select_cell_or_range(browser_session=browser_session, cell_or_range=cell_or_range)+@self.registry.action('Google Sheets: Get the contents of a specific cell or range of cells', domains=['sheets.google.com'])async def get_range_contents(browser_session: BrowserSession, cell_or_range: str):page = await browser_session.get_current_page()- await select_cell_or_range(browser_session=browser_session, cell_or_range=cell_or_range)+ await _select_cell_or_range(browser_session=browser_session, cell_or_range=cell_or_range)await page.keyboard.press('ControlOrMeta+C')await asyncio.sleep(0.1)diff --git a/browser_use/utils.py b/browser_use/utils.pyindex d62ef31c5..ea595bf9d 100644--- a/browser_use/utils.py+++ b/browser_use/utils.py@@ -5,9 +5,11 @@ import platformimport signalimport timefrom collections.abc import Callable, Coroutine+from fnmatch import fnmatchfrom functools import wrapsfrom sys import stderrfrom typing import Any, ParamSpec, TypeVar+from urllib.parse import urlparselogger = logging.getLogger(__name__)@@ -343,3 +345,126 @@ def singleton(cls):def check_env_variables(keys: list[str], any_or_all=all) -> bool:"""Check if all required environment variables are set"""return any_or_all(os.getenv(key, '').strip() for key in keys)+++def is_unsafe_pattern(pattern: str) -> bool:+ """+ Check if a domain pattern has complex wildcards that could match too many domains.++ Args:+ pattern: The domain pattern to check++ Returns:+ bool: True if the pattern has unsafe wildcards, False otherwise+ """+ # Extract domain part if there's a scheme+ if '://' in pattern:+ _, pattern = pattern.split('://', 1)++ # Remove safe patterns (*.domain and domain.*)+ bare_domain = pattern.replace('.*', '').replace('*.', '')++ # If there are still wildcards, it's potentially unsafe+ return '*' in bare_domain+++def match_url_with_domain_pattern(url: str, domain_pattern: str, log_warnings: bool = False) -> bool:+ """+ Check if a URL matches a domain pattern. SECURITY CRITICAL.++ Supports optional glob patterns and schemes:+ - *.example.com will match sub.example.com and example.com+ - *google.com will match google.com, agoogle.com, and www.google.com+ - http*://example.com will match http://example.com, https://example.com+ - chrome-extension://* will match chrome-extension://aaaaaaaaaaaa and chrome-extension://bbbbbbbbbbbbb++ When no scheme is specified, https is used by default for security.+ For example, 'example.com' will match 'https://example.com' but not 'http://example.com'.++ Note: about:blank must be handled at the callsite, not inside this function.++ Args:+ url: The URL to check+ domain_pattern: Domain pattern to match against+ log_warnings: Whether to log warnings about unsafe patterns++ Returns:+ bool: True if the URL matches the pattern, False otherwise+ """+ try:+ # Note: about:blank should be handled at the callsite, not here+ if url == 'about:blank':+ return False++ parsed_url = urlparse(url)++ # Extract only the hostname and scheme components+ scheme = parsed_url.scheme.lower() if parsed_url.scheme else ''+ domain = parsed_url.hostname.lower() if parsed_url.hostname else ''++ if not scheme or not domain:+ return False++ # Normalize the domain pattern+ domain_pattern = domain_pattern.lower()++ # Handle pattern with scheme+ if '://' in domain_pattern:+ pattern_scheme, pattern_domain = domain_pattern.split('://', 1)+ else:+ pattern_scheme = 'https' # Default to matching only https for security+ pattern_domain = domain_pattern++ # Handle port in pattern (we strip ports from patterns since we already+ # extracted only the hostname from the URL)+ if ':' in pattern_domain and not pattern_domain.startswith(':'):+ pattern_domain = pattern_domain.split(':', 1)[0]++ # If scheme doesn't match, return False+ if not fnmatch(scheme, pattern_scheme):+ return False++ # Check for exact match+ if pattern_domain == '*' or domain == pattern_domain:+ return True++ # Handle glob patterns+ if '*' in pattern_domain:+ # Check for unsafe glob patterns+ # First, check for patterns like *.*.domain which are unsafe+ if pattern_domain.count('*.') > 1 or pattern_domain.count('.*') > 1:+ if log_warnings:+ logger = logging.getLogger(__name__)+ logger.error(f'⛔️ Multiple wildcards in pattern=[{domain_pattern}] are not supported')+ return False # Don't match unsafe patterns++ # Check for wildcards in TLD part (example.*)+ if pattern_domain.endswith('.*'):+ if log_warnings:+ logger = logging.getLogger(__name__)+ logger.error(f'⛔️ Wildcard TLDs like in pattern=[{domain_pattern}] are not supported for security')+ return False # Don't match unsafe patterns++ # Then check for embedded wildcards+ bare_domain = pattern_domain.replace('*.', '')+ if '*' in bare_domain:+ if log_warnings:+ logger = logging.getLogger(__name__)+ logger.error(f'⛔️ Only *.domain style patterns are supported, ignoring pattern=[{domain_pattern}]')+ return False # Don't match unsafe patterns++ # Special handling so that *.google.com also matches bare google.com+ if pattern_domain.startswith('*.'):+ parent_domain = pattern_domain[2:]+ if domain == parent_domain or fnmatch(domain, parent_domain):+ return True++ # Normal case: match domain against pattern+ if fnmatch(domain, pattern_domain):+ return True++ return False+ except Exception as e:+ logger = logging.getLogger(__name__)+ logger.error(f'⛔️ Error matching URL {url} with pattern {domain_pattern}: {type(e).__name__}: {e}')+ return Falsediff --git a/docs/customize/sensitive-data.mdx b/docs/customize/sensitive-data.mdxindex 371b0e90e..d642fde6f 100644--- a/docs/customize/sensitive-data.mdx+++ b/docs/customize/sensitive-data.mdx@@ -10,13 +10,15 @@ When working with sensitive information like passwords, you can use the `sensitiMake sure to always set [`allowed_domains`](https://docs.browser-use.com/customize/browser-settings#restrict-urls) to restrict the domains the Agent is allowed to visit when working with sensitive data or logins.-Here's an example of how to use sensitive data:+### Basic Usage++Here's a basic example of how to use sensitive data:```pythonfrom dotenv import load_dotenvfrom langchain_openai import ChatOpenAI-from browser_use import Agent, Browser, BrowserConfig-from browser_use.browser.context import BrowserContextConfig+from browser_use import Agent+from browser_use.browser.session import BrowserSessionload_dotenv()@@ -33,9 +35,9 @@ sensitive_data = {'x_name': 'magnus', 'x_password': '12345678'}# Use the placeholder names in your task descriptiontask = 'go to x.com and login with x_name and x_password then write a post about the meaning of life'-# Configure allowed_domains that the agent should be restricted to in BrowserContextConfig-context_config = BrowserContextConfig(- allowed_domains=['example.com'],+# Configure browser session with allowed domains+browser_session = BrowserSession(+ allowed_domains=['example.com'])# Pass the sensitive data to the agent@@ -43,11 +45,7 @@ agent = Agent(task=task,llm=llm,sensitive_data=sensitive_data,- browser=Browser(- config=BrowserConfig(- new_context_config=context_config- )- )+ browser_session=browser_session)async def main():@@ -63,6 +61,79 @@ In this example:3. When your password is visible on the current page, we replace it in the LLM input - so that the model never has it in its state.4. The agent will be prevented from going to any site not on `example.com` to protect from prompt injection attacks and jailbreaks+### Domain-Specific Sensitive Data++For enhanced security, you can associate sensitive data with specific domains. This ensures credentials are only used on the domains they're intended for:++```python+from dotenv import load_dotenv+from langchain_openai import ChatOpenAI+from browser_use import Agent+from browser_use.browser.session import BrowserSession++load_dotenv()++# Initialize the model+llm = ChatOpenAI(+ model='gpt-4o',+ temperature=0.0,+)++# Domain-specific sensitive data+sensitive_data = {+ 'https://*.google.com': {'x_email': '...', 'x_pass': '...'},+ 'chrome-extension://abcd': {'x_api_key': '...'},+ 'http*://example.com': {'x_authcode': '123123'}+}++# Set browser session with allowed domains that match all domain patterns in sensitive_data+browser_session = BrowserSession(+ allowed_domains=[+ 'https://*.google.com',+ 'chrome-extension://abcd',+ 'http://example.com', # Explicitly include http:// if needed+ 'https://example.com' # By default, only https:// is matched+ ]+)++# Pass the sensitive data to the agent+agent = Agent(+ task="Log into Google, then check my account information",+ llm=llm,+ sensitive_data=sensitive_data,+ browser_session=browser_session+)++async def main():+ await agent.run()++if __name__ == '__main__':+ asyncio.run(main())+```++With this approach:+1. The Google credentials (`x_email` and `x_pass`) will only be used on Google domains (any subdomain)+2. The API key (`x_api_key`) will only be used in the specific Chrome extension+3. The auth code (`x_authcode`) will only be used on example.com via http or https++### Domain Pattern Format++Domain patterns in sensitive_data follow the same format as `allowed_domains`:++- `example.com` - Matches only example.com+- `*.example.com` - Matches any subdomain of example.com+- `http*://example.com` - Matches both http and https protocols for example.com+- `chrome-extension://*` - Matches any Chrome extension++> **Security Warning**: For security reasons, certain patterns are explicitly rejected:+> - Wildcards in TLD part (e.g., `example.*`) are not allowed as they could match any TLD+> - Embedded wildcards (e.g., `g*e.com`) are rejected to prevent overly broad matches+> - Multiple wildcards like `*.*.domain` are not supported to avoid security issues++The default protocol when no scheme is specified is now `https` for enhanced security.++The system will validate that all domain patterns used in `sensitive_data` are covered by the patterns in `allowed_domains`.+### Missing or Empty ValuesWhen working with sensitive data, keep these details in mind:diff --git a/examples/features/sensitive_data.py b/examples/features/sensitive_data.pyindex fa2d87a9c..3924a612b 100644--- a/examples/features/sensitive_data.py+++ b/examples/features/sensitive_data.py@@ -17,11 +17,34 @@ llm = ChatOpenAI(model='gpt-4o',temperature=0.0,)-# the model will see x_name and x_password, but never the actual values.-sensitive_data = {'x_name': 'my_x_name', 'x_password': 'my_x_password'}-task = 'go to x.com and login with x_name and x_password then find interesting posts and like them'+# Simple case: the model will see x_name and x_password, but never the actual values.+# sensitive_data = {'x_name': 'my_x_name', 'x_password': 'my_x_password'}++# Advanced case: domain-specific credentials with reusable data+# Define a single credential set that can be reused+company_credentials = {'company_username': '[email protected]', 'company_password': 'securePassword123'}++# Map the same credentials to multiple domains for secure access control+sensitive_data = {+ 'https://example.com': company_credentials,+ 'https://admin.example.com': company_credentials,+ 'https://*.example-staging.com': company_credentials,+ 'http*://test.example.com': company_credentials,+ # You can also add domain-specific credentials+ 'https://*.google.com': {'g_email': '[email protected]', 'g_pass': 'google_password'},+}+# Update task to use one of the credentials above+task = 'Go to example.com and login with company_username and company_password'++# Always set allowed_domains when using sensitive_data for security+from browser_use.browser.session import BrowserSession++browser_session = BrowserSession(+ allowed_domains=list(sensitive_data.keys())+ + ['https://*.trusted-partner.com'] # Domain patterns from sensitive_data + additional allowed domains+)-agent = Agent(task=task, llm=llm, sensitive_data=sensitive_data)+agent = Agent(task=task, llm=llm, sensitive_data=sensitive_data, browser_session=browser_session)async def main():diff --git a/tests/test_sensitive_data.py b/tests/test_sensitive_data.pyindex 89f722bb0..ab9600a16 100644--- a/tests/test_sensitive_data.py+++ b/tests/test_sensitive_data.py@@ -5,6 +5,7 @@ from pydantic import BaseModel, Fieldfrom browser_use.agent.message_manager.service import MessageManager, MessageManagerSettingsfrom browser_use.agent.views import MessageManagerStatefrom browser_use.controller.registry.service import Registry+from browser_use.utils import match_url_with_domain_patternclass SensitiveParams(BaseModel):@@ -62,6 +63,136 @@ def test_replace_sensitive_data_with_missing_keys(registry):# Empty value should be treated the same as missing key+def test_simple_domain_specific_sensitive_data(registry):+ """Test the basic functionality of domain-specific sensitive data replacement"""+ # Create a simple Pydantic model with sensitive data placeholders+ params = SensitiveParams(text='Please enter <secret>username</secret> and <secret>password</secret>')++ # Simple test with directly instantiable values+ sensitive_data = {+ 'example.com': {'username': 'example_user'},+ 'other_data': 'non_secret_value', # Old format mixed with new+ }++ # Without a browser_session, it should still replace known keys+ result = registry._replace_sensitive_data(params, sensitive_data)+ assert 'example_user' in result.text+ assert '<secret>password</secret>' in result.text # Password is missing in sensitive_data+++def test_match_url_with_domain_pattern():+ """Test that the domain pattern matching utility works correctly"""++ # Test exact domain matches+ assert match_url_with_domain_pattern('https://example.com', 'example.com') is True+ assert match_url_with_domain_pattern('http://example.com', 'example.com') is False # Default scheme is now https+ assert match_url_with_domain_pattern('https://google.com', 'example.com') is False++ # Test subdomain pattern matches+ assert match_url_with_domain_pattern('https://sub.example.com', '*.example.com') is True+ assert match_url_with_domain_pattern('https://example.com', '*.example.com') is True # Base domain should match too+ assert match_url_with_domain_pattern('https://sub.sub.example.com', '*.example.com') is True+ assert match_url_with_domain_pattern('https://example.org', '*.example.com') is False++ # Test protocol pattern matches+ assert match_url_with_domain_pattern('https://example.com', 'http*://example.com') is True+ assert match_url_with_domain_pattern('http://example.com', 'http*://example.com') is True+ assert match_url_with_domain_pattern('ftp://example.com', 'http*://example.com') is False++ # Test explicit http protocol+ assert match_url_with_domain_pattern('http://example.com', 'http://example.com') is True+ assert match_url_with_domain_pattern('https://example.com', 'http://example.com') is False++ # Test Chrome extension pattern+ assert match_url_with_domain_pattern('chrome-extension://abcdefghijkl', 'chrome-extension://*') is True+ assert match_url_with_domain_pattern('chrome-extension://mnopqrstuvwx', 'chrome-extension://abcdefghijkl') is False++ # Test about:blank handling+ assert match_url_with_domain_pattern('about:blank', 'example.com') is False+ assert match_url_with_domain_pattern('about:blank', '*://*') is False+++def test_unsafe_domain_patterns():+ """Test that unsafe domain patterns are rejected"""++ # These are unsafe patterns that could match too many domains+ assert match_url_with_domain_pattern('https://evil.com', '*google.com') is False+ assert match_url_with_domain_pattern('https://google.com.evil.com', '*.*.com') is False+ assert match_url_with_domain_pattern('https://google.com', '**google.com') is False+ assert match_url_with_domain_pattern('https://google.com', 'g*e.com') is False+ assert match_url_with_domain_pattern('https://google.com', '*com*') is False++ # Test with patterns that have multiple asterisks in different positions+ assert match_url_with_domain_pattern('https://subdomain.example.com', '*domain*example*') is False+ assert match_url_with_domain_pattern('https://sub.domain.example.com', '*.*.example.com') is False++ # Test patterns with wildcards in TLD part+ assert match_url_with_domain_pattern('https://example.com', 'example.*') is False+ assert match_url_with_domain_pattern('https://example.org', 'example.*') is False+++def test_malformed_urls_and_patterns():+ """Test handling of malformed URLs or patterns"""++ # Malformed URLs+ assert match_url_with_domain_pattern('not-a-url', 'example.com') is False+ assert match_url_with_domain_pattern('http://', 'example.com') is False+ assert match_url_with_domain_pattern('https://', 'example.com') is False+ assert match_url_with_domain_pattern('ftp:/example.com', 'example.com') is False # Missing slash++ # Empty URLs or patterns+ assert match_url_with_domain_pattern('', 'example.com') is False+ assert match_url_with_domain_pattern('https://example.com', '') is False++ # URLs with no hostname+ assert match_url_with_domain_pattern('file:///path/to/file.txt', 'example.com') is False++ # Invalid pattern formats+ assert match_url_with_domain_pattern('https://example.com', '..example.com') is False+ assert match_url_with_domain_pattern('https://example.com', '.*.example.com') is False+ assert match_url_with_domain_pattern('https://example.com', '**') is False++ # Nested URL attacks in path, query or fragments+ assert match_url_with_domain_pattern('https://example.com/redirect?url=https://evil.com', 'example.com') is True+ assert match_url_with_domain_pattern('https://example.com/path/https://evil.com', 'example.com') is True+ assert match_url_with_domain_pattern('https://example.com#https://evil.com', 'example.com') is True+ # These should match example.com, not evil.com since urlparse extracts the hostname correctly++ # Complex URL obfuscation attempts+ assert match_url_with_domain_pattern('https://example.com/path?next=//evil.com/attack', 'example.com') is True+ assert match_url_with_domain_pattern('https://[email protected]', 'example.com') is False+ assert match_url_with_domain_pattern('https://evil.com?example.com', 'example.com') is False+ assert match_url_with_domain_pattern('https://user:[email protected]', 'example.com') is False+ # urlparse correctly identifies evil.com as the hostname in these cases+++def test_url_components():+ """Test handling of URL components like credentials, ports, fragments, etc."""++ # URLs with credentials (username:password@)+ assert match_url_with_domain_pattern('https://user:[email protected]', 'example.com') is True+ assert match_url_with_domain_pattern('https://user:[email protected]', '*.example.com') is True++ # URLs with ports+ assert match_url_with_domain_pattern('https://example.com:8080', 'example.com') is True+ assert match_url_with_domain_pattern('https://example.com:8080', 'example.com:8080') is True # Port is stripped from pattern++ # URLs with paths+ assert match_url_with_domain_pattern('https://example.com/path/to/page', 'example.com') is True+ assert (+ match_url_with_domain_pattern('https://example.com/path/to/page', 'example.com/path') is False+ ) # Paths in patterns are not supported++ # URLs with query parameters+ assert match_url_with_domain_pattern('https://example.com?param=value', 'example.com') is True++ # URLs with fragments+ assert match_url_with_domain_pattern('https://example.com#section', 'example.com') is True++ # URLs with all components+ assert match_url_with_domain_pattern('https://user:[email protected]:8080/path?query=val#fragment', 'example.com') is True++def test_filter_sensitive_data(message_manager):"""Test that _filter_sensitive_data handles all sensitive data scenarios correctly"""# Set up a message with sensitive information@@ -89,3 +220,16 @@ def test_filter_sensitive_data(message_manager):result = message_manager._filter_sensitive_data(message)assert '<secret>username</secret>' in result.content# Only username should be replaced since password is empty++ # Case 5: Test with domain-specific sensitive data format+ message_manager.settings.sensitive_data = {+ 'example.com': {'username': 'admin', 'password': 'secret123'},+ 'google.com': {'email': '[email protected]', 'password': 'google_pass'},+ }+ # Update the message to include the values we're going to test+ message = HumanMessage(content='My username is admin, email is [email protected] and password is secret123 or google_pass')+ result = message_manager._filter_sensitive_data(message)+ # All sensitive values should be replaced regardless of domain+ assert '<secret>username</secret>' in result.content+ assert '<secret>password</secret>' in result.content+ assert '<secret>email</secret>' in result.content