Skip to content

Commit 45b1c83

Browse files
authored
feat: check screenshot image mimetype and extension (#491)
1 parent 3da2dc0 commit 45b1c83

3 files changed

Lines changed: 49 additions & 6 deletions

File tree

pkg/analysis/passes/screenshots/screenshots.go

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"encoding/json"
66
"fmt"
7+
"mime"
78
"net/http"
89
"os"
910
"path/filepath"
@@ -124,15 +125,30 @@ func validateImage(imgPath string) error {
124125
mimeType = svgImage
125126
}
126127

128+
found := false
127129
for _, accepted := range acceptedImageTypes {
128130
if accepted == mimeType {
129-
return nil
131+
found = true
132+
break
130133
}
131134
}
132135

133-
return fmt.Errorf(
134-
"invalid screenshot image: %q. Accepted image types: %q",
135-
imgPath,
136-
acceptedImageTypes,
137-
)
136+
if !found {
137+
return fmt.Errorf(
138+
"invalid screenshot image: %q. Accepted image types: %q",
139+
imgPath,
140+
acceptedImageTypes,
141+
)
142+
}
143+
144+
ext := filepath.Ext(imgPath)
145+
expectedMimeType := mime.TypeByExtension(ext)
146+
if expectedMimeType != mimeType {
147+
return fmt.Errorf(
148+
"screenshot image has extension mismatch: %q has extension %q but content is %s",
149+
imgPath, ext, mimeType,
150+
)
151+
}
152+
153+
return nil
138154
}

pkg/analysis/passes/screenshots/screenshots_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,33 @@ func TestNoScreenshots(t *testing.T) {
6767
require.Equal(t, interceptor.Diagnostics[0].Title, "plugin.json: should include screenshots for the Plugin catalog")
6868
}
6969

70+
func TestMimeTypeExtMismatch(t *testing.T) {
71+
var interceptor testpassinterceptor.TestPassInterceptor
72+
const pluginJsonContent = `{
73+
"name": "my plugin name",
74+
"info": {
75+
"screenshots": [{
76+
"path": "testdata/screenshot2.png",
77+
"name": "screenshot2"
78+
}]
79+
}
80+
}`
81+
pass := &analysis.Pass{
82+
RootDir: filepath.Join("./"),
83+
ResultOf: map[*analysis.Analyzer]interface{}{
84+
metadata.Analyzer: []byte(pluginJsonContent),
85+
archive.Analyzer: filepath.Join("."),
86+
metadatavalid.Analyzer: nil,
87+
},
88+
Report: interceptor.ReportInterceptor(),
89+
}
90+
91+
_, err := Analyzer.Run(pass)
92+
require.NoError(t, err)
93+
require.Len(t, interceptor.Diagnostics, 1)
94+
require.Equal(t, `screenshot image has extension mismatch: "testdata/screenshot2.png" has extension ".png" but content is image/jpeg`, interceptor.Diagnostics[0].Title)
95+
}
96+
7097
func TestEmptyInvalidScreenshotPath(t *testing.T) {
7198
var interceptor testpassinterceptor.TestPassInterceptor
7299
const pluginJsonContent = `{
128 KB
Loading

0 commit comments

Comments
 (0)