fix(security): apply MCP upload sandbox when transport is set via CLI
Record the active transport at run_stdio/run_sse/run_http startup so create_knowledge_from_file path checks apply even when MCP_TRANSPORT is not set in the environment.
This commit is contained in:
@@ -3,15 +3,17 @@ import os
|
|||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from upload_paths import resolve_upload_file_path
|
from upload_paths import clear_active_transport, resolve_upload_file_path, set_active_transport
|
||||||
|
|
||||||
|
|
||||||
class ResolveUploadFilePathTest(unittest.TestCase):
|
class ResolveUploadFilePathTest(unittest.TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self._old_transport = os.environ.get("MCP_TRANSPORT")
|
self._old_transport = os.environ.get("MCP_TRANSPORT")
|
||||||
self._old_roots = os.environ.get("MCP_ALLOWED_UPLOAD_DIRS")
|
self._old_roots = os.environ.get("MCP_ALLOWED_UPLOAD_DIRS")
|
||||||
|
os.environ.pop("MCP_TRANSPORT", None)
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
|
clear_active_transport()
|
||||||
if self._old_transport is None:
|
if self._old_transport is None:
|
||||||
os.environ.pop("MCP_TRANSPORT", None)
|
os.environ.pop("MCP_TRANSPORT", None)
|
||||||
else:
|
else:
|
||||||
@@ -35,6 +37,21 @@ class ResolveUploadFilePathTest(unittest.TestCase):
|
|||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
resolve_upload_file_path("/etc/passwd")
|
resolve_upload_file_path("/etc/passwd")
|
||||||
|
|
||||||
|
def test_active_transport_without_env_blocks_path_outside_cwd(self):
|
||||||
|
"""CLI --transport http sets active transport without MCP_TRANSPORT env."""
|
||||||
|
set_active_transport("http")
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
os.chdir(tmp)
|
||||||
|
allowed = os.path.join(tmp, "note.txt")
|
||||||
|
with open(allowed, "w", encoding="utf-8") as handle:
|
||||||
|
handle.write("ok")
|
||||||
|
|
||||||
|
resolved = resolve_upload_file_path("note.txt")
|
||||||
|
self.assertEqual(resolved, os.path.realpath(allowed))
|
||||||
|
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
resolve_upload_file_path("/etc/passwd")
|
||||||
|
|
||||||
def test_explicit_allowed_roots(self):
|
def test_explicit_allowed_roots(self):
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
os.environ["MCP_ALLOWED_UPLOAD_DIRS"] = tmp
|
os.environ["MCP_ALLOWED_UPLOAD_DIRS"] = tmp
|
||||||
|
|||||||
@@ -3,7 +3,27 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from typing import List
|
from typing import List, Optional
|
||||||
|
|
||||||
|
_active_transport: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
def set_active_transport(transport: str) -> None:
|
||||||
|
"""Record the transport selected at server startup (CLI or run_* entry)."""
|
||||||
|
global _active_transport
|
||||||
|
_active_transport = transport.strip().lower()
|
||||||
|
|
||||||
|
|
||||||
|
def clear_active_transport() -> None:
|
||||||
|
"""Reset startup transport override (for tests)."""
|
||||||
|
global _active_transport
|
||||||
|
_active_transport = None
|
||||||
|
|
||||||
|
|
||||||
|
def _current_transport() -> str:
|
||||||
|
if _active_transport is not None:
|
||||||
|
return _active_transport
|
||||||
|
return os.getenv("MCP_TRANSPORT", "stdio").strip().lower()
|
||||||
|
|
||||||
|
|
||||||
def _path_within_root(resolved_path: str, root: str) -> bool:
|
def _path_within_root(resolved_path: str, root: str) -> bool:
|
||||||
@@ -22,7 +42,7 @@ def _allowed_upload_roots() -> List[str]:
|
|||||||
if raw:
|
if raw:
|
||||||
return [os.path.realpath(part.strip()) for part in raw.split(",") if part.strip()]
|
return [os.path.realpath(part.strip()) for part in raw.split(",") if part.strip()]
|
||||||
|
|
||||||
transport = os.getenv("MCP_TRANSPORT", "stdio").strip().lower()
|
transport = _current_transport()
|
||||||
if transport in ("sse", "http"):
|
if transport in ("sse", "http"):
|
||||||
return [os.path.realpath(os.getcwd())]
|
return [os.path.realpath(os.getcwd())]
|
||||||
return []
|
return []
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import requests
|
|||||||
from mcp.server import NotificationOptions, Server
|
from mcp.server import NotificationOptions, Server
|
||||||
from mcp.server.models import InitializationOptions
|
from mcp.server.models import InitializationOptions
|
||||||
from requests.exceptions import RequestException
|
from requests.exceptions import RequestException
|
||||||
from upload_paths import resolve_upload_file_path
|
from upload_paths import resolve_upload_file_path, set_active_transport
|
||||||
|
|
||||||
# Set up logging configuration for the MCP server
|
# Set up logging configuration for the MCP server
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
@@ -1338,12 +1338,14 @@ def _init_options() -> InitializationOptions:
|
|||||||
|
|
||||||
async def run_stdio():
|
async def run_stdio():
|
||||||
"""Run the MCP server using stdio transport"""
|
"""Run the MCP server using stdio transport"""
|
||||||
|
set_active_transport("stdio")
|
||||||
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
|
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
|
||||||
await app.run(read_stream, write_stream, _init_options())
|
await app.run(read_stream, write_stream, _init_options())
|
||||||
|
|
||||||
|
|
||||||
async def run_sse(host: str, port: int):
|
async def run_sse(host: str, port: int):
|
||||||
"""Run the MCP server using SSE transport (legacy MCP clients)"""
|
"""Run the MCP server using SSE transport (legacy MCP clients)"""
|
||||||
|
set_active_transport("sse")
|
||||||
auth_token = require_network_transport_auth("sse")
|
auth_token = require_network_transport_auth("sse")
|
||||||
try:
|
try:
|
||||||
from mcp.server.sse import SseServerTransport
|
from mcp.server.sse import SseServerTransport
|
||||||
@@ -1380,6 +1382,7 @@ async def run_sse(host: str, port: int):
|
|||||||
|
|
||||||
async def run_http(host: str, port: int):
|
async def run_http(host: str, port: int):
|
||||||
"""Run the MCP server using Streamable HTTP transport (MCP 2025-03-26 spec)"""
|
"""Run the MCP server using Streamable HTTP transport (MCP 2025-03-26 spec)"""
|
||||||
|
set_active_transport("http")
|
||||||
auth_token = require_network_transport_auth("http")
|
auth_token = require_network_transport_auth("http")
|
||||||
try:
|
try:
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
|||||||
Reference in New Issue
Block a user