Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 6 additions & 16 deletions src/mcp/server/transport_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,9 @@ def _validate_host(self, host: str | None) -> bool:
if host in self.settings.allowed_hosts:
Comment thread
Kludex marked this conversation as resolved.
Resolved
return True

# Check wildcard port patterns
for allowed in self.settings.allowed_hosts:
if allowed.endswith(":*"):
# Extract base host from pattern
base_host = allowed[:-2]
# Check if the actual host starts with base host and has a port
if host.startswith(base_host + ":"):
return True
base_host, colon, port = host.rpartition(":")
if colon and port.isascii() and port.isdigit() and f"{base_host}:*" in self.settings.allowed_hosts:
return True

logger.warning(f"Invalid Host header: {host}")
return False
Expand All @@ -79,14 +74,9 @@ def _validate_origin(self, origin: str | None) -> bool:
if origin in self.settings.allowed_origins:
return True

# Check wildcard port patterns
for allowed in self.settings.allowed_origins:
if allowed.endswith(":*"):
# Extract base origin from pattern
base_origin = allowed[:-2]
# Check if the actual origin starts with base origin and has a port
if origin.startswith(base_origin + ":"):
return True
base_origin, colon, port = origin.rpartition(":")
if colon and port.isascii() and port.isdigit() and f"{base_origin}:*" in self.settings.allowed_origins:
return True

logger.warning(f"Invalid Origin header: {origin}")
return False
Expand Down
14 changes: 14 additions & 0 deletions tests/server/test_transport_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,15 @@ def _request(host: str | None, origin: str | None, content_type: str | None = "a
pytest.param("evil.example:9000", None, 421, id="host-wildcard-base-mismatch"),
pytest.param("good.example", None, None, id="host-exact-no-origin"),
pytest.param("wild.example:9000", None, None, id="host-wildcard-match"),
pytest.param("wild.example:abc", None, 421, id="host-wildcard-non-numeric-port"),
pytest.param("wild.example:", None, 421, id="host-wildcard-empty-port"),
pytest.param("good.example", "http://evil.example", 403, id="origin-no-match"),
pytest.param("good.example", "http://evil.example:9000", 403, id="origin-wildcard-base-mismatch"),
pytest.param("good.example", "http://good.example", None, id="origin-exact"),
pytest.param("good.example", "http://wild.example:9000", None, id="origin-wildcard-match"),
pytest.param(
"good.example", "http://wild.example:9000.other.example", 403, id="origin-wildcard-non-numeric-port"
),
],
)
async def test_validate_request_checks_host_then_origin(
Expand All @@ -56,6 +61,15 @@ async def test_validate_request_checks_host_then_origin(
assert (None if response is None else response.status_code) == expected


@pytest.mark.anyio
async def test_validate_request_wildcard_port_needs_a_colon() -> None:
"""A bare `:*` entry does not match a Host that is only digits."""
middleware = TransportSecurityMiddleware(TransportSecuritySettings(allowed_hosts=[":*"]))
response = await middleware.validate_request(_request("8080", None))
assert response is not None
assert response.status_code == 421


@pytest.mark.anyio
async def test_validate_request_skips_host_and_origin_when_protection_is_disabled() -> None:
"""With DNS-rebinding protection off, any Host/Origin is accepted."""
Expand Down
Loading