Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(mcp): sanitize OAuth cache keys

Haozhe Wu1a3cee401261
diff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.py
index 6325323b2..31cf7ff26 100644
--- a/agent/src/tools/mcp.py
+++ b/agent/src/tools/mcp.py
@@ -20,7 +20,7 @@ from fastmcp.client.transports.http import StreamableHttpTransport
from fastmcp.client.transports.sse import SSETransport
from fastmcp.client.transports.stdio import StdioTransport
from fastmcp.exceptions import McpError, ToolError
-from key_value.aio.stores.filetree import FileTreeStore
+from key_value.aio.stores.filetree import FileTreeStore, FileTreeV1KeySanitizationStrategy
from mcp import types as mcp_types
from src.agent.tools import BaseTool
@@ -285,9 +285,11 @@ def _build_token_store(cache_dir: str) -> FileTreeStore:
The directory is created (with parents) and locked down to ``0700`` so only
the owning user can read the cached refresh tokens. ``FileTreeStore`` is a
pure-stdlib ``AsyncKeyValue`` backend (no ``diskcache`` dependency) and uses
- atomic same-directory temp-file renames for write safety. The OAuth provider
- persists refreshed tokens back through this store, giving silent refresh
- across CLI sessions.
+ atomic same-directory temp-file renames for write safety. FastMCP's OAuth
+ storage uses raw MCP URLs as logical keys, so key sanitization is enabled to
+ keep those URL-shaped keys as filesystem-safe cache-local filenames. The
+ collection names stay unchanged because token-presence checks scan FastMCP's
+ literal ``mcp-oauth-token`` collection directory.
Args:
cache_dir: Token cache directory. A leading ``~`` is expanded.
@@ -301,7 +303,10 @@ def _build_token_store(cache_dir: str) -> FileTreeStore:
path.mkdir(parents=True, exist_ok=True)
# 0700: owner-only. Tokens are secrets; no group/other access.
os.chmod(path, 0o700)
- return FileTreeStore(data_directory=path)
+ return FileTreeStore(
+ data_directory=path,
+ key_sanitization_strategy=FileTreeV1KeySanitizationStrategy(path),
+ )
class MCPServerAdapter:
diff --git a/agent/tests/test_oauth_token_cache.py b/agent/tests/test_oauth_token_cache.py
index 7d58f7f23..52bc5930d 100644
--- a/agent/tests/test_oauth_token_cache.py
+++ b/agent/tests/test_oauth_token_cache.py
@@ -7,7 +7,7 @@ These guard the security-critical invariants of the live-channel token cache:
back from disk, never from constructor args or process memory alone.
* A cached token never appears in any log record or in the OAuth transport's
request-bound payload.
-* The store rejects path-escape keys (defense-in-depth on the cache root).
+* URL/path-shaped cache keys are neutralized into cache-root-local filenames.
"""
from __future__ import annotations
@@ -71,6 +71,42 @@ def test_token_persists_across_store_instances(tmp_path: Path) -> None:
assert read_back == token_value
+def test_fastmcp_url_cache_keys_are_filesystem_safe(tmp_path: Path) -> None:
+ """FastMCP OAuth keys include the raw MCP URL and must stay cache-local."""
+ cache = tmp_path / "oauth"
+ url = "https://agent.robinhood.com/mcp/trading"
+ entries = [
+ ("mcp-oauth-client-info", f"{url}/client_info"),
+ ("mcp-oauth-token", f"{url}/tokens"),
+ ("mcp-oauth-token-expiry", f"{url}/token_expiry"),
+ ]
+
+ async def _roundtrip_url_keys() -> None:
+ writer = _build_token_store(str(cache))
+ for collection, key in entries:
+ await writer.put(collection=collection, key=key, value={"key": key})
+
+ reader = _build_token_store(str(cache))
+ for collection, key in entries:
+ assert await reader.get(collection=collection, key=key) == {"key": key}
+
+ asyncio.run(_roundtrip_url_keys())
+
+ collection_names = {collection for collection, _ in entries}
+ payload_files = [
+ path.relative_to(cache)
+ for path in cache.rglob("*.json")
+ if path.parent.name in collection_names
+ ]
+ assert len(payload_files) == len(entries)
+ assert all(len(path.parts) == 2 for path in payload_files)
+ assert not any(
+ part in {"https:", "agent.robinhood.com", "mcp", "trading"}
+ for path in payload_files
+ for part in path.parts
+ )
+
+
def test_token_value_never_in_args_or_payload(tmp_path: Path) -> None:
"""The token lives only on disk — it is never passed via constructor args.
@@ -104,22 +140,21 @@ def test_token_never_logged(tmp_path: Path, caplog) -> None:
assert secret not in record.getMessage()
-def test_store_rejects_path_escape_key(tmp_path: Path) -> None:
- """FileTreeStore fails closed when a key would escape the cache root."""
- from key_value.aio.errors.store import PathSecurityError
-
+def test_store_sanitizes_path_escape_key_inside_cache_root(tmp_path: Path) -> None:
+ """Path-shaped keys are stored under a sanitized cache-local filename."""
cache = tmp_path / "oauth"
store = _build_token_store(str(cache))
- async def _write_escape() -> None:
+ async def _write_escape() -> dict | None:
await store.put(collection="robinhood", key="../../escape", value={"x": 1})
+ return await store.get(collection="robinhood", key="../../escape")
- with pytest.raises(PathSecurityError):
- asyncio.run(_write_escape())
+ assert asyncio.run(_write_escape()) == {"x": 1}
# Nothing leaked outside the cache root.
assert not (tmp_path / "escape").exists()
assert not (tmp_path.parent / "escape").exists()
+ assert all(path.resolve().is_relative_to(cache.resolve()) for path in cache.rglob("*") if path.is_file())
# --------------------------------------------------------------------------- #
diff --git a/agent/tests/test_readonly_default.py b/agent/tests/test_readonly_default.py
index 45cd37c4c..2f89daa09 100644
--- a/agent/tests/test_readonly_default.py
+++ b/agent/tests/test_readonly_default.py
@@ -294,14 +294,14 @@ def test_should_register_live_channel_headless_with_cached_token(live_runtime: P
cache = str(live_runtime / "live" / "robinhood" / "oauth")
url = "https://agent.robinhood.com/mcp/trading"
- # Seed a token entry the way FastMCP's FileTreeStore lays one out: a file
- # under the <cache>/mcp-oauth-token/ collection directory. (A slash-free key
- # is used because that is how an entry actually materializes on disk.)
+ # Seed a token entry using FastMCP's URL-derived token key. The key contains
+ # slashes/colon in the logical store API, but the FileTreeStore backend must
+ # persist it as a filesystem-safe cache-local filename.
async def _seed_token() -> None:
store = _build_token_store(cache)
await store.put(
collection="mcp-oauth-token",
- key="cached_tokens",
+ key=f"{url}/tokens",
value={"access_token": "cached"},
)