160-tool MCP server for real-time global intelligence from free public APIs: markets, liquidity, prediction markets, SEC filings, conflict, military, aircraft-cohort early warning, migration and border flows, cyber, climate, news and more. Dated observation history, 29 research prompts, cited briefs, geofences, SSE dashboard. MIT, no paid API keys.
Python ai-toolsai-watchanthropicclaudecybersecuritydashboardgeofencinggeopoliticalgeospatialintelligencemarketsmcpmigrationmilitarymodel-context-protocolnuclearosintreal-timespace-weatherthreat-intelligence
Fetcher: mask credentials in failure logs and error strings
Phoenix Agent (mac-studio)044ace34c243
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f314f61..f03b48f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,15 @@Tools 139 -> 160. Collector sources 55 -> 61. New MCP surface: 29 prompts and 3resources (none before).+### Fixed: failed fetches log no credentials+- A failed keyed request (FRED, EIA, TomTom and others pass the key as a+ query parameter) logged the full request URL, key included. Fetch+ failure logs, `get_bytes` error strings and stale-cache log lines now mask+ credential-named query parameters (`api_key`, `key`, `token` and similar)+ and any value of a `*_KEY`, `*_TOKEN`, `*_SECRET` or `*_PASSWORD`+ environment variable, which covers the key NASA FIRMS carries in the URL+ path. Keys already written to old log files are not rewritten.+### Added: dashboard research panels (Phase 29)- RESEARCH in the dashboard top bar (or the `p` key) opens four tabs:liquidity board, situations, top stories and collection health. Each tabdiff --git a/src/world_intel_mcp/fetcher.py b/src/world_intel_mcp/fetcher.pyindex aa47224..c5b91dc 100644--- a/src/world_intel_mcp/fetcher.py+++ b/src/world_intel_mcp/fetcher.py@@ -13,6 +13,7 @@ import contextlibimport contextvarsimport loggingimport os+import reimport sqlite3import timefrom dataclasses import dataclass@@ -82,6 +83,36 @@ class BinaryResult:return self.content is not None+# Query parameters whose values are credentials. httpx puts the full+# request URL in its error text, so a failed keyed request would otherwise+# carry the key into logs and returned error strings.+_SECRET_PARAMS = (+ "api_key|apikey|app_key|appid|key|token|access_token|auth|password|secret|client_secret"+)+_SECRET_QUERY_RE = re.compile(rf"(?i)([?&](?:{_SECRET_PARAMS})=)[^&#\s'\"]+")+# The same names as dict keys, as they appear in a cache key built from params.+_SECRET_DICT_RE = re.compile(rf"(?i)(['\"](?:{_SECRET_PARAMS})['\"]\s*:\s*['\"])[^'\"]*")+# Environment variables holding credentials; their values are masked wherever+# they appear, which covers keys carried in a URL path (NASA FIRMS).+_SECRET_ENV_RE = re.compile(r"(?i)(KEY|TOKEN|SECRET|PASSWORD)$")+_MASK = "***"+++def redact(text: object) -> str:+ """``str(text)`` with credential values masked.++ Masks the values of credential-named query parameters and dict keys,+ and any value (8+ characters) of an environment variable whose name+ ends in KEY, TOKEN, SECRET or PASSWORD.+ """+ out = str(text)+ for name, value in os.environ.items():+ if len(value) >= 8 and _SECRET_ENV_RE.search(name) and value in out:+ out = out.replace(value, _MASK)+ out = _SECRET_QUERY_RE.sub(rf"\g<1>{_MASK}", out)+ return _SECRET_DICT_RE.sub(rf"\g<1>{_MASK}", out)++@dataclass(frozen=True)class StaleServe:"""One expired cache entry served because the live fetch failed."""@@ -263,14 +294,16 @@ class Fetcher:attempt + 1,self.max_retries,source,- exc,+ redact(exc),wait,)await asyncio.sleep(wait)# All retries failed — try stale cache before giving upself.breaker.record_failure(source)- logger.warning("Fetch failed for %s: %s (url=%s)", source, last_error, url)+ logger.warning(+ "Fetch failed for %s: %s (url=%s)", source, redact(last_error), redact(url)+ )return self._stale_fallback(effective_key, source)async def get_text(@@ -315,7 +348,7 @@ class Fetcher:await asyncio.sleep(min(2**attempt, 30))self.breaker.record_failure(source)- logger.warning("Text fetch failed for %s: %s", source, last_error)+ logger.warning("Text fetch failed for %s: %s", source, redact(last_error))return self._stale_fallback(effective_key, source)async def get_xml(@@ -426,12 +459,14 @@ class Fetcher:)return BinaryResult(last_status, body, None)except (httpx.HTTPStatusError, httpx.RequestError) as exc:- last_error = f"{type(exc).__name__}: {exc}"+ last_error = redact(f"{type(exc).__name__}: {exc}")if attempt < self.max_retries:await asyncio.sleep(min(2**attempt, 30))self.breaker.record_failure(source)- logger.warning("Binary fetch failed for %s: %s (url=%s)", source, last_error, url)+ logger.warning(+ "Binary fetch failed for %s: %s (url=%s)", source, last_error, redact(url)+ )return BinaryResult(last_status, None, last_error)def _stale_fallback(self, cache_key: str, source: str) -> Any | None:@@ -454,7 +489,7 @@ class Fetcher:logger.info("Serving stale cache for %s (key=%s, age=%.0fs)",source,- cache_key,+ redact(cache_key),age_seconds,)serve = StaleServe(source, cache_key, round(age_seconds, 1))diff --git a/src/world_intel_mcp/tests/test_fetcher_redacts_keys.py b/src/world_intel_mcp/tests/test_fetcher_redacts_keys.pynew file mode 100644index 0000000..3f20bcc--- /dev/null+++ b/src/world_intel_mcp/tests/test_fetcher_redacts_keys.py@@ -0,0 +1,112 @@+"""Failed keyed fetches never put the key in a log line or a returned error.++httpx's HTTPStatusError text carries the full request URL, query string+included, so a 401 from a keyed source logged its api_key at WARNING.+NASA FIRMS carries its key in the URL path, which only the environment+value match catches.++Gaps / not covered: errors a source module formats itself without going+through the fetcher; keys shorter than 8 characters held in the+environment (only their query-parameter form is masked).+"""++import logging++import httpx+import pytest++from world_intel_mcp.cache import Cache+from world_intel_mcp.circuit_breaker import CircuitBreaker+from world_intel_mcp.fetcher import Fetcher, redact++QUERY_KEY = "-".join(["query", "param", "value"])+PATH_KEY = "-".join(["firms", "path", "value"])+++def _fetcher(tmp_path, status: int) -> Fetcher:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(status, text="denied", request=request)++ fetcher = Fetcher(cache=Cache(db_path=tmp_path / "cache.db"), breaker=CircuitBreaker())+ fetcher.max_retries = 0+ fetcher._client = httpx.AsyncClient(transport=httpx.MockTransport(handler))+ return fetcher+++def _logged(caplog) -> str:+ return "\n".join(r.getMessage() for r in caplog.records)++[email protected]("status", [401, 500])+async def test_json_failure_log_masks_query_key(tmp_path, caplog, status) -> None:+ fetcher = _fetcher(tmp_path, status)+ caplog.set_level(logging.DEBUG, logger="world-intel-mcp.fetcher")+ try:+ result = await fetcher.get_json(+ "https://api.example.test/series",+ source="fred",+ params={"series_id": "WALCL", "api_key": QUERY_KEY},+ )+ finally:+ await fetcher._client.aclose()+ assert result is None+ text = _logged(caplog)+ assert "Fetch failed for fred" in text+ assert QUERY_KEY not in text+ assert "api_key=***" in text+++async def test_text_failure_log_masks_query_key(tmp_path, caplog) -> None:+ fetcher = _fetcher(tmp_path, 403)+ caplog.set_level(logging.DEBUG, logger="world-intel-mcp.fetcher")+ try:+ await fetcher.get_text(+ "https://api.example.test/flow", source="tomtom", params={"key": QUERY_KEY}+ )+ finally:+ await fetcher._client.aclose()+ text = _logged(caplog)+ assert "Text fetch failed for tomtom" in text+ assert QUERY_KEY not in text+++async def test_path_key_from_environment_is_masked(tmp_path, caplog, monkeypatch) -> None:+ monkeypatch.setenv("NASA_FIRMS_API_KEY", PATH_KEY)+ fetcher = _fetcher(tmp_path, 401)+ caplog.set_level(logging.DEBUG, logger="world-intel-mcp.fetcher")+ url = f"https://firms.example.test/api/area/csv/{PATH_KEY}/VIIRS_SNPP_NRT/world/2"+ try:+ await fetcher.get_text(url, source="nasa-firms")+ binary = await fetcher.get_bytes(url, source="nasa-firms")+ finally:+ await fetcher._client.aclose()+ assert binary.error is not None+ assert PATH_KEY not in binary.error+ text = _logged(caplog)+ assert "Binary fetch failed for nasa-firms" in text+ assert PATH_KEY not in text+++async def test_stale_serve_log_masks_key_in_cache_key(tmp_path, caplog) -> None:+ fetcher = _fetcher(tmp_path, 500)+ key = f"fred:https://api.example.test/series:{{'api_key': '{QUERY_KEY}'}}"+ fetcher.cache.set(key, {"v": 1}, -1)+ caplog.set_level(logging.DEBUG, logger="world-intel-mcp.fetcher")+ try:+ served = await fetcher.get_json(+ "https://api.example.test/series", source="fred", params={"api_key": QUERY_KEY}+ )+ finally:+ await fetcher._client.aclose()+ assert served is not None and served["_stale"] is True+ text = _logged(caplog)+ assert "Serving stale cache for fred" in text+ assert QUERY_KEY not in text+++def test_redact_leaves_ordinary_text_alone() -> None:+ plain = "HTTPStatusError: 404 for url 'https://example.test/a?series_id=WALCL&limit=5'"+ assert redact(plain) == plain+ names = ("token", "apikey")+ query = "x?" + "&".join(f"{name}={QUERY_KEY[:5]}" for name in names)+ assert redact(query) == "x?" + "&".join(f"{name}=***" for name in names)