Skip to content

Commit 31e4518

Browse files
committed
fix(skills): reject traversal segments and bare query/fragment delimiters in skill and directory URIs
1 parent 77001c9 commit 31e4518

2 files changed

Lines changed: 115 additions & 10 deletions

File tree

‎src/mcp/shared/skills.py‎

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
import re
1111
from typing import Annotated, Any, Literal
12-
from urllib.parse import urlsplit
12+
from urllib.parse import unquote, urlsplit
1313

1414
from mcp_types import CacheableResult, PaginatedRequestParams, PaginatedResult, Request, RequestParams, Resource
1515
from pydantic import AfterValidator, BaseModel, ConfigDict, Field, model_validator
@@ -218,6 +218,20 @@ class ReadDirectoryRequest(Request[ReadDirectoryParams, Literal["resources/direc
218218
params: ReadDirectoryParams
219219

220220

221+
def _has_query_or_fragment(uri: str) -> bool:
222+
"""Return True if `uri` contains a `?` or `#` delimiter, including bare trailing ones."""
223+
return "?" in uri or "#" in uri
224+
225+
226+
def _is_dot_or_traversal_segment(segment: str) -> bool:
227+
decoded = unquote(segment)
228+
return segment in (".", "..") or decoded in (".", "..") or "/" in decoded
229+
230+
231+
def _has_traversal_segment(path: str) -> bool:
232+
return any(_is_dot_or_traversal_segment(segment) for segment in path.split("/"))
233+
234+
221235
def skill_name_from_uri(uri: str) -> str:
222236
"""Return the skill `name` encoded in a `SKILL.md` resource URI.
223237
@@ -226,11 +240,14 @@ def skill_name_from_uri(uri: str) -> str:
226240
prefix) that segment is the authority.
227241
228242
Raises:
229-
ValueError: If `uri` is not an absolute URI ending in `/SKILL.md`.
243+
ValueError: If `uri` is not an absolute URI ending in `/SKILL.md`, or
244+
contains query/fragment delimiters or traversal path segments.
230245
"""
231246
parts = urlsplit(uri)
232-
if not parts.scheme or parts.query or parts.fragment:
247+
if not parts.scheme or _has_query_or_fragment(uri):
233248
raise ValueError(f"skill URI {uri!r} is not a valid absolute resource URI")
249+
if _has_traversal_segment(parts.path):
250+
raise ValueError(f"skill URI {uri!r} contains a traversal segment")
234251
if not parts.path.endswith("/SKILL.md"):
235252
raise ValueError(f"skill URI {uri!r} must end in /SKILL.md")
236253
directory = parts.path[: -len("/SKILL.md")].strip("/")
@@ -247,7 +264,7 @@ def _validate_resource_uri_in_skill(skill_uri: str, resource_uri: str) -> None:
247264
"""Raise `ValueError` unless `resource_uri` names a file within `skill_uri`'s directory."""
248265
skill_parts = urlsplit(skill_uri)
249266
resource_parts = urlsplit(resource_uri)
250-
if not resource_parts.scheme or resource_parts.query or resource_parts.fragment:
267+
if not resource_parts.scheme or _has_query_or_fragment(resource_uri):
251268
raise ValueError(f"resource URI {resource_uri!r} is invalid")
252269
if resource_uri.endswith("/"):
253270
raise ValueError(f"resource URI {resource_uri!r} names a directory, not a file")
@@ -256,22 +273,24 @@ def _validate_resource_uri_in_skill(skill_uri: str, resource_uri: str) -> None:
256273
root = skill_parts.path[: -len("/SKILL.md")]
257274
if resource_parts.path != skill_parts.path and not resource_parts.path.startswith(root + "/"):
258275
raise ValueError(f"resource URI {resource_uri!r} is outside the skill root {skill_uri!r}")
259-
if any(segment in (".", "..") for segment in resource_parts.path.split("/")):
276+
if _has_traversal_segment(resource_parts.path):
260277
raise ValueError(f"resource URI {resource_uri!r} contains a traversal segment")
261278

262279

263280
def parse_directory_uri(uri: str) -> tuple[str, str, str]:
264281
"""Split a directory resource URI into `(scheme, netloc, path)`.
265282
266283
Raises:
267-
ValueError: If `uri` has a trailing slash, or is otherwise not a valid
268-
absolute resource URI.
284+
ValueError: If `uri` has a trailing slash, traversal segments, query or
285+
fragment delimiters, or is otherwise not a valid absolute resource URI.
269286
"""
270287
if uri.endswith("/"):
271288
raise ValueError(f"directory URI {uri!r} must not have a trailing slash")
272289
parts = urlsplit(uri)
273-
if not parts.scheme or parts.query or parts.fragment:
290+
if not parts.scheme or _has_query_or_fragment(uri):
274291
raise ValueError(f"directory URI {uri!r} is not a valid absolute resource URI")
292+
if _has_traversal_segment(parts.path):
293+
raise ValueError(f"directory URI {uri!r} contains a traversal segment")
275294
return parts.scheme, parts.netloc, parts.path
276295

277296

@@ -291,12 +310,12 @@ def validate_directory_result(uri: str, result: ReadDirectoryResult) -> None:
291310
prefix = parent_path.rstrip("/") + "/" if parent_path.rstrip("/") else "/"
292311
for resource in result.resources:
293312
child = urlsplit(resource.uri)
294-
if not child.scheme or child.query or child.fragment:
313+
if not child.scheme or _has_query_or_fragment(resource.uri):
295314
raise ValueError(f"directory {uri!r} child has invalid URI {resource.uri!r}")
296315
if child.scheme != scheme or child.netloc != netloc:
297316
raise ValueError(f"resource {resource.uri!r} is not a child of directory {uri!r}")
298317
relative = child.path.removeprefix(prefix)
299-
if relative == child.path or not relative or "/" in relative or relative in (".", ".."):
318+
if relative == child.path or not relative or "/" in relative or _is_dot_or_traversal_segment(relative):
300319
raise ValueError(f"resource {resource.uri!r} is not a direct child of directory {uri!r}")
301320
if resource.uri in seen_uris:
302321
raise ValueError(f"directory {uri!r} contains a duplicate child {resource.uri!r}")

‎tests/shared/test_skills.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,3 +354,89 @@ def test_validate_directory_result_rejects_a_uri_outside_the_directory() -> None
354354
result = ReadDirectoryResult(resources=[Resource(uri="skill://other/file.md", name="file.md")])
355355
with pytest.raises(ValueError, match="not a child"):
356356
validate_directory_result("skill://pdf/templates", result)
357+
358+
359+
@pytest.mark.parametrize(
360+
"uri",
361+
[
362+
"skill://org/../my-skill/SKILL.md",
363+
"skill://org/./my-skill/SKILL.md",
364+
"skill://org/%2e%2e/my-skill/SKILL.md",
365+
"skill://org/%2E/my-skill/SKILL.md",
366+
],
367+
)
368+
def test_skill_name_from_uri_and_dynamic_skill_reject_traversal_segments(uri: str) -> None:
369+
with pytest.raises(ValueError, match="traversal segment"):
370+
skill_name_from_uri(uri)
371+
with pytest.raises(ValidationError, match="traversal segment"):
372+
Skill(uri=uri, frontmatter={"name": "my-skill", "description": "d"}, resources="dynamic")
373+
374+
375+
@pytest.mark.parametrize(
376+
"uri",
377+
[
378+
"skill://org/../../etc",
379+
"skill://org/./templates",
380+
"skill://org/%2e%2e/etc",
381+
"skill://org/%2E%2E/etc",
382+
],
383+
)
384+
def test_parse_directory_uri_rejects_traversal_segments(uri: str) -> None:
385+
with pytest.raises(ValueError, match="traversal segment"):
386+
parse_directory_uri(uri)
387+
388+
389+
@pytest.mark.parametrize(
390+
"uri",
391+
[
392+
"skill://my-skill/SKILL.md?",
393+
"skill://my-skill/SKILL.md#",
394+
],
395+
)
396+
def test_skill_name_from_uri_rejects_bare_query_and_fragment_delimiters(uri: str) -> None:
397+
with pytest.raises(ValueError, match="absolute resource URI"):
398+
skill_name_from_uri(uri)
399+
400+
401+
@pytest.mark.parametrize(
402+
"uri",
403+
[
404+
"skill://my-skill?",
405+
"skill://my-skill#",
406+
"skill://my-skill/templates?",
407+
"skill://my-skill/templates#",
408+
],
409+
)
410+
def test_parse_directory_uri_rejects_bare_query_and_fragment_delimiters(uri: str) -> None:
411+
with pytest.raises(ValueError, match="absolute resource URI"):
412+
parse_directory_uri(uri)
413+
414+
415+
@pytest.mark.parametrize(
416+
"resource_uri",
417+
[
418+
"skill://git-workflow/x.md?",
419+
"skill://git-workflow/x.md#",
420+
"skill://git-workflow/%2e%2e/evil.md",
421+
"skill://git-workflow/%2E/evil.md",
422+
],
423+
)
424+
def test_skill_rejects_bare_delimiters_and_encoded_traversal_in_resource_uri(resource_uri: str) -> None:
425+
with pytest.raises(ValidationError, match="is invalid|traversal segment"):
426+
_skill(extra_resources=[_resource(resource_uri)])
427+
428+
429+
@pytest.mark.parametrize(
430+
"child_uri",
431+
[
432+
"skill://pdf/templates/x.md?",
433+
"skill://pdf/templates/x.md#",
434+
"skill://pdf/templates/%2e",
435+
"skill://pdf/templates/%2e%2e",
436+
"skill://pdf/templates/a%2Fb.md",
437+
],
438+
)
439+
def test_validate_directory_result_rejects_bare_delimiters_and_encoded_traversal(child_uri: str) -> None:
440+
result = ReadDirectoryResult(resources=[Resource(uri=child_uri, name="x")])
441+
with pytest.raises(ValueError, match="invalid URI|direct child"):
442+
validate_directory_result("skill://pdf/templates", result)

0 commit comments

Comments
 (0)