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

Use pathlib for path resolution #2506

Merged
merged 4 commits into from Jul 31, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 13 additions & 10 deletions sanic/mixins/routes.py
Expand Up @@ -3,8 +3,8 @@
from functools import partial, wraps
from inspect import getsource, signature
from mimetypes import guess_type
from os import path, sep
from pathlib import PurePath
from os import path
from pathlib import Path, PurePath
from textwrap import dedent
from time import gmtime, strftime
from typing import (
Expand Down Expand Up @@ -806,22 +806,25 @@ async def _static_request_handler(
__file_uri__=None,
):
# Merge served directory and requested file if provided
root_path = file_path = path.abspath(unquote(file_or_directory))
file_path_raw = Path(unquote(file_or_directory))
root_path = file_path = file_path_raw.resolve()

if __file_uri__:
# Strip all / that in the beginning of the URL to help prevent
# python from herping a derp and treating the uri as an
# absolute path
unquoted_file_uri = unquote(__file_uri__).lstrip("/")

segments = unquoted_file_uri.split("/")
if ".." in segments or any(sep in segment for segment in segments):
file_path_raw = Path(file_or_directory, unquoted_file_uri)
file_path = file_path_raw.resolve()
if (
file_path < root_path and not file_path_raw.is_symlink()
) or file_path_raw.match("../**/*"):
raise BadRequest("Invalid URL")

file_path = path.join(file_or_directory, unquoted_file_uri)
file_path = path.abspath(file_path)

if not file_path.startswith(root_path):
if (
not file_path.is_relative_to(root_path)
and not file_path_raw.is_symlink()
):
error_logger.exception(
f"File not found: path={file_or_directory}, "
f"relative_url={__file_uri__}"
Expand Down
3 changes: 3 additions & 0 deletions tests/test_static.py
Expand Up @@ -616,6 +616,9 @@ def test_dotted_dir_ok(
def test_breakout(app: Sanic, static_file_directory: str):
app.static("/foo", static_file_directory)

_, response = app.test_client.get("/foo/..%2Ffake/server.py")
assert response.status == 400

_, response = app.test_client.get("/foo/..%2Fstatic/test.file")
assert response.status == 400

Expand Down