Avoid misuse sanitize_path, clarify docs (#45469)

This commit is contained in:
Paulus Schoutsen 2021-01-23 18:28:57 +01:00 committed by GitHub
parent f86beed7b0
commit 0930aae208
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 10 deletions

View file

@ -33,13 +33,33 @@ RE_SANITIZE_PATH = re.compile(r"(~|\.(\.)+)")
def sanitize_filename(filename: str) -> str: def sanitize_filename(filename: str) -> str:
r"""Sanitize a filename by removing .. / and \\.""" """Check if a filename is safe.
return RE_SANITIZE_FILENAME.sub("", filename)
Only to be used to compare to original filename to check if changed.
If result changed, the given path is not safe and should not be used,
raise an error.
DEPRECATED.
"""
# Backwards compatible fix for misuse of method
if RE_SANITIZE_FILENAME.sub("", filename) != filename:
return ""
return filename
def sanitize_path(path: str) -> str: def sanitize_path(path: str) -> str:
"""Sanitize a path by removing ~ and ..""" """Check if a path is safe.
return RE_SANITIZE_PATH.sub("", path)
Only to be used to compare to original path to check if changed.
If result changed, the given path is not safe and should not be used,
raise an error.
DEPRECATED.
"""
# Backwards compatible fix for misuse of method
if RE_SANITIZE_PATH.sub("", path) != path:
return ""
return path
def slugify(text: str, *, separator: str = "_") -> str: def slugify(text: str, *, separator: str = "_") -> str:

View file

@ -11,17 +11,17 @@ import homeassistant.util.dt as dt_util
def test_sanitize_filename(): def test_sanitize_filename():
"""Test sanitize_filename.""" """Test sanitize_filename."""
assert util.sanitize_filename("test") == "test" assert util.sanitize_filename("test") == "test"
assert util.sanitize_filename("/test") == "test" assert util.sanitize_filename("/test") == ""
assert util.sanitize_filename("..test") == "test" assert util.sanitize_filename("..test") == ""
assert util.sanitize_filename("\\test") == "test" assert util.sanitize_filename("\\test") == ""
assert util.sanitize_filename("\\../test") == "test" assert util.sanitize_filename("\\../test") == ""
def test_sanitize_path(): def test_sanitize_path():
"""Test sanitize_path.""" """Test sanitize_path."""
assert util.sanitize_path("test/path") == "test/path" assert util.sanitize_path("test/path") == "test/path"
assert util.sanitize_path("~test/path") == "test/path" assert util.sanitize_path("~test/path") == ""
assert util.sanitize_path("~/../test/path") == "//test/path" assert util.sanitize_path("~/../test/path") == ""
def test_slugify(): def test_slugify():