Skip to content

Replace regex usage for MIME parsing #17831

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 27, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions modules/upload/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package upload

import (
"mime"
"net/http"
"net/url"
"path"
Expand All @@ -31,7 +32,6 @@ func (err ErrFileTypeForbidden) Error() string {
return "This file extension or type is not allowed to be uploaded."
}

var mimeTypeSuffixRe = regexp.MustCompile(`;.*$`)
var wildcardTypeRe = regexp.MustCompile(`^[a-z]+/\*$`)

// Verify validates whether a file is allowed to be uploaded.
Expand All @@ -51,7 +51,11 @@ func Verify(buf []byte, fileName string, allowedTypesStr string) error {
}

fullMimeType := http.DetectContentType(buf)
mimeType := strings.TrimSpace(mimeTypeSuffixRe.ReplaceAllString(fullMimeType, ""))
mimeType, _, err := mime.ParseMediaType(fullMimeType)
if err != nil {
log.Warn("Detected attachment type could not be parsed %s", fullMimeType)
return ErrFileTypeForbidden{Type: fullMimeType}
}
extension := strings.ToLower(path.Ext(fileName))

// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Unique_file_type_specifiers
Expand Down