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 glob support to allowed_domains
Nick Sweeting7e26eb14b1a2
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yamlindex ed45cd7be..1cf5e12c6 100644--- a/.github/workflows/test.yaml+++ b/.github/workflows/test.yaml@@ -43,6 +43,7 @@ jobs:- test_controller- test_tab_management- test_sensitive_data+ - test_url_allowlist_securitysteps:- uses: actions/checkout@v4- uses: astral-sh/setup-uv@v6diff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex 6e7cf6bf0..3baa86439 100644--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@ -940,28 +940,54 @@ class BrowserContext:await asyncio.sleep(remaining)def _is_url_allowed(self, url: str) -> bool:- """Check if a URL is allowed based on the whitelist configuration."""+ """+ Check if a URL is allowed based on the whitelist configuration.++ Supports glob patterns in allowed_domains:+ - *.example.com will match sub.example.com and example.com+ - *google.com will match google.com, agoogle.com, and www.google.com+ """if not self.config.allowed_domains:return Truetry:+ import fnmatchfrom urllib.parse import urlparse+ parsed_url = urlparse(url)+# Special case: Allow 'about:blank' explicitly- if url == 'about:blank':+ if url == 'about:blank' or parsed_url.scheme in ('chrome', 'brave', 'edge', 'chrome-extension'):return True- parsed_url = urlparse(url)-# Extract only the hostname component (without auth credentials or port)# Hostname returns only the domain portion, ignoring username:password and portdomain = parsed_url.hostname.lower() if parsed_url.hostname else ''- # Check if domain matches any allowed domain pattern- return any(- domain == allowed_domain.lower() or domain.endswith('.' + allowed_domain.lower())- for allowed_domain in self.config.allowed_domains- )+ if not domain:+ return False++ for allowed_domain in self.config.allowed_domains:+ allowed_domain = allowed_domain.lower()++ # Handle glob patterns+ if '*' in allowed_domain:+ # Special handling for *.domain.tld pattern to also match the bare domain+ if allowed_domain.startswith('*.'):+ # If pattern is *.example.com, also allow example.com (without subdomain)+ parent_domain = allowed_domain[2:] # Remove the '*.' prefix+ if domain == parent_domain or fnmatch.fnmatch(domain, allowed_domain):+ return True+ else:+ # For other glob patterns like *google.com+ if fnmatch.fnmatch(domain, allowed_domain):+ return True+ else:+ # Standard matching (exact or subdomain)+ if domain == allowed_domain or domain.endswith('.' + allowed_domain):+ return True++ return Falseexcept Exception as e:logger.error(f'⛔️ Error checking URL allowlist: {str(e)}')return Falsediff --git a/docs/customize/browser-settings.mdx b/docs/customize/browser-settings.mdxindex 6a290d2ac..3d47932de 100644--- a/docs/customize/browser-settings.mdx+++ b/docs/customize/browser-settings.mdx@@ -175,6 +175,10 @@ async def run_search():- **allowed_domains** (default: `None`)List of allowed domains that the agent can access. If None, all domains are allowed.Example: ['google.com', 'wikipedia.org'] - Here the agent will only be able to access google and wikipedia.++ Glob patterns are supported:+ - `['*.example.com']` will match both `sub.example.com` and `example.com`+ - `['*google.com']` will match `google.com`, `www.google.com`, and `anygoogle.com`### Session Managementdiff --git a/tests/test_context.py b/tests/test_context.pyindex 9d59951e4..2ef634440 100644--- a/tests/test_context.py+++ b/tests/test_context.py@@ -15,6 +15,7 @@ def test_is_url_allowed():Scenario 1: When allowed_domains is None, all URLs should be allowed.Scenario 2: When allowed_domains is a list, only URLs matching the allowed domain(s) are allowed.Scenario 3: When the URL is malformed, it should return False.+ Scenario 4: When allowed_domains contain glob patterns, matching should work according to glob rules."""# Create a dummy Browser mock. Only the 'config' attribute is needed for _is_url_allowed.dummy_browser = Mock()diff --git a/tests/test_url_allowlist_security.py b/tests/test_url_allowlist_security.pyindex 9a205eba0..72d8699e4 100644--- a/tests/test_url_allowlist_security.py+++ b/tests/test_url_allowlist_security.py@@ -19,3 +19,47 @@ class TestUrlAllowlistSecurity:# Make sure legitimate auth credentials still workassert context._is_url_allowed('https://user:[email protected]') is True++ def test_glob_pattern_matching(self):+ """Test that glob patterns in allowed_domains work correctly."""+ # Test *.example.com pattern (should match subdomains and main domain)+ glob_config = BrowserContextConfig(allowed_domains=['*.example.com'])+ glob_context = BrowserContext(browser=None, config=glob_config)++ # Should match subdomains+ assert glob_context._is_url_allowed('https://sub.example.com') is True+ assert glob_context._is_url_allowed('https://deep.sub.example.com') is True++ # Should also match main domain+ assert glob_context._is_url_allowed('https://example.com') is True++ # Should not match other domains+ assert glob_context._is_url_allowed('https://notexample.com') is False+ assert glob_context._is_url_allowed('https://example.org') is False++ # Test more complex glob patterns+ stars_config = BrowserContextConfig(allowed_domains=['*google.com', 'wiki*'])+ stars_context = BrowserContext(browser=None, config=stars_config)++ # Should match domains ending with google.com+ assert stars_context._is_url_allowed('https://google.com') is True+ assert stars_context._is_url_allowed('https://www.google.com') is True+ assert stars_context._is_url_allowed('https://anygoogle.com') is True++ # Should match domains starting with wiki+ assert stars_context._is_url_allowed('https://wiki.org') is True+ assert stars_context._is_url_allowed('https://wikipedia.org') is True++ # Should not match other domains+ assert stars_context._is_url_allowed('https://example.com') is False++ # Test browser internal URLs+ assert stars_context._is_url_allowed('chrome://settings') is True+ assert stars_context._is_url_allowed('about:blank') is True++ # Test security for glob patterns (authentication credentials bypass attempts)+ # These should all be detected as malicious despite containing allowed domain patterns+ assert glob_context._is_url_allowed('https://allowed.example.com:[email protected]') is False+ assert glob_context._is_url_allowed('https://[email protected]') is False+ assert glob_context._is_url_allowed('https://sub.example.com%[email protected]') is False+ assert stars_context._is_url_allowed('https://[email protected]') is False