Skip to content

Clarify the documentation of pathlib.Path.is_relative_to() #99334

@thomas-mckay

Description

@thomas-mckay

Hi,

Currently (python 3.10.6 & 3.11.0):

from pathlib import Path

p = Path('/var/log/../../opt')
p.is_relative_to('/var/log')
>>> True

p = p.resolve()
p.is_relative_to('/var/log')
>>> False

Once you know is_relative_to uses relative_to, this makes more sense but it's not obvious from the documentation and the examples given. Also it can easily lead to code that looks secure but isn't. Case in point, I was tasked with reviewing this code today (simplified for illustration purposes):

path = Path(ROOT_PATH, user_input_rel_path)
if path.is_relative_to(ROOT_PATH):
    path.unlink()
else:
    raise PermissionError('Nope!')

I was unsure if I should open a bug or not because one could easily argue it isn't a bug. I do believe however that a warning in the documentation could save a few devs from making a mistake.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy