Skip to content

Commit

Permalink
Fix: Resolve the issue where the directory itself being a symlink doe…
Browse files Browse the repository at this point in the history
…s not work.
  • Loading branch information
hanxi committed Sep 30, 2024
1 parent 0b50b9c commit 6410378
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion starlette/staticfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def lookup_path(self, path: str) -> tuple[str, os.stat_result | None]:
full_path = os.path.abspath(joined_path)
else:
full_path = os.path.realpath(joined_path)
directory = os.path.realpath(directory)
directory = os.path.realpath(directory)
if os.path.commonpath([full_path, directory]) != directory:
# Don't allow misbehaving clients to break out of the static files
# directory.
Expand Down
20 changes: 20 additions & 0 deletions tests/test_staticfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,3 +559,23 @@ def test_staticfiles_avoids_path_traversal(tmp_path: Path) -> None:

assert exc_info.value.status_code == 404
assert exc_info.value.detail == "Not Found"


def test_staticfiles_self_symlinks(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
statics_path = os.path.join(tmpdir, "statics")
os.mkdir(statics_path)

source_file_path = os.path.join(statics_path, "index.html")
with open(source_file_path, "w") as file:
file.write("<h1>Hello</h1>")

statics_symlink_path = os.path.join(tmpdir, "statics_symlink")
os.symlink(statics_path, statics_symlink_path)

app = StaticFiles(directory=statics_symlink_path, follow_symlink=True)
client = test_client_factory(app)

response = client.get("/index.html")
assert response.url == "http://testserver/index.html"
assert response.status_code == 200
assert response.text == "<h1>Hello</h1>"

0 comments on commit 6410378

Please sign in to comment.