Repository navigation
Expand file tree
/
Copy pathtest_websocket_security.py
More file actions
172 lines (142 loc) · 6.5 KB
/
Copy pathtest_websocket_security.py
File metadata and controls
172 lines (142 loc) · 6.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
"""Tests for WebSocket server request validation."""
# pyright: reportDeprecated=false
import logging
import multiprocessing
import socket
import warnings
import pytest
import uvicorn
from starlette.applications import Starlette
from starlette.routing import WebSocketRoute
from starlette.types import Message, Scope
from starlette.websockets import WebSocket
from websockets.asyncio.client import connect
from websockets.exceptions import InvalidStatus
from websockets.typing import Subprotocol
from mcp.server import Server
from mcp.server.transport_security import TransportSecuritySettings
from mcp.server.websocket import websocket_server
from tests.test_helpers import wait_for_server
logger = logging.getLogger(__name__)
SERVER_NAME = "test_ws_security_server"
# This suite intentionally exercises the deprecated WebSocket transport.
pytestmark = pytest.mark.filterwarnings(
"ignore:The WebSocket (client|server) transport is deprecated:DeprecationWarning"
)
@pytest.fixture
def server_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def run_server_with_settings(port: int, security_settings: TransportSecuritySettings | None = None): # pragma: no cover
"""Run a WebSocket MCP server with the given security settings."""
warnings.filterwarnings("ignore", category=DeprecationWarning)
server = Server(SERVER_NAME)
async def handle_ws(websocket: WebSocket) -> None:
try:
async with websocket_server(
websocket.scope, websocket.receive, websocket.send, security_settings=security_settings
) as streams:
await server.run(streams[0], streams[1], server.create_initialization_options())
except ValueError as exc:
logger.debug(f"WebSocket connection failed validation: {exc}")
app = Starlette(routes=[WebSocketRoute("/ws", endpoint=handle_ws)])
uvicorn.run(app, host="127.0.0.1", port=port, log_level="error")
def start_server_process(port: int, security_settings: TransportSecuritySettings | None = None):
"""Start the server in a subprocess and wait until it accepts connections."""
process = multiprocessing.Process(target=run_server_with_settings, args=(port, security_settings))
process.start()
wait_for_server(port)
return process
@pytest.mark.anyio
async def test_ws_security_default_settings(server_port: int) -> None:
"""With no security settings the WebSocket transport accepts any Origin (matches SSE/StreamableHTTP default)."""
process = start_server_process(server_port)
try:
async with connect(
f"ws://127.0.0.1:{server_port}/ws",
subprotocols=[Subprotocol("mcp")],
additional_headers={"Origin": "http://evil.com"},
) as ws:
assert ws.subprotocol == "mcp"
finally:
process.terminate()
process.join()
@pytest.mark.anyio
async def test_ws_security_invalid_origin_header(server_port: int) -> None:
"""An Origin not in allowed_origins is rejected before the handshake completes."""
settings = TransportSecuritySettings(
enable_dns_rebinding_protection=True, allowed_hosts=["127.0.0.1:*"], allowed_origins=["http://localhost:*"]
)
process = start_server_process(server_port, settings)
try:
with pytest.raises(InvalidStatus) as exc_info:
async with connect(
f"ws://127.0.0.1:{server_port}/ws",
subprotocols=[Subprotocol("mcp")],
additional_headers={"Origin": "http://evil.com"},
):
pytest.fail("handshake should have been rejected") # pragma: no cover
assert exc_info.value.response.status_code == 403
finally:
process.terminate()
process.join()
@pytest.mark.anyio
async def test_ws_security_invalid_host_header(server_port: int) -> None:
"""A Host not in allowed_hosts is rejected before the handshake completes."""
settings = TransportSecuritySettings(enable_dns_rebinding_protection=True, allowed_hosts=["example.com"])
process = start_server_process(server_port, settings)
try:
with pytest.raises(InvalidStatus) as exc_info:
async with connect(f"ws://127.0.0.1:{server_port}/ws", subprotocols=[Subprotocol("mcp")]):
pytest.fail("handshake should have been rejected") # pragma: no cover
assert exc_info.value.response.status_code == 403
finally:
process.terminate()
process.join()
@pytest.mark.anyio
async def test_ws_security_allowed_origin(server_port: int) -> None:
"""An Origin matching allowed_origins is accepted."""
settings = TransportSecuritySettings(
enable_dns_rebinding_protection=True, allowed_hosts=["127.0.0.1:*"], allowed_origins=["http://localhost:*"]
)
process = start_server_process(server_port, settings)
try:
async with connect(
f"ws://127.0.0.1:{server_port}/ws",
subprotocols=[Subprotocol("mcp")],
additional_headers={"Origin": "http://localhost:8080"},
) as ws:
assert ws.subprotocol == "mcp"
finally:
process.terminate()
process.join()
@pytest.mark.anyio
async def test_ws_security_disabled(server_port: int) -> None:
"""Explicitly disabling protection accepts any Origin."""
settings = TransportSecuritySettings(enable_dns_rebinding_protection=False)
process = start_server_process(server_port, settings)
try:
async with connect(
f"ws://127.0.0.1:{server_port}/ws",
subprotocols=[Subprotocol("mcp")],
additional_headers={"Origin": "http://evil.com"},
) as ws:
assert ws.subprotocol == "mcp"
finally:
process.terminate()
process.join()
@pytest.mark.anyio
async def test_ws_security_rejects_before_accept() -> None:
"""A failing validation closes the connection before the handshake is accepted."""
settings = TransportSecuritySettings(enable_dns_rebinding_protection=True, allowed_hosts=["example.com"])
sent: list[Message] = []
async def receive() -> Message:
raise NotImplementedError
async def send(message: Message) -> None:
sent.append(message)
scope: Scope = {"type": "websocket", "headers": [(b"host", b"evil.com")]}
with pytest.raises(ValueError, match="Request validation failed"):
async with websocket_server(scope, receive, send, security_settings=settings):
pytest.fail("should not yield streams") # pragma: no cover
assert [m["type"] for m in sent] == ["websocket.close"]