Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

fix!: Validate OpenAPI path parameter segments (#5457)

Jeremiah Lowinf98b44d0e3f2
diff --git a/docs/integrations/openapi.mdx b/docs/integrations/openapi.mdx
index 1572dc4cd..cdd7f4f21 100644
--- a/docs/integrations/openapi.mdx
+++ b/docs/integrations/openapi.mdx
@@ -428,6 +428,8 @@ Path parameters are typically required by REST APIs. FastMCP:
- Validates that all required path parameters are provided
- Raises clear errors for missing required parameters
+Path values must not contain `.` or `..` segments, including percent-encoded forms. Ordinary dotted names such as `report.json` are accepted.
+
```python
# βœ… This works
await client.call_tool("get_user", {"user_id": 123})
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/director.py b/fastmcp_slim/fastmcp/utilities/openapi/director.py
index 84cf9a787..7067586a0 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/director.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/director.py
@@ -4,7 +4,7 @@ import io
import json as _json
from email.message import Message
from typing import Any, ClassVar
-from urllib.parse import quote, urljoin
+from urllib.parse import quote, unquote, urljoin
import httpx2
from jsonschema_path import SchemaPath
@@ -16,6 +16,8 @@ from .schemas import _combine_schemas_and_map_params, _ref_is_mergeable_object
logger = get_logger(__name__)
+_MAX_PATH_DECODINGS = 32
+
def _query_scalar_to_str(value: Any) -> str:
"""Convert a scalar to its query-string representation.
@@ -406,6 +408,23 @@ class RequestDirector:
for param_name, param_value in path_params.items():
placeholder = f"{{{param_name}}}"
if placeholder in url_path:
+ decoded = str(param_value)
+ for _ in range(_MAX_PATH_DECODINGS):
+ if any(
+ part in {".", ".."}
+ for part in decoded.replace("\\", "/").split("/")
+ ):
+ raise ValueError(
+ f"Path parameter '{param_name}' cannot contain dot segments"
+ )
+ expanded = unquote(decoded)
+ if expanded == decoded:
+ break
+ decoded = expanded
+ else:
+ raise ValueError(
+ f"Path parameter '{param_name}' has too many encoding layers"
+ )
safe_value = quote(str(param_value), safe="").replace(".", "%2E")
url_path = url_path.replace(placeholder, safe_value)
diff --git a/tests/utilities/openapi/test_director.py b/tests/utilities/openapi/test_director.py
index cd0b43815..33e1373ef 100644
--- a/tests/utilities/openapi/test_director.py
+++ b/tests/utilities/openapi/test_director.py
@@ -1,7 +1,6 @@
"""Unit tests for RequestDirector."""
import json
-from urllib.parse import unquote
import pytest
from jsonschema_path import SchemaPath
@@ -1154,14 +1153,8 @@ class TestPathTraversalPrevention:
],
)
def test_path_traversal_encoded(self, director, path_route, malicious_id: str):
- request = director.build(
- path_route, {"id": malicious_id}, "https://api.example.com"
- )
- url = str(request.url)
- assert "/admin" not in url
- assert "/secret" not in url
- assert "/etc/passwd" not in url
- assert url.startswith("https://api.example.com/api/v1/users/")
+ with pytest.raises(ValueError, match="dot segments"):
+ director.build(path_route, {"id": malicious_id}, "https://api.example.com")
def test_slash_in_param_is_encoded(self, director, path_route):
request = director.build(path_route, {"id": "a/b"}, "https://api.example.com")
@@ -1170,12 +1163,8 @@ class TestPathTraversalPrevention:
assert "a%2Fb" in url
def test_dot_dot_slash_is_encoded(self, director, path_route):
- request = director.build(
- path_route, {"id": "../admin"}, "https://api.example.com"
- )
- url = str(request.url)
- assert "%2E%2E%2Fadmin" in url or "%2e%2e%2fadmin" in url
- assert url.startswith("https://api.example.com/api/v1/users/")
+ with pytest.raises(ValueError, match="dot segments"):
+ director.build(path_route, {"id": "../admin"}, "https://api.example.com")
def test_question_mark_encoded(self, director, path_route):
request = director.build(
@@ -1213,30 +1202,18 @@ class TestPathTraversalPrevention:
assert str(request.url) == "https://api.example.com/api/v1/users/42/profile"
def test_bare_single_dot_encoded(self, director, path_route):
- """Bare '.' must be encoded so urljoin doesn't normalize it away."""
- request = director.build(path_route, {"id": "."}, "https://api.example.com")
- url = str(request.url)
- assert "%2E" in url
- assert url.startswith("https://api.example.com/api/v1/users/")
+ with pytest.raises(ValueError, match="dot segments"):
+ director.build(path_route, {"id": "."}, "https://api.example.com")
def test_bare_dotdot_encoded(self, director, path_route):
- """Bare '..' must be encoded so urljoin doesn't resolve it as traversal."""
- request = director.build(path_route, {"id": ".."}, "https://api.example.com")
- url = str(request.url)
- assert "%2E%2E" in url or "%2e%2e" in url
- assert url.startswith("https://api.example.com/api/v1/users/")
+ with pytest.raises(ValueError, match="dot segments"):
+ director.build(path_route, {"id": ".."}, "https://api.example.com")
def test_double_encoded_traversal(self, director, path_route):
- request = director.build(
- path_route,
- {"id": "..%2F..%2Fadmin"},
- "https://api.example.com",
- )
- url = str(request.url)
- decoded = unquote(unquote(url))
- # Verify traversal didn't escape the users/ prefix
- assert decoded.startswith("https://api.example.com/api/v1/users/")
- assert url.startswith("https://api.example.com/api/v1/users/")
+ with pytest.raises(ValueError, match="dot segments"):
+ director.build(
+ path_route, {"id": "..%2F..%2Fadmin"}, "https://api.example.com"
+ )
class TestContentTypeDispatch:
diff --git a/tests/utilities/openapi/test_path_values.py b/tests/utilities/openapi/test_path_values.py
new file mode 100644
index 000000000..00acc60d3
--- /dev/null
+++ b/tests/utilities/openapi/test_path_values.py
@@ -0,0 +1,95 @@
+"""Path values remain data within an operation's declared route."""
+
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from threading import Thread
+
+import httpx2
+import pytest
+from jsonschema_path import SchemaPath
+
+from fastmcp import Client, FastMCP
+from fastmcp.exceptions import ToolError
+from fastmcp.utilities.openapi.director import RequestDirector
+
+
+ "value",
+ [
+ ".",
+ "..",
+ "../other",
+ "other/../x",
+ r"other\..\x",
+ "%2e%2e",
+ "%252e%252e",
+ "..%2fother",
+ "other%5c..%5cx",
+ ],
+)
+def test_path_value_rejects_dot_segments(value: str):
+ with pytest.raises(ValueError, match="dot segments"):
+ RequestDirector(SchemaPath.from_dict({}))._build_url(
+ "/items/{id}/record", {"id": value}, "https://api.example.com"
+ )
+
+
+ "value", ["item.1", ".hidden", "..name", "a/b", "a\\b", "100%", 42]
+)
+def test_path_value_preserves_ordinary_data(value: str | int):
+ url = RequestDirector(SchemaPath.from_dict({}))._build_url(
+ "/items/{id}/record", {"id": value}, "https://api.example.com"
+ )
+ assert url.startswith("https://api.example.com/items/")
+ assert url.endswith("/record")
+
+
+async def test_path_value_is_checked_before_backend_request(tmp_path: Path):
+ (tmp_path / "api" / "users").mkdir(parents=True)
+ (tmp_path / "api" / "admin.txt").write_text("private-record")
+ handler = partial(SimpleHTTPRequestHandler, directory=str(tmp_path))
+ backend = ThreadingHTTPServer(("127.0.0.1", 0), handler)
+ worker = Thread(target=backend.serve_forever, daemon=True)
+ worker.start()
+ spec = {
+ "openapi": "3.0.0",
+ "info": {"title": "API", "version": "1"},
+ "paths": {
+ "/api/users/{id}/admin.txt": {
+ "get": {
+ "operationId": "get_record",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": True,
+ "schema": {"type": "string"},
+ }
+ ],
+ "responses": {"200": {"description": "OK"}},
+ }
+ }
+ },
+ }
+ try:
+ async with httpx2.AsyncClient(
+ base_url=f"http://127.0.0.1:{backend.server_port}"
+ ) as http:
+ server = FastMCP.from_openapi(spec, client=http)
+ async with Client(server) as client:
+ with pytest.raises(ToolError, match="dot segments"):
+ await client.call_tool("get_record", {"id": ".."})
+ finally:
+ backend.shutdown()
+ backend.server_close()
+ worker.join()
+
+
+def test_path_value_rejects_excessive_encoding_layers():
+ value = "%" + "25" * 40 + "2e"
+ with pytest.raises(ValueError, match="too many encoding layers"):
+ RequestDirector(SchemaPath.from_dict({}))._build_url(
+ "/items/{id}", {"id": value}, "https://api.example.com"
+ )