Skip to content

Commit

Permalink
test traversal_safe_path
Browse files Browse the repository at this point in the history
  • Loading branch information
rmorshea committed Apr 5, 2022
1 parent eff3718 commit 3ba0ef5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/idom/server/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ def safe_web_modules_dir_path(path: str) -> Path:
return traversal_safe_path(IDOM_WEB_MODULES_DIR.current, *path.split("/"))


def traversal_safe_path(root: Path, *unsafe: str | Path) -> Path:
def traversal_safe_path(root: str | Path, *unsafe: str | Path) -> Path:
"""Raise a ``ValueError`` if the ``unsafe`` path resolves outside the root dir."""
root = root.resolve()
root = Path(root).resolve()
# resolve relative paths and symlinks
path = root.joinpath(*unsafe).resolve()

Expand Down
22 changes: 22 additions & 0 deletions tests/test_server/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import threading
import time
from contextlib import ExitStack
from pathlib import Path

import pytest
from playwright.async_api import Page
Expand All @@ -10,6 +11,7 @@
from idom.server import flask as flask_implementation
from idom.server.utils import find_available_port
from idom.server.utils import run as sync_run
from idom.server.utils import traversal_safe_path
from tests.tooling.loop import open_event_loop


Expand Down Expand Up @@ -49,3 +51,23 @@ def run_in_thread():

await page.goto(url)
await page.wait_for_selector("#sample")


@pytest.mark.parametrize(
"bad_path",
[
"../escaped",
"ok/../../escaped",
"ok/ok-again/../../ok-yet-again/../../../escaped",
],
)
def test_catch_unsafe_relative_path_traversal(tmp_path, bad_path):
with pytest.raises(ValueError, match="Unsafe path"):
traversal_safe_path(tmp_path, *bad_path.split("/"))


def test_catch_unsafe_symlink_path_traversal(tmp_path):
symlink: Path = tmp_path / "file.txt"
symlink.symlink_to(tmp_path.parent / "escaped-file.txt")
with pytest.raises(ValueError, match="Unsafe path"):
traversal_safe_path(tmp_path, "file.txt")

0 comments on commit 3ba0ef5

Please sign in to comment.