Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Send 404 instead of 500 when filename requested is too long on StaticFiles #2583

Merged
merged 4 commits into from
Jun 1, 2024
Merged
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
9 changes: 7 additions & 2 deletions starlette/staticfiles.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import errno
import importlib.util
import os
import stat
Expand Down Expand Up @@ -124,8 +125,12 @@ async def get_response(self, path: str, scope: Scope) -> Response:
)
except PermissionError:
raise HTTPException(status_code=401)
except OSError:
raise
except OSError as exc:
# Filename is too long, so it can't be a valid static file.
if exc.errno == errno.ENAMETOOLONG:
raise HTTPException(status_code=404)

raise exc

if stat_result and stat.S_ISREG(stat_result.st_mode):
# We have a static file to serve.
Expand Down
13 changes: 13 additions & 0 deletions tests/test_staticfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,19 @@ def test_staticfiles_access_file_as_dir_returns_404(
assert response.text == "Not Found"


def test_staticfiles_filename_too_long(
tmpdir: Path, test_client_factory: TestClientFactory
) -> None:
routes = [Mount("/", app=StaticFiles(directory=tmpdir), name="static")]
app = Starlette(routes=routes)
client = test_client_factory(app)

path_max_size = os.pathconf("/", "PC_PATH_MAX")
response = client.get(f"/{'a' * path_max_size}.txt")
assert response.status_code == 404
assert response.text == "Not Found"


def test_staticfiles_unhandled_os_error_returns_500(
tmpdir: Path,
test_client_factory: TestClientFactory,
Expand Down