django-storages: I can't upload image with dropbox SuspiciousFileOperation

settings.py

STATICFILES_STORAGE = 'storages.backends.dropbox.DropBoxStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage'
DROPBOX_OAUTH2_TOKEN = 'xxx-xxx'
DROPBOX_ROOT_PATH = '/TKYK/'

my models.py

def get_image_filename(instance, filename):
    fpath = pathlib.Path(filename)
    new_fname = str(uuid.uuid1()) # uuid1 -> uuid + timestamps
    return f"patient/{new_fname}{fpath.suffix}"

class Image (models.Model):
    me = models.ForeignKey(me, on_delete=models.CASCADE)
    images_data = models.FileField(upload_to=get_image_filename)

error when upload via django admin site image

But I see the image already uploaded to dropbox image

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 1
  • Comments: 15 (3 by maintainers)

Commits related to this issue

Most upvoted comments

I needed to get around this, so FWIW, here is a monkey patch to django that seems to work (not sure if this has any unintended consequences):

import os
import pathlib

from django.core.exceptions import SuspiciousFileOperation
from django.core.files import storage


# monkey patch django for https://github.com/jschneier/django-storages/issues/1109
def validate_file_name(name, allow_relative_path=False):
    # Remove potentially dangerous names
    if os.path.basename(name) in {'', '.', '..'}:
        raise SuspiciousFileOperation('Could not derive file name from "%s"' % name)

    if allow_relative_path:
        # Use PurePosixPath() because this branch is checked only in
        # FileField.generate_filename() where all file paths are expected to be
        # Unix style (with forward slashes).
        path = pathlib.PurePosixPath(name)
        # if path.is_absolute() or '..' in path.parts:  # <----------- problem
        if '..' in path.parts:
            raise SuspiciousFileOperation(
                'Detected path traversal attempt in "%s"' % name
            )
    elif name != os.path.basename(name):
        raise SuspiciousFileOperation('File name "%s" includes path elements' % name)

    return name

storage.validate_file_name = validate_file_name

I am having the same issue I am using django-dbbackup to send files to dropbox. Django=3.2.11 django.core.exceptions.SuspiciousFileOperation: Detected path traversal attempt in '/default-ubuntu-2022-02-10-114225.psql'