Repository navigation
feat(mcp): add trust verification before browser tool execution - #6226
eddyflores100-lang wants to merge 4 commits into
Conversation
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
There was a problem hiding this comment.
1 issue found across 2 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="browser_use/mcp/trust.py">
<violation number="1" location="browser_use/mcp/trust.py:95">
P2: Nothing calls `TrustChecker` from the MCP client or the agent, so browser tool execution is not gated by this change. Either wire the check into the connection path or narrow the PR title and description to a standalone helper.</violation>
</file>
Heads up: you’re close to your flex budget. Increase your flex budget so reviews don’t pause.
View guided diff | Re-trigger cubic
| TrustLookup = Callable[[str], Awaitable[TrustVerdict]] | ||
|
|
||
|
|
||
| class TrustChecker: |
There was a problem hiding this comment.
P2: Nothing calls TrustChecker from the MCP client or the agent, so browser tool execution is not gated by this change. Either wire the check into the connection path or narrow the PR title and description to a standalone helper.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At browser_use/mcp/trust.py, line 95:
<comment>Nothing calls `TrustChecker` from the MCP client or the agent, so browser tool execution is not gated by this change. Either wire the check into the connection path or narrow the PR title and description to a standalone helper.</comment>
<file context>
@@ -0,0 +1,154 @@
+TrustLookup = Callable[[str], Awaitable[TrustVerdict]]
+
+
+class TrustChecker:
+ """Optional pre-call trust gate for MCP server connections.
+
</file context>
|
Thanks for the CLA prompt. I'll sign it shortly — the CLA assistant link needs a browser-based OAuth flow that I'll complete in the next few minutes. The PR itself is ready for review: it adds a pluggable trust verification module ( |
|
Thanks @cubic-dev-ai for the review — all 5 points are valid. Plan:
CLA: I'll complete the CLA assistant OAuth flow this week — needs a browser session I didn't have ready when I opened the PR. |
|
Update on the plan from my previous comment: Status: still WIP, but want to be transparent
No pressure on merge timeline. If you'd rather close this and re-open when bandwidth allows, that's also fine. |
…-closed + 6 P2 fixes) Addresses all 7 issues raised by cubic-dev-ai[bot] in its review on PR browser-use#6226 (review run 978321d8-5481-5e5a-baa4-f7acfa7415cb). P1 — filter_trusted trusts on lookup exception (trust.py:147) filter_trusted used to append a URL to trusted[] when its lookup raised and allow_unknown=True. That is wrong: allow_unknown applies ONLY to explicit TrustVerdict(score=None) results. A lookup that raised did not produce a verdict, so the server must not be trusted. Lookup exceptions are now ALWAYS fail-closed, regardless of allow_unknown. The class docstring spells this out. New test: test_lookup_exception_is_fail_closed_even_with_allow_unknown. P2 browser-use#1 — inclusive threshold not tested (test_trust.py:11) Added test_threshold_is_inclusive_at_boundary that asserts a verdict with score=0.7 against min_score=0.7 is trusted. Locks down the >= comparison so an accidental switch to > would fail CI. P2 browser-use#2 — Ruff double-quote style (test_trust.py:14) All new string literals switched to single quotes to match the repo's Ruff config. Ran 'ruff format' on both files; clean. P2 browser-use#3 — credentials in lookup URL (trust.py:64) Added _strip_credentials_from_url that drops userinfo (user:pass@) and secret-bearing query parameters (api_key, token, access_token, secret, password, auth) before the URL is sent to the third-party trust API. Non-secret query params (page, etc.) are preserved. New test: test_strip_credentials_from_url covers userinfo, secret query, non-secret query, and port preservation. P2 browser-use#4 — out-of-range scores (trust.py:75) Score validation now rejects NaN, inf, and any value outside [0.0, 100.0] before normalizing. A score=200 would previously normalize to 2.0 and pass any threshold <= 1.0. String scores ('0.85') are coerced to float; non-numeric strings are rejected. New test: test_default_lookup_rejects_out_of_range_score. P2 browser-use#5 — malformed 200 escapes (trust.py:82) The except clause now catches ValueError, TypeError, AttributeError in addition to httpx.RequestError and asyncio.TimeoutError. A 200 response with malformed JSON or a non-object body returns a fail- closed verdict with a reason, instead of raising out of check(). New test: test_default_lookup_handles_malformed_200. P2 browser-use#6 — TrustChecker not wired into agent (trust.py:95) Not fixed in this PR by design: keeping the change small and reviewable. The PR title and docstring already describe the module as a standalone helper. A follow-up PR will wire it into the MCP client connection path. Reply in the review thread. Tests: 11 pass, 0 fail. Ruff check + format clean. DCO: Signed-off-by: Edison Flores <[email protected]>
|
Thanks for the review — all 7 issues are valid. Pushed P1 #5 (filter_trusted trusts on lookup exception, trust.py:147). Fixed. P2 #1 (inclusive threshold not tested, test_trust.py:11). Fixed. Added P2 #2 (Ruff double-quote style, test_trust.py:14). Fixed. All new string literals switched to single quotes. Ran P2 #3 (credentials in lookup URL, trust.py:64). Fixed. Added P2 #4 (out-of-range scores, trust.py:75). Fixed. Score validation now rejects NaN, inf, and any value outside P2 #5 (malformed 200 escapes, trust.py:82). Fixed. The except clause now catches P2 #6 (TrustChecker not wired into agent, trust.py:95). Not fixed in this PR by design — keeping the change small and reviewable. The PR title and docstring describe the module as a standalone helper. A follow-up PR will wire it into the MCP client connection path so reviewers can see that surface clearly. Happy to open that as #6240 once this lands. Tests: 11 pass, 0 fail. |
|
@CLAassistant — following up: I have not forgotten the CLA. The signing flow requires a browser OAuth step that I need to complete in person (it can't be done via the API). I will sign it as soon as I'm at a browser. The code fixes from the cubic-dev-ai review are already pushed ( |
…-closed + 6 P2 fixes) Addresses all 7 issues raised by cubic-dev-ai[bot] in its review on PR browser-use#6226 (review run 978321d8-5481-5e5a-baa4-f7acfa7415cb). P1 — filter_trusted trusts on lookup exception (trust.py:147) filter_trusted used to append a URL to trusted[] when its lookup raised and allow_unknown=True. That is wrong: allow_unknown applies ONLY to explicit TrustVerdict(score=None) results. A lookup that raised did not produce a verdict, so the server must not be trusted. Lookup exceptions are now ALWAYS fail-closed, regardless of allow_unknown. The class docstring spells this out. New test: test_lookup_exception_is_fail_closed_even_with_allow_unknown. P2 browser-use#1 — inclusive threshold not tested (test_trust.py:11) Added test_threshold_is_inclusive_at_boundary that asserts a verdict with score=0.7 against min_score=0.7 is trusted. Locks down the >= comparison so an accidental switch to > would fail CI. P2 browser-use#2 — Ruff double-quote style (test_trust.py:14) All new string literals switched to single quotes to match the repo's Ruff config. Ran 'ruff format' on both files; clean. P2 browser-use#3 — credentials in lookup URL (trust.py:64) Added _strip_credentials_from_url that drops userinfo (user:pass@) and secret-bearing query parameters (api_key, token, access_token, secret, password, auth) before the URL is sent to the third-party trust API. Non-secret query params (page, etc.) are preserved. New test: test_strip_credentials_from_url covers userinfo, secret query, non-secret query, and port preservation. P2 browser-use#4 — out-of-range scores (trust.py:75) Score validation now rejects NaN, inf, and any value outside [0.0, 100.0] before normalizing. A score=200 would previously normalize to 2.0 and pass any threshold <= 1.0. String scores ('0.85') are coerced to float; non-numeric strings are rejected. New test: test_default_lookup_rejects_out_of_range_score. P2 browser-use#5 — malformed 200 escapes (trust.py:82) The except clause now catches ValueError, TypeError, AttributeError in addition to httpx.RequestError and asyncio.TimeoutError. A 200 response with malformed JSON or a non-object body returns a fail- closed verdict with a reason, instead of raising out of check(). New test: test_default_lookup_handles_malformed_200. P2 browser-use#6 — TrustChecker not wired into agent (trust.py:95) Not fixed in this PR by design: keeping the change small and reviewable. The PR title and docstring already describe the module as a standalone helper. A follow-up PR will wire it into the MCP client connection path. Reply in the review thread. Tests: 11 pass, 0 fail. Ruff check + format clean. DCO: Signed-off-by: Edison Flores <[email protected]>
5c840d1 to
94ce2f0
Compare
There was a problem hiding this comment.
All reported issues were addressed across 2 files (changes from recent commits).
Heads up: you’re close to your flex budget. Increase your flex budget so reviews don’t pause.
View guided diff | Re-trigger cubic
There was a problem hiding this comment.
1 issue found across 1 file (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="browser_use/mcp/trust.py">
<violation number="1" location="browser_use/mcp/trust.py:256">
P2: `filter_trusted` still lets `BaseException` results reach this cast because the guard only recognizes `Exception`; a cancelled lookup therefore reaches `verdict.is_trusted` and raises `AttributeError` instead of preserving cancellation or failing closed. Handle `BaseException` results before casting, re-raise `asyncio.CancelledError`, and exclude other failures.</violation>
</file>
Heads up: you’re close to your flex budget. Increase your flex budget so reviews don’t pause.
View guided diff | Re-trigger cubic
| # After the isinstance(result, Exception) check above, pyright still | ||
| # narrows to BaseException rather than TrustVerdict (because | ||
| # asyncio.gather with return_exceptions=True returns | ||
| # List[TrustVerdict | BaseException]). Cast to TrustVerdict so the | ||
| # verdict attributes are reachable; the runtime check above is the | ||
| # actual safety boundary. | ||
| verdict: TrustVerdict = result # type: ignore[assignment] |
There was a problem hiding this comment.
P2: filter_trusted still lets BaseException results reach this cast because the guard only recognizes Exception; a cancelled lookup therefore reaches verdict.is_trusted and raises AttributeError instead of preserving cancellation or failing closed. Handle BaseException results before casting, re-raise asyncio.CancelledError, and exclude other failures.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At browser_use/mcp/trust.py, line 256:
<comment>`filter_trusted` still lets `BaseException` results reach this cast because the guard only recognizes `Exception`; a cancelled lookup therefore reaches `verdict.is_trusted` and raises `AttributeError` instead of preserving cancellation or failing closed. Handle `BaseException` results before casting, re-raise `asyncio.CancelledError`, and exclude other failures.</comment>
<file context>
@@ -253,8 +253,15 @@ async def filter_trusted(self, server_urls: List[str]) -> List[str]:
)
continue
- if result.is_trusted:
+ # After the isinstance(result, Exception) check above, pyright still
+ # narrows to BaseException rather than TrustVerdict (because
+ # asyncio.gather with return_exceptions=True returns
</file context>
| # After the isinstance(result, Exception) check above, pyright still | |
| # narrows to BaseException rather than TrustVerdict (because | |
| # asyncio.gather with return_exceptions=True returns | |
| # List[TrustVerdict | BaseException]). Cast to TrustVerdict so the | |
| # verdict attributes are reachable; the runtime check above is the | |
| # actual safety boundary. | |
| verdict: TrustVerdict = result # type: ignore[assignment] | |
| if isinstance(result, BaseException): | |
| if isinstance(result, asyncio.CancelledError): | |
| raise result | |
| logger.warning('Trust check raised for %s: %s', url, result) | |
| continue | |
| verdict: TrustVerdict = result |
Adds a pluggable trust gate that browser-use agents can use to verify an MCP server's reliability before granting it browser access — closing the security gap described in browser-use#4903. The module provides: - TrustVerdict: dataclass with score (0-1), is_trusted, reason - TrustChecker: configurable gate with min_score (default 0.7), fail-open/fail-closed modes, and pluggable lookup function - filter_trusted(): convenience method to filter a list of server URLs The default threshold is 0.7 (stricter than general-purpose 0.5) because browser-use grants MCP servers browser access — a malicious server could inject harmful actions. Fail-closed by default: servers with unknown trust scores are considered untrusted. This is the recommended setting for browser automation. The default lookup queries a public trust API (Dominion Observatory, free tier, 50 queries/day, no key needed), but users can pass their own lookup callable for local or air-gapped verification. Includes 6 tests covering: trusted pass, untrusted fail, unknown fail-closed, unknown fail-open, filter_trusted, and default threshold. Closes browser-use#4903.
…-closed + 6 P2 fixes) Addresses all 7 issues raised by cubic-dev-ai[bot] in its review on PR browser-use#6226 (review run 978321d8-5481-5e5a-baa4-f7acfa7415cb). P1 — filter_trusted trusts on lookup exception (trust.py:147) filter_trusted used to append a URL to trusted[] when its lookup raised and allow_unknown=True. That is wrong: allow_unknown applies ONLY to explicit TrustVerdict(score=None) results. A lookup that raised did not produce a verdict, so the server must not be trusted. Lookup exceptions are now ALWAYS fail-closed, regardless of allow_unknown. The class docstring spells this out. New test: test_lookup_exception_is_fail_closed_even_with_allow_unknown. P2 browser-use#1 — inclusive threshold not tested (test_trust.py:11) Added test_threshold_is_inclusive_at_boundary that asserts a verdict with score=0.7 against min_score=0.7 is trusted. Locks down the >= comparison so an accidental switch to > would fail CI. P2 browser-use#2 — Ruff double-quote style (test_trust.py:14) All new string literals switched to single quotes to match the repo's Ruff config. Ran 'ruff format' on both files; clean. P2 browser-use#3 — credentials in lookup URL (trust.py:64) Added _strip_credentials_from_url that drops userinfo (user:pass@) and secret-bearing query parameters (api_key, token, access_token, secret, password, auth) before the URL is sent to the third-party trust API. Non-secret query params (page, etc.) are preserved. New test: test_strip_credentials_from_url covers userinfo, secret query, non-secret query, and port preservation. P2 browser-use#4 — out-of-range scores (trust.py:75) Score validation now rejects NaN, inf, and any value outside [0.0, 100.0] before normalizing. A score=200 would previously normalize to 2.0 and pass any threshold <= 1.0. String scores ('0.85') are coerced to float; non-numeric strings are rejected. New test: test_default_lookup_rejects_out_of_range_score. P2 browser-use#5 — malformed 200 escapes (trust.py:82) The except clause now catches ValueError, TypeError, AttributeError in addition to httpx.RequestError and asyncio.TimeoutError. A 200 response with malformed JSON or a non-object body returns a fail- closed verdict with a reason, instead of raising out of check(). New test: test_default_lookup_handles_malformed_200. P2 browser-use#6 — TrustChecker not wired into agent (trust.py:95) Not fixed in this PR by design: keeping the change small and reviewable. The PR title and docstring already describe the module as a standalone helper. A follow-up PR will wire it into the MCP client connection path. Reply in the review thread. Tests: 11 pass, 0 fail. Ruff check + format clean. DCO: Signed-off-by: Edison Flores <[email protected]>
…nd type-checker) CI on the previous push reported 2 failing checks: - code-style: ruff format - type-checker: pyright Pyright errors (2): trust.py:256:14 — Cannot access attribute 'is_trusted' for class 'BaseException' trust.py:259:69 — Cannot access attribute 'reason' for class 'BaseException' asyncio.gather with return_exceptions=True returns List[TrustVerdict | BaseException], and pyright's isinstance narrowing collapses to BaseException rather than TrustVerdict after the Exception branch + continue. Cast to TrustVerdict with an explicit type:ignore[assignment] so the verdict attributes are reachable; the runtime isinstance check above is the actual safety boundary. Ruff format: My manual Edit had preserved the file's pre-existing tab indentation in some blocks but used spaces in the new lines (the diff shows mixed indentation in trust.py). 'ruff format' has rewritten all indentation to tabs to match the repo style. Tests: 11 pass, 0 fail. pyright clean. ruff format clean. DCO: Signed-off-by: Edison Flores <[email protected]>
9682279 to
9eb6199
Compare
…n, CancelledError (cubic-dev-ai review round 2) Addresses the 5 new issues raised by cubic-dev-ai[bot] in its second and third reviews on PR browser-use#6226 (2026-11-06 01:54 and 02:05), all against the recent commits that fixed the original 7 issues. P1 browser-use#4 (trust.py:259, review 2026-11-06 01:54) — filter_trusted logs raw URLs filter_trusted's warning and info log lines logged the raw server_url, so credentials embedded in a URL (e.g. https://user:pass@host?api_key=...) reached application logs even though the API request had them stripped. Added _redact_url_for_logging helper that strips userinfo and secret query params before logging; both warning and info paths now use it. Two new tests: test_filter_trusted_logs_redacted_url_on_exception and test_filter_trusted_logs_redacted_url_on_skip — both assert the raw URL never appears in caplog.text. P2 browser-use#1 (trust.py:69) — IPv6 brackets dropped by sanitizer _strip_credentials_from_url used parts.hostname, which strips the brackets from an IPv6 address; urlunsplit then produced a malformed URL (the colon in the IPv6 address is ambiguous with the port separator). Re-add brackets around colon-containing hostnames before building the netloc. New test: test_strip_credentials_preserves_ipv6_brackets covers [::1]:8443 and [2001:db8::1] cases. P2 browser-use#2 (trust.py:70) — invalid port escapes sanitizer parts.port raises ValueError on a malformed port substring like 'abc' (e.g. https://host:abc/). That ValueError escaped the sanitizer and the lookup raised before the fail-closed handler could catch it. Wrapped parts.port access in try/except (ValueError, TypeError) and treat invalid port as no port. New test: test_strip_credentials_handles_invalid_port asserts the sanitizer returns a URL without :abc and does not raise. P2 browser-use#3 (trust.py:139) — score validator accepts JSON booleans bool is a subclass of int in Python, so isinstance(True, int) is True and float(True) returns 1.0. A JSON `true` in the trust_score field would normalize to 1.0 and pass any threshold <= 1.0. Added an explicit isinstance(score, bool) check before numeric coercion that rejects booleans with a fail-closed verdict. New test: test_default_lookup_rejects_boolean_score asserts the verdict has score=None and the reason mentions 'boolean'. P2 browser-use#5 (trust.py:256, review 2026-11-06 02:05) — BaseException reaches cast asyncio.gather with return_exceptions=True returns List[TrustVerdict | BaseException]. The isinstance(result, Exception) guard only catches Exception subclasses, not BaseException. A CancelledError (which is a BaseException since Python 3.8) reached the cast and crashed with AttributeError on verdict.is_trusted instead of preserving the cancellation. Now we re-raise asyncio.CancelledError and any other BaseException that isn't an Exception subclass (KeyboardInterrupt, SystemExit) before the cast. New test: test_filter_trusted_propagates_cancelled_error asserts that a CancelledError raised by the lookup propagates instead of being swallowed as fail-closed. Tests: 17 pass, 0 fail (was 11, +6 new). pyright clean. ruff format clean. DCO: Signed-off-by: Edison Flores <[email protected]>
|
Thanks for the two follow-up reviews — all 5 new issues are valid. Pushed P1 #4 (trust.py:259, review 01:54) — log redaction. Added P2 #1 (trust.py:69) — IPv6 brackets. P2 #2 (trust.py:70) — invalid port. P2 #3 (trust.py:139) — boolean score. P2 #5 (trust.py:256, review 02:05) — CancelledError. Tests: 17 pass, 0 fail (was 11, +6 new). |
There was a problem hiding this comment.
4 issues found across 2 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="browser_use/mcp/trust.py">
<violation number="1" location="browser_use/mcp/trust.py:71">
P2: `_redact_url_for_logging` raises `ValueError` for malformed ports such as `https://host:abc/...`, so `filter_trusted` fails while logging instead of excluding the server. Catch invalid ports and return `<malformed-url>`.</violation>
</file>
<file name="tests/mcp/test_trust.py">
<violation number="1" location="tests/mcp/test_trust.py:206">
P2: These assertions do not verify the sanitized URL or path preservation, so the test can pass with another malformed result. Assert the exact expected URL `https://host/path`.</violation>
<violation number="2" location="tests/mcp/test_trust.py:217">
P2: Ruff's import-sorting rule rejects this unordered `unittest.mock` import, which can fail CI. Sort the imported names consistently with the other tests.</violation>
<violation number="3" location="tests/mcp/test_trust.py:278">
P3: This test passes even when `filter_trusted` emits no skip log, so it does not cover the info logging path named by the test. Also assert that the redacted host, such as `bad.com`, appears.</violation>
</file>
Heads up: you’re close to your flex budget. Increase your flex budget so reviews don’t pause.
View guided diff | Re-trigger cubic
| if ':' in hostname: | ||
| hostname = f'[{hostname}]' | ||
| netloc = hostname | ||
| if parts.port is not None: |
There was a problem hiding this comment.
P2: _redact_url_for_logging raises ValueError for malformed ports such as https://host:abc/..., so filter_trusted fails while logging instead of excluding the server. Catch invalid ports and return <malformed-url>.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At browser_use/mcp/trust.py, line 71:
<comment>`_redact_url_for_logging` raises `ValueError` for malformed ports such as `https://host:abc/...`, so `filter_trusted` fails while logging instead of excluding the server. Catch invalid ports and return `<malformed-url>`.</comment>
<file context>
@@ -50,6 +50,29 @@ class TrustVerdict:
+ if ':' in hostname:
+ hostname = f'[{hostname}]'
+ netloc = hostname
+ if parts.port is not None:
+ netloc = f'{netloc}:{parts.port}'
+ return urlunsplit((parts.scheme, netloc, parts.path or '', '', ''))
</file context>
| assert 'host' in stripped | ||
| assert ':abc' not in stripped |
There was a problem hiding this comment.
P2: These assertions do not verify the sanitized URL or path preservation, so the test can pass with another malformed result. Assert the exact expected URL https://host/path.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/mcp/test_trust.py, line 206:
<comment>These assertions do not verify the sanitized URL or path preservation, so the test can pass with another malformed result. Assert the exact expected URL `https://host/path`.</comment>
<file context>
@@ -173,3 +175,123 @@ async def test_default_lookup_handles_malformed_200():
+ # Invalid port 'abc' — should not raise, should produce a URL with no port
+ stripped = _strip_credentials_from_url('https://host:abc/path')
+ # The malformed port is dropped; the path is preserved
+ assert 'host' in stripped
+ assert ':abc' not in stripped
+
</file context>
| assert 'host' in stripped | |
| assert ':abc' not in stripped | |
| assert stripped == 'https://host/path' |
| bool is a subclass of int in Python, so isinstance(True, int) is True — | ||
| the validator must explicitly reject bool before numeric coercion. | ||
| """ | ||
| from unittest.mock import patch, AsyncMock, MagicMock |
There was a problem hiding this comment.
P2: Ruff's import-sorting rule rejects this unordered unittest.mock import, which can fail CI. Sort the imported names consistently with the other tests.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/mcp/test_trust.py, line 217:
<comment>Ruff's import-sorting rule rejects this unordered `unittest.mock` import, which can fail CI. Sort the imported names consistently with the other tests.</comment>
<file context>
@@ -173,3 +175,123 @@ async def test_default_lookup_handles_malformed_200():
+ bool is a subclass of int in Python, so isinstance(True, int) is True —
+ the validator must explicitly reject bool before numeric coercion.
+ """
+ from unittest.mock import patch, AsyncMock, MagicMock
+
+ fake_response = MagicMock()
</file context>
| from unittest.mock import patch, AsyncMock, MagicMock | |
| from unittest.mock import AsyncMock, MagicMock, patch |
| log_text = caplog.text | ||
| # Credentials must not leak to logs | ||
| assert 'pass' not in log_text | ||
| assert 'secret_token_value' not in log_text |
There was a problem hiding this comment.
P3: This test passes even when filter_trusted emits no skip log, so it does not cover the info logging path named by the test. Also assert that the redacted host, such as bad.com, appears.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/mcp/test_trust.py, line 278:
<comment>This test passes even when `filter_trusted` emits no skip log, so it does not cover the info logging path named by the test. Also assert that the redacted host, such as `bad.com`, appears.</comment>
<file context>
@@ -173,3 +175,123 @@ async def test_default_lookup_handles_malformed_200():
+ log_text = caplog.text
+ # Credentials must not leak to logs
+ assert 'pass' not in log_text
+ assert 'secret_token_value' not in log_text
+
+
</file context>
| assert 'secret_token_value' not in log_text | |
| assert 'secret_token_value' not in log_text | |
| assert 'bad.com' in log_text |
What
Add an optional, pluggable trust verification module (
browser_use/mcp/trust.py) that browser-use agents can use to verify an MCP server's reliability before granting it browser access.Why
Issue #4903 identifies a significant security gap: when browser-use agents connect to MCP servers for tool execution, there's no way to verify whether a server is trustworthy before granting it browser access. A malicious MCP server could inject harmful actions into browser sessions.
This PR provides a neutral, pluggable implementation that doesn't lock into any specific trust provider:
lookupcallable for local, cached, or air-gapped verificationallow_unknown=True) or fail-closed (allow_unknown=False) for servers with unknown scoresHow
Added two files:
browser_use/mcp/trust.py— the module:TrustVerdict: dataclass withscore,is_trusted,reason,total_callsTrustChecker: configurable gate withmin_score(default 0.7, stricter than general-purpose 0.5),allow_unknown(defaultFalse— fail-closed), and pluggablelookupfilter_trusted(urls): convenience method to filter a list of server URLs_default_trust_lookup: queries the public Dominion Observatory API (50 queries/day, no key)tests/mcp/test_trust.py— 6 tests:allow_unknown=Truefilter_trustedkeeps only good serversDesign choices
httpxwhich is already a dependency.lookupparameter lets users substitute any trust provider.Usage
Closes #4903.
Summary by cubic
Adds a pluggable trust verification gate (
browser_use/mcp/trust.py) so agents can verify an MCP server's reliability before granting it browser access, closing the security gap in #4903.TrustCheckergates servers by trust score with a default threshold of 0.7 and fail-closed behavior for unknown scores (allow_unknown=False); lookup exceptions always fail closed, even whenallow_unknown=True.filter_trusted()drops untrusted server URLs from a list, redacts credentials before logging, and propagatesCancelledErrorinstead of swallowing it.TrustVerdictdataclass; no new dependencies (uses existinghttpx); 17 tests cover trusted/untrusted/unknown/exception/filtering/credential-stripping/redaction/cancellation cases.Written for commit a64a825. Summary will update on new commits.