Skip to content

Personal AI, On Personal Devices

Python

fix(tools): keep Firecrawl failures credential-safe

Elliot Slusky4ee0b1ed0510
diff --git a/src/openjarvis/security/data_boundary_audit.py b/src/openjarvis/security/data_boundary_audit.py
index 64a502d6..a1e133e5 100644
--- a/src/openjarvis/security/data_boundary_audit.py
+++ b/src/openjarvis/security/data_boundary_audit.py
@@ -1109,7 +1109,9 @@ def _web_search_destination() -> str:
engine = "youcom"
elif os.environ.get("SERPLY_API_KEY"):
engine = "serply"
- elif os.environ.get("FIRECRAWL_API_KEY") or _firecrawl_self_hosted_url():
+ elif (os.environ.get("FIRECRAWL_API_KEY") or "").strip() or (
+ _firecrawl_self_hosted_url()
+ ):
engine = "firecrawl"
else:
engine = "youcom"
diff --git a/src/openjarvis/tools/web_search.py b/src/openjarvis/tools/web_search.py
index c6abea8d..f7a0e3c6 100644
--- a/src/openjarvis/tools/web_search.py
+++ b/src/openjarvis/tools/web_search.py
@@ -128,14 +128,14 @@ class WebSearchTool(BaseTool):
self._youcom_api_key = youcom_api_key or os.environ.get(YOUCOM_API_KEY_ENV)
self._serply_api_key = serply_api_key or os.environ.get(SERPLY_API_KEY_ENV)
self._serply_location = serply_location or os.environ.get(SERPLY_LOCATION_ENV)
- self._firecrawl_api_key = firecrawl_api_key or os.environ.get(
- FIRECRAWL_API_KEY_ENV
- )
+ self._firecrawl_api_key = (
+ firecrawl_api_key or os.environ.get(FIRECRAWL_API_KEY_ENV) or ""
+ ).strip() or None
self._firecrawl_api_url = (
- firecrawl_api_url
- or os.environ.get(FIRECRAWL_API_URL_ENV)
- or FIRECRAWL_DEFAULT_API_URL
- ).rstrip("/")
+ (firecrawl_api_url or os.environ.get(FIRECRAWL_API_URL_ENV) or "")
+ .strip()
+ .rstrip("/")
+ ) or FIRECRAWL_DEFAULT_API_URL
# Self-hosted instances usually run without auth, so a custom URL
# enables the engine even when no key is set.
self._firecrawl_self_hosted = (
@@ -532,21 +532,26 @@ class WebSearchTool(BaseTool):
if status == 401:
raise _WebSearchEngineError(
f"Firecrawl rejected the credential in {FIRECRAWL_API_KEY_ENV}"
- ) from exc
+ ) from None
if status == 402:
raise _WebSearchEngineError(
"Firecrawl credits are exhausted for this key. Check the "
f"plan or create a new key at {FIRECRAWL_KEYS_URL}"
- ) from exc
+ ) from None
if status == 429:
raise _WebSearchEngineError(
"Firecrawl rate limit reached (HTTP 429)"
- ) from exc
+ ) from None
raise _WebSearchEngineError(
f"Firecrawl search failed with HTTP {status}"
- ) from exc
- except (httpx.HTTPError, ValueError) as exc:
- raise _WebSearchEngineError(f"Firecrawl search failed: {exc}") from exc
+ ) from None
+ except (httpx.HTTPError, httpx.InvalidURL, ValueError) as exc:
+ # Header validation can include the Authorization value; URL
+ # parsing errors can include credentials from a self-hosted URL.
+ # execute() logs this message and returns it in fallback metadata.
+ raise _WebSearchEngineError(
+ f"Firecrawl search failed ({type(exc).__name__})"
+ ) from None
formatted, count = self._format_firecrawl_results(payload)
metadata: dict[str, Any] = {"num_results": count, "engine": "firecrawl"}
@@ -590,14 +595,12 @@ class WebSearchTool(BaseTool):
)
response.raise_for_status()
payload = response.json()
- except (httpx.HTTPError, ValueError) as exc:
+ except (httpx.HTTPError, httpx.InvalidURL, ValueError) as exc:
reason = type(exc).__name__
if isinstance(exc, httpx.HTTPStatusError):
reason = f"HTTP {exc.response.status_code}"
logger.warning(
- "Firecrawl scrape failed for %s (%s); falling back to local "
- "HTML extraction",
- url,
+ "Firecrawl scrape failed (%s); falling back to local HTML extraction",
reason,
)
return None
diff --git a/tests/security/test_data_boundary_audit.py b/tests/security/test_data_boundary_audit.py
index c700d1c2..e9bf7180 100644
--- a/tests/security/test_data_boundary_audit.py
+++ b/tests/security/test_data_boundary_audit.py
@@ -1430,6 +1430,16 @@ class TestWebSearchDestination:
monkeypatch.setenv("FIRECRAWL_API_KEY", "fc-test")
assert _web_search_destination() == "Firecrawl search API"
+ def test_blank_firecrawl_configuration_matches_runtime(self, monkeypatch):
+ from openjarvis.security.data_boundary_audit import _web_search_destination
+ from openjarvis.tools.web_search import WebSearchTool
+
+ self._clear(monkeypatch)
+ monkeypatch.setenv("FIRECRAWL_API_KEY", " \n")
+ monkeypatch.setenv("FIRECRAWL_API_URL", " \n")
+ assert WebSearchTool()._resolve_engine() == "youcom"
+ assert _web_search_destination() == "You.com web search API (keyless free tier)"
+
def test_firecrawl_self_hosted_names_only_the_host(self, monkeypatch):
"""A self-hosted instance keeps queries off the hosted API, so the
audit says so, without echoing a URL that may carry credentials."""
diff --git a/tests/tools/test_web_search.py b/tests/tools/test_web_search.py
index 9754b58b..1efb430b 100644
--- a/tests/tools/test_web_search.py
+++ b/tests/tools/test_web_search.py
@@ -1249,6 +1249,15 @@ class TestFirecrawlSearch:
assert calls["json"]["origin"] == "openjarvis"
assert result.metadata["engine"] == "firecrawl"
+ def test_pasted_key_whitespace_is_trimmed(self, monkeypatch):
+ monkeypatch.setenv("FIRECRAWL_API_KEY", " fc-test\n")
+ calls = self._mock_post(monkeypatch)
+
+ result = WebSearchTool(engine="firecrawl").execute(query="test query")
+
+ assert result.success is True
+ assert calls["headers"]["Authorization"] == "Bearer fc-test"
+
def test_result_format_matches_the_other_engines(self, monkeypatch):
"""Same labeled Source/Summary shape agents already parse (#390)."""
monkeypatch.setenv("FIRECRAWL_API_KEY", "fc-test")
@@ -1509,6 +1518,65 @@ class TestFirecrawlScrapeExtraction:
assert "private IP blocked" in result.content
+class TestFirecrawlCredentialSafety:
+ @pytest.fixture
+ def http_client(self, monkeypatch):
+ """Exercise real HTTPX/header validation with an in-memory connection."""
+ import httpcore
+ import httpx
+
+ transport = httpx.HTTPTransport()
+ transport._pool = httpcore.ConnectionPool(
+ network_backend=httpcore.MockBackend([])
+ )
+ with httpx.Client(transport=transport, trust_env=False) as client:
+ monkeypatch.setattr(httpx, "post", client.post)
+ yield client
+
+ @pytest.mark.parametrize("mode", ["search", "scrape"])
+ @pytest.mark.parametrize("failure", ["header", "url"])
+ def test_client_errors_never_expose_credentials(
+ self, monkeypatch, caplog, http_client, mode, failure
+ ):
+ secret = "fc-private-test-value"
+ tool = WebSearchTool(
+ engine="firecrawl",
+ # Interior newlines still fail after trimming pasted whitespace.
+ firecrawl_api_key=secret + "\ninvalid" if failure == "header" else secret,
+ firecrawl_api_url=(
+ f"https://example.test:{secret}" if failure == "url" else None
+ ),
+ )
+ monkeypatch.setattr(tool, "_duckduckgo_search", lambda *a: "Search fallback")
+ monkeypatch.setattr(tool, "_fetch_url", lambda *a: "Local fallback")
+ monkeypatch.setattr("openjarvis.tools.web_search.check_ssrf", lambda url: None)
+ query = "https://example.test/article" if mode == "scrape" else "test query"
+
+ with caplog.at_level("WARNING"):
+ result = tool.execute(query=query)
+
+ assert result.success is True
+ expected_error = "LocalProtocolError" if failure == "header" else "InvalidURL"
+ assert expected_error in caplog.text
+ assert secret not in caplog.text
+ assert secret not in result.content
+ assert secret not in str(result.metadata)
+ if mode == "search":
+ assert expected_error in result.metadata["fallback_reason"]
+ assert result.metadata["fallback_from"] == "firecrawl"
+ else:
+ assert result.metadata["extractor"] == "local"
+
+ def test_scrape_failure_does_not_log_private_target_url(self, caplog, http_client):
+ tool = WebSearchTool(engine="firecrawl", firecrawl_api_key="fc-key\ninvalid")
+ with caplog.at_level("WARNING"):
+ text = tool._firecrawl_extract("https://example.test/?token=private-token")
+ assert text is None
+ assert "LocalProtocolError" in caplog.text
+ assert "private-token" not in caplog.text
+ assert "fc-key" not in caplog.text
+
+
class TestFallbackVisibility:
def test_fallback_is_logged_at_warning(self, monkeypatch, caplog):
"""Regression for the silent-degradation half of #923: a typo'd key