Skip to content

Commit 2e8fc5b

Browse files
Replace regex usage for MIME parsing (#17831)
MIME types can have multiple optional parameters, eg: video/webm; codecs="w/e codec"; charset="binary" This commit replaces the usage of regex for getting the "type/subtype" with mime.ParseMediaType.
1 parent 789d251 commit 2e8fc5b

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

modules/upload/upload.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package upload
66

77
import (
8+
"mime"
89
"net/http"
910
"net/url"
1011
"path"
@@ -31,7 +32,6 @@ func (err ErrFileTypeForbidden) Error() string {
3132
return "This file extension or type is not allowed to be uploaded."
3233
}
3334

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

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

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

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

0 commit comments

Comments
 (0)