Skip to content

Commit 2d0b90c

Browse files
lunnylafriks
authored andcommitted
Fix upload file type check (#7890)
* fix upload file type check * make the function simple and added tests * Update comment as per @silverwind
1 parent a678ea4 commit 2d0b90c

File tree

2 files changed

+54
-10
lines changed

2 files changed

+54
-10
lines changed

modules/upload/filetype.go

+7-10
Original file line numberDiff line numberDiff line change
@@ -31,19 +31,16 @@ func (err ErrFileTypeForbidden) Error() string {
3131
func VerifyAllowedContentType(buf []byte, allowedTypes []string) error {
3232
fileType := http.DetectContentType(buf)
3333

34-
allowed := false
3534
for _, t := range allowedTypes {
3635
t := strings.Trim(t, " ")
37-
if t == "*/*" || t == fileType {
38-
allowed = true
39-
break
40-
}
41-
}
4236

43-
if !allowed {
44-
log.Info("Attachment with type %s blocked from upload", fileType)
45-
return ErrFileTypeForbidden{Type: fileType}
37+
if t == "*/*" || t == fileType ||
38+
// Allow directives after type, like 'text/plain; charset=utf-8'
39+
strings.HasPrefix(fileType, t+";") {
40+
return nil
41+
}
4642
}
4743

48-
return nil
44+
log.Info("Attachment with type %s blocked from upload", fileType)
45+
return ErrFileTypeForbidden{Type: fileType}
4946
}

modules/upload/filetype_test.go

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Copyright 2019 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package upload
6+
7+
import (
8+
"bytes"
9+
"compress/gzip"
10+
"testing"
11+
12+
"github.com/stretchr/testify/assert"
13+
)
14+
15+
func TestUpload(t *testing.T) {
16+
testContent := []byte(`This is a plain text file.`)
17+
var b bytes.Buffer
18+
w := gzip.NewWriter(&b)
19+
w.Write(testContent)
20+
w.Close()
21+
22+
kases := []struct {
23+
data []byte
24+
allowedTypes []string
25+
err error
26+
}{
27+
{
28+
data: testContent,
29+
allowedTypes: []string{"text/plain"},
30+
err: nil,
31+
},
32+
{
33+
data: testContent,
34+
allowedTypes: []string{"application/x-gzip"},
35+
err: ErrFileTypeForbidden{"text/plain; charset=utf-8"},
36+
},
37+
{
38+
data: b.Bytes(),
39+
allowedTypes: []string{"application/x-gzip"},
40+
err: nil,
41+
},
42+
}
43+
44+
for _, kase := range kases {
45+
assert.Equal(t, kase.err, VerifyAllowedContentType(kase.data, kase.allowedTypes))
46+
}
47+
}

0 commit comments

Comments
 (0)