How I cheated the Python interpreter

During my first hours of reckoning working on chad I came down with a problem.

Since we try to exploit the model of monorepo we’ve decided that we’ll have our frontend served by the backend. It is generally a very bad idea and an anti-pattern, but since we’ll be building the backend and frontend from the same repository into one single Docker image, this has been found as a sane compromise.

Namely, I would like to handle all (previously unhandled) calls to backend that requires no prefix (ie. if I queried for /.gitkeep I’d get .gitkeep) get the static file server, which takes a URL path, navigates the filesystem that tends to find the offending file, however problem was found in it’s constructor:

def static(prefix, view=serve, **kwargs):
    """
    Return a URL pattern for serving files in debug mode.

    from django.conf import settings
    from django.conf.urls.static import static

    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    """
    if not prefix:
        raise ImproperlyConfigured("Empty static prefix not permitted")
    elif not settings.DEBUG or urlsplit(prefix).netloc:
        # No-op if not in debug mode or a non-local prefix.
        return []
    return [
        re_path(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs),
    ]

It clearly accepts a prefix that cannot be equal to False, so if we were limited to expressing ourselves with empty strings which natively are equal to False is a way nowhere. A closer inspection of the source code reveals that an empty prefix is indeed a distinct possiblity.

Note how the check here is performed. There is no in '' syntax. There’s no checking equality to a specific value. Empty string, being a static would have been interned anyway by the Python interpreter itself. We need a particular piece of code to defeat it. We need advanced cheese, namely – empty strings that evaluate to True:

class TrueString(str):
   def __bool__(self):
      return True

#: which conforms to the specification of:

emptystring = TrueString('')
assert emptystring
assert bool(emptystring)
assert len(emptystring) == 0
assert emptystring == ''

Thanks to the Python nature of everything-can-be-extended class system. So naturally being a case of static I handled it like this:

   ...
   path(r'swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
] + static(TrueString(''), document_root=settings.STATIC_ROOT)

Me and the interpreter parted ways in best of the moods.

Now it’s time for your advanced cheese stories.

Published

By Piotr Maślanka

Programmer, certified first aider, entrepreneur, biotechnologist, expert witness, mentor, former PhD student. Your favourite renaissance man.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.