Skip to content

Instantly share code, notes, and snippets.

@gfranxman
Last active February 18, 2022 23:28
Show Gist options
  • Save gfranxman/289669e70871d807637ff1034715695a to your computer and use it in GitHub Desktop.
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.
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