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.

PythonSecurity Boundaries

Code

snippet
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 paths

What 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

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.