Skip to content

Commit 76fd00f

Browse files
fzlzjerryKludex
andauthored
Reject WebSocket requests to StaticFiles (#3532)
Co-authored-by: Marcelo Trylesinski <[email protected]>
1 parent f03f65c commit 76fd00f

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

‎starlette/staticfiles.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from starlette.exceptions import HTTPException
1616
from starlette.responses import FileResponse, RedirectResponse, Response
1717
from starlette.types import Receive, Scope, Send
18+
from starlette.websockets import WebSocketClose
1819

1920
PathLike = Union[str, "os.PathLike[str]"]
2021

@@ -88,6 +89,11 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
8889
"""
8990
The ASGI entry point.
9091
"""
92+
if scope["type"] == "websocket":
93+
websocket_close = WebSocketClose()
94+
await websocket_close(scope, receive, send)
95+
return
96+
9197
assert scope["type"] == "http"
9298

9399
if not self.config_checked:

‎tests/test_staticfiles.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from starlette.responses import Response
1717
from starlette.routing import Mount
1818
from starlette.staticfiles import StaticFiles
19+
from starlette.websockets import WebSocketDisconnect
1920
from tests.types import TestClientFactory
2021

2122

@@ -31,6 +32,17 @@ def test_staticfiles(tmpdir: Path, test_client_factory: TestClientFactory) -> No
3132
assert response.text == "<file content>"
3233

3334

35+
def test_staticfiles_websocket(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
36+
app = Starlette(routes=[Mount("/static", app=StaticFiles(directory=tmp_path))])
37+
client = test_client_factory(app)
38+
39+
with pytest.raises(WebSocketDisconnect) as exc:
40+
with client.websocket_connect("/static/example.txt"):
41+
pass # pragma: no cover - The connection is rejected before entering the context.
42+
43+
assert exc.value.code == 1000
44+
45+
3446
def test_staticfiles_with_pathlib(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
3547
path = tmp_path / "example.txt"
3648
with open(path, "w") as file:

0 commit comments

Comments
 (0)