symfony: File constraint and application/json mime type not working together

Symfony version(s) affected: 3.4.42

Description

In my file upload form, I’m using a constraint similar to this for FileType form:

'constraints' => [
    new Constraints\File([
        'mimeTypes' => [
            'application/json'
        ],
    ])
]

Even if I upload a valid JSON file (with .json extension), Symfony complains that I uploaded text/plain. If I inspect the UploadedFile object, it has a correct mime type assigned. The validation fails because the FileValidator uses UploadedFile::getMimeType to validate the mime type, which in turn uses mime guesser which finally incorrectly guesses the mime type to be text/plain.

How to reproduce

Create a file upload form which limits the mime type to application/json and upload a valid JSON document.

About this issue

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

Most upvoted comments

I managed to reproduce this bug and it is indeed present. I’ve created a small application to test it: https://github.com/YaFou/symfony-symfony-37457. I will investigate on it now.

I think there is no bug here. Guessing naturally leads to false guesses, but at least they are safe (not trusting user input by default.)

Maybe we could guess first, then have some logic to validate that the submitted content-type is acceptable (by using the guess + some extra logic I suppose).

That’d be a new feature for sure (and I don’t know how this would be implemented exactly - to be investigated).

@YaFou Your fix potentially fixes this for Symfony (which is also fine and thank you for this!), but I reported it to PHP project because I managed to reproduce it without Symfony on latest PHP version.

@mamontovdmitriy Indeed. If I replace all empty arrays with some other value, it works fine. As soon as JSON file has an empty array ([]) or an empty object ({}), FileinfoMimeTypeGuesser fails to recognize it as application/json.