Last active
February 18, 2022 23:28
-
-
Save gfranxman/289669e70871d807637ff1034715695a to your computer and use it in GitHub Desktop.
Python safepath to replace os.path.join when you don't want the path components to tmp outside a root path preventing path traversal.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def safepath_join(head, *tail): | |
""" | |
combines path parts like os.path.join, but ensures the resultant directory | |
doesn't step outside of the path given as the root. | |
""" | |
root = os.path.abspath(head) | |
p = os.path.normpath(os.path.join(head, *tail)) | |
if not p.startswith(root + os.path.sep): | |
raise ValueError(f"{p} steps outside {root}") | |
return p |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment