Skip to content

Commit

Permalink
salt.utils.verify.clean_path: make filesystem link resolution optinally
Browse files Browse the repository at this point in the history
  • Loading branch information
hurzhurz authored and s0undt3ch committed May 18, 2024
1 parent a204ad2 commit b0e7c62
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
21 changes: 12 additions & 9 deletions salt/utils/verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,25 +524,28 @@ def _realpath(path):
return os.path.realpath(path)


def clean_path(root, path, subdir=False):
def clean_path(root, path, subdir=False, realpath=True):
"""
Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to reside directly in the root
subdirectory of the root instead of having to reside directly in the root.
Pass realpath=False if filesystem links should not be resolved.
"""
real_root = _realpath(root)
if not os.path.isabs(real_root):
if not os.path.isabs(root):
return ""
root = os.path.normpath(root)
if not os.path.isabs(path):
path = os.path.join(root, path)
path = os.path.normpath(path)
real_path = _realpath(path)
if realpath:
root = _realpath(root)
path = _realpath(path)
if subdir:
if real_path.startswith(real_root):
return real_path
if os.path.commonpath([path, root]) == root:
return path
else:
if os.path.dirname(real_path) == os.path.normpath(real_root):
return real_path
if os.path.dirname(path) == root:
return path
return ""


Expand Down
8 changes: 8 additions & 0 deletions tests/pytests/unit/utils/verify/test_clean_path_link.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,11 @@ def test_clean_path_symlinked_tgt(setup_links):
expect_path = str(to_path / "test")
ret = salt.utils.verify.clean_path(str(from_path), str(test_path))
assert ret == expect_path, f"{ret} is not {expect_path}"


def test_clean_path_symlinked_src_unresolved(setup_links):
to_path, from_path = setup_links
test_path = from_path / "test"
expect_path = str(from_path / "test")
ret = salt.utils.verify.clean_path(str(from_path), str(test_path), realpath=False)
assert ret == expect_path, f"{ret} is not {expect_path}"

0 comments on commit b0e7c62

Please sign in to comment.