From d2e2bf7db8ca81a90aec4c491aca922cbb815221 Mon Sep 17 00:00:00 2001 From: hurzhurz Date: Tue, 23 Apr 2024 10:33:29 +0200 Subject: [PATCH] salt.utils.verify.clean_path: make filesystem link resolution optinally --- salt/utils/verify.py | 21 +++++++++++-------- .../unit/utils/verify/test_clean_path_link.py | 8 +++++++ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/salt/utils/verify.py b/salt/utils/verify.py index c4143996270..b3fe6c02c60 100644 --- a/salt/utils/verify.py +++ b/salt/utils/verify.py @@ -513,25 +513,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 "" diff --git a/tests/pytests/unit/utils/verify/test_clean_path_link.py b/tests/pytests/unit/utils/verify/test_clean_path_link.py index 8effa56a59c..99b18477eac 100644 --- a/tests/pytests/unit/utils/verify/test_clean_path_link.py +++ b/tests/pytests/unit/utils/verify/test_clean_path_link.py @@ -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}"