61 lines
2.1 KiB
Python
61 lines
2.1 KiB
Python
"""is_safe_path 路径遍历防护测试."""
|
|
from src.core.security import is_safe_path
|
|
|
|
|
|
class TestIsSafePath:
|
|
"""is_safe_path 函数测试."""
|
|
|
|
# -- 合法路径 --
|
|
def test_relative_path_ok(self):
|
|
"""相对路径应通过."""
|
|
assert is_safe_path("docs/readme.md") is True
|
|
assert is_safe_path("src/core/config.py") is True
|
|
|
|
def test_single_filename_ok(self):
|
|
"""仅文件名应通过."""
|
|
assert is_safe_path("readme.md") is True
|
|
assert is_safe_path("config.yaml") is True
|
|
|
|
def test_nested_relative_path_ok(self):
|
|
"""深层相对路径应通过."""
|
|
assert is_safe_path("a/b/c/d/e/file.md") is True
|
|
|
|
def test_dot_prefix_dir_ok(self):
|
|
"""以 . 开头的目录名(如 .config)是合法的."""
|
|
assert is_safe_path(".config/settings.yaml") is True
|
|
|
|
def test_current_dir_prefix_ok(self):
|
|
"""./ 前缀的路径应通过."""
|
|
assert is_safe_path("./docs/readme.md") is True
|
|
|
|
# -- 非法路径 --
|
|
def test_absolute_path_rejected(self):
|
|
"""绝对路径应拒绝."""
|
|
# Windows 绝对路径
|
|
assert is_safe_path("D:/Code/test.md") is False
|
|
assert is_safe_path("C:\\Windows\\system32") is False
|
|
|
|
def test_parent_dir_traversal_rejected(self):
|
|
""".. 目录穿越应拒绝."""
|
|
assert is_safe_path("../secret.txt") is False
|
|
assert is_safe_path("docs/../../../etc/passwd") is False
|
|
assert is_safe_path("foo/bar/..") is False
|
|
|
|
def test_encoded_traversal_rejected(self):
|
|
"""以 .. 开头的相对路径也被拒绝."""
|
|
assert is_safe_path("..") is False
|
|
assert is_safe_path("../..") is False
|
|
|
|
def test_windows_style_traversal_rejected(self):
|
|
"""Windows 风格路径穿越."""
|
|
assert is_safe_path("..\\..\\secret.txt") is False
|
|
|
|
# -- 边界情况 --
|
|
def test_empty_string(self):
|
|
"""空字符串."""
|
|
assert is_safe_path("") is True # normpath("") → ""
|
|
|
|
def test_dot_only(self):
|
|
"""仅 '.' 的路径."""
|
|
assert is_safe_path(".") is True # normpath(".") → ""
|