[Python-ideas] Working with Path objects: p-strings?

Sjoerd Job Postmus sjoerdjob at sjec.nl
Tue Mar 29 03:46:34 EDT 2016


On Tue, Mar 29, 2016 at 06:27:09PM +1100, Chris Angelico wrote:
> On Tue, Mar 29, 2016 at 6:22 PM, Sven R. Kunze <srkunze at mail.de> wrote:
> > Thinking more about it, that would even come in nicely with path separators:
> >
> > p'/{whereever}/{youwant}/{togo}'
> >
> > That'll finally an easy-to-write and readable path generation. Great idea,
> > Stephen.
> 
> Agreed, although this introduces a new edge case: what if 'togo'
> contains a slash? Should this raise an exception, or should it be
> interpreted as a multi-part path component? Arguments can be put for
> both sides.

As we all know, togo is user input containing
    ../../../../../../../../../../../../../../../etc/passwd

I agree that both sides can get arguments. However, if it does raise an
exception, you'd have to go through hoops to make it work with
components that might contain a slash. The other way around, however, is

    p'/{whereever}/{youwant}/{nosl(togo)}'

where 'nosl' (or something similar) is a function that checks that the
string 'togo' matches some sensible expectations:

 - Does not contain a '/'.
 - Does not equal '..'

One of the codebases I worked at also had to work with relative paths,
and we had a similar helper function which we used for

    os.path.join(
        whereever,
        youwant,
        nosl(togo),
    )

It hurts me to say this, but in this case it is probably better to slap
on extra security later, than to make it too secure a default.

An alternative might be to look at what frameworks like Django do w.r.t.
XSS prevention, and do something like

    p'/{whereever}/{youwant}/{togo:|safe}'

However I'm not really a fan of that.

> 
> But it's pretty cool.
> 
> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/


More information about the Python-ideas mailing list