KalvadTech / django-cloudflare-images

Django library to add Cloudflare Images support for ImageField
MIT License
15 stars 6 forks source link

Security check while uploading. #4

Closed ChetSocio closed 1 year ago

ChetSocio commented 1 year ago

Hello Dev/Author of this project,


def validate_warranty_media_mimetype(file):
    """only to accept certain file types in product warranty model"""

    accepted_types = ['image/png', 'image/jpeg']
    file_mime_type = magic.from_buffer(file.read(1024), mime=True)
    if file_mime_type not in accepted_types:
        raise ValidationError("Only .png, .jpg images  are accepted")

I was using models.FileField(upload_to='images', validators=[validate_warranty_media_mimetype]) instead of modes.ImageField(upload_to='images') so that I could run checks before uploading files to avoid saving xss or malicious scripts. I have seen that your package needs the field to have CloudflareImagesField

How can i achieve same using this package ???

hnb2 commented 1 year ago

Hello @ChetSocio,

Basically you should be using a CloudflareImagesField only if you need to have a specific variant for your field, otherwise there is no need.

Your example with a validator should work with this package, though i would recommend using an ImageField instead of a FileField in this case.

Please let me know how it goes for you.

ChetSocio commented 1 year ago

I always used ImageField but recently I read that it doesnot validates exact file type. Like if a hacker sends hello.py.png, the file will be stored which raises security issue. Relying on client side for validation is foolishness most of the times. So in blog i found this way and this way is secure. So Is there any way that I can use my code and still use cloudflare. Their pricing is very affordable for my business. The sad thing is that Imagefield doesnot accept validators props.

hnb2 commented 1 year ago

ImageField inherits from FileField (See https://github.com/django/django/blob/main/django/db/models/fields/files.py#L390) so it should not be a problem.

For the file validation I understand your motivation, it makes sense to add a validator.

You should be able to use your code and this library, just setup:

CLOUDFLARE_IMAGES_ACCOUNT_ID = "XXX"
CLOUDFLARE_IMAGES_API_TOKEN = "YYY"
CLOUDFLARE_IMAGES_ACCOUNT_HASH = "ZZZ"

And the STORAGES or DEFAULT_FILE_STORAGE based on your django version (see README.md) for all of this.

hnb2 commented 1 year ago

Hi @ChetSocio is your issue solved ?

ChetSocio commented 1 year ago

Yup i have decided not to use cloudflare images.