Commonpath Finds The Shared Root And Guards Containment
os.path.commonpath computes the longest common parent for grouping and prefix stripping; comparing it against a base directory detects escaped paths.
Code
import os.path
base = "/srv/app/uploads"
files = [
"/srv/app/uploads/reports/q4.xlsx",
"/srv/app/uploads/invoices/inv-204.pdf",
"/srv/app/uploads/avatar.png",
]
# Longest common parent directory: archive prefixing and log grouping both need it
shared = os.path.commonpath(files)
print("shared root:", shared)
for path in sorted(files):
print(" -", os.path.relpath(path, shared))
# Containment guard: when the common root of [base, path] is not base itself, the path escaped
user_path = "/srv/app/secrets.env"
contained = os.path.commonpath([base, user_path]) == base
print(user_path, "inside base:", contained)
# Absolute and relative paths cannot be mixed; commonpath raises ValueError
try:
os.path.commonpath([base, "uploads/avatar.png"])
except ValueError as error:
print("cannot mix:", error)Output
Captured from a sandboxed run of this snippet in the build pipeline.
shared root: \srv\app\uploads
- avatar.png
- invoices\inv-204.pdf
- reports\q4.xlsx
/srv/app/secrets.env inside base: False
cannot mix: Can't mix absolute and relative pathsWhat the demo guards
os.path.commonpath(files) finds the longest shared parent, /srv/app/uploads, and the loop prints each file relative to that root, the prefix-stripping step archive packaging needs.
The containment check is the security half: commonpath([base, user_path]) returns /srv/app, not base, so the equality test prints inside base: False for secrets.env. Mixing absolute and relative inputs raises ValueError, caught and printed as cannot mix.
Points worth noting
- commonpath is lexical; it never touches the filesystem.
- The equality form catches escapes that startswith misses.
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- Why compare commonpath to the base instead of startswith?
- Prefix string checks match siblings like /srv/app/uploads-evil; comparing the computed common root to base decides containment structurally, as the False for secrets.env shows.
Report a problem with this exampleOpens a pre-filled issue on GitHub.