Skip to content

Commit

Permalink
feat: validate mimetypes (#461)
Browse files Browse the repository at this point in the history
* feat: validate mimetypes

* fix: validate mimeType when uploading images
  • Loading branch information
Birkbjo authored Apr 15, 2021
1 parent 1c90182 commit 0e8fba3
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
3 changes: 2 additions & 1 deletion server/src/routes/v1/apps/handlers/uploadImageToApp.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ const {
getCurrentUserFromRequest,
currentUserIsManager,
} = require('../../../../security')

const { addAppMedia, getOrganisationAppsByUserId } = require('../../../../data')
const { validateImageMetadata } = require('../../../../utils/validateMime')

module.exports = {
method: 'POST',
Expand Down Expand Up @@ -60,6 +60,7 @@ module.exports = {

const imageFile = request.payload.file
const imageFileMetadata = imageFile.hapi
validateImageMetadata(request.server.mime, imageFileMetadata)

const trx = await knex.transaction()

Expand Down
37 changes: 37 additions & 0 deletions server/src/utils/validateMime.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const Boom = require('@hapi/boom')
const Joi = require('@hapi/joi')
const Path = require('path')

const allowedImageMimeTypes = ['image/jpeg', 'image/png', 'image/svg+xml']
const imageMetadataSchema = Joi.object({
headers: Joi.object({
'content-type': Joi.string().valid(...allowedImageMimeTypes),
}).unknown(),
filename: Joi.string(),
}).unknown()

const validateImageMetadata = (mimos, imageMetadata) => {
Joi.assert(imageMetadata, imageMetadataSchema)
return validateExtensionForMimeType(
mimos,
imageMetadata.filename,
allowedImageMimeTypes
)
}

const validateExtensionForMimeType = (mimos, filePath, mimeTypes) => {
if (!Array.isArray(mimeTypes)) {
mimeTypes = [mimeTypes]
}
const ext = Path.extname(filePath).substring(1)
const mimeExtensions = mimeTypes.flatMap(t => mimos.type(t).extensions)
if (mimeExtensions.includes(ext)) {
return true
}
throw Boom.badRequest(`File extension must be one of [${mimeExtensions}]`)
}

module.exports = {
validateImageMetadata,
validateExtensionForMimeType,
}

0 comments on commit 0e8fba3

Please sign in to comment.