← retour aux snippets

pathlib.is_relative_to: vérifier l'ancrage dans une base

Empêcher les parcours hors base (path traversal) côté chemin.

python filesystem #pathlib#security

objectif

Empêcher les parcours hors base (path traversal) côté chemin.

code minimal

from pathlib import Path
base = Path("/safe/base")
child = base / "sub/dir"
print(child.is_relative_to(base))  # attendu: True (Python 3.9+)

utilisation

from pathlib import Path
base = Path("/x/base")
def safe_join(base: Path, user_path: str) -> Path:
    p = (base / user_path).resolve()
    if not p.is_relative_to(base.resolve()):
        raise ValueError("chemin hors base")
    return p
# démonstration (ne crée rien sur disque ici)
ok = safe_join(base, "a/b")
print(isinstance(ok, Path))

variante(s) utile(s)

from pathlib import Path
base = Path("/a"); outside = Path("/b")
print(not outside.is_relative_to(base))

notes

  • Utilisez resolve() avant is_relative_to pour normaliser.
  • Pour Python <3.9, comparez base in p.parents + p.