Add URL unescaping for file query parameter. (#414)

* Add URL unescaping for file query parameter.

* Fix go.mod declared package.

* Add the net/url dependency.

* Fix return values.

* Fix return values correctly.

* Fix call site.

* Update go.mod

---------

Co-authored-by: Tom <tomas@aparicio.me>
This commit is contained in:
Joshua Harrison
2023-11-28 10:36:37 -05:00
committed by GitHub
parent 0d241c8228
commit 6a405833b7
2 changed files with 22 additions and 7 deletions

View File

@@ -1,8 +1,10 @@
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"strings"
)
@@ -18,16 +20,24 @@ func NewFileSystemImageSource(config *SourceConfig) ImageSource {
}
func (s *FileSystemImageSource) Matches(r *http.Request) bool {
return r.Method == http.MethodGet && s.getFileParam(r) != ""
file, err := s.getFileParam(r)
if err != nil {
return false
}
return r.Method == http.MethodGet && file != ""
}
func (s *FileSystemImageSource) GetImage(r *http.Request) ([]byte, error) {
file := s.getFileParam(r)
file, err := s.getFileParam(r)
if err != nil {
return nil, err
}
if file == "" {
return nil, ErrMissingParamFile
}
file, err := s.buildPath(file)
file, err = s.buildPath(file)
if err != nil {
return nil, err
}
@@ -51,8 +61,13 @@ func (s *FileSystemImageSource) read(file string) ([]byte, error) {
return buf, nil
}
func (s *FileSystemImageSource) getFileParam(r *http.Request) string {
return r.URL.Query().Get("file")
func (s *FileSystemImageSource) getFileParam(r *http.Request) (string, error) {
unescaped, err := url.QueryUnescape(r.URL.Query().Get("file"))
if err != nil{
return "", fmt.Errorf("failed to unescape file param: %w", err)
}
return unescaped, nil
}
func init() {

View File

@@ -11,7 +11,7 @@ import (
func TestFileSystemImageSource(t *testing.T) {
var body []byte
var err error
const fixtureFile = "testdata/large.jpg"
const fixtureFile = "testdata/large image.jpg"
source := NewFileSystemImageSource(&SourceConfig{MountPath: "testdata"})
fakeHandler := func(w http.ResponseWriter, r *http.Request) {
@@ -27,7 +27,7 @@ func TestFileSystemImageSource(t *testing.T) {
}
file, _ := os.Open(fixtureFile)
r, _ := http.NewRequest(http.MethodGet, "http://foo/bar?file=large.jpg", file)
r, _ := http.NewRequest(http.MethodGet, "http://foo/bar?file=large%20image.jpg", file)
w := httptest.NewRecorder()
fakeHandler(w, r)