Correcting comments, casing and constant use

This commit is contained in:
Mark van der Velden 2018-12-30 10:03:22 +01:00
parent bab8a729fc
commit a299f70f89
No known key found for this signature in database
GPG Key ID: C3DE78B7CDE2A243
6 changed files with 64 additions and 64 deletions

View File

@ -23,18 +23,18 @@ const (
)
var (
ErrNotFound = NewError("Not found", NotFound)
ErrInvalidApiKey = NewError("Invalid or missing API key", Unauthorized)
ErrMethodNotAllowed = NewError("Method not allowed", NotAllowed)
ErrUnsupportedMedia = NewError("Unsupported media type", Unsupported)
ErrOutputFormat = NewError("Unsupported output image format", BadRequest)
ErrEmptyBody = NewError("Empty image", BadRequest)
ErrMissingParamFile = NewError("Missing required param: file", BadRequest)
ErrInvalidFilePath = NewError("Invalid file path", BadRequest)
ErrInvalidImageURL = NewError("Invalid image URL", BadRequest)
ErrMissingImageSource = NewError("Cannot process the image due to missing or invalid params", BadRequest)
ErrNotImplemented = NewError("Not implemented endpoint", NotImplemented)
ErrInvalidURLSignature = NewError("Invalid URL signature", BadRequest)
ErrNotFound = NewError("not found", NotFound)
ErrInvalidAPIKey = NewError("invalid or missing API key", Unauthorized)
ErrMethodNotAllowed = NewError("method not allowed", NotAllowed)
ErrUnsupportedMedia = NewError("unsupported media type", Unsupported)
ErrOutputFormat = NewError("unsupported output image format", BadRequest)
ErrEmptyBody = NewError("empty image", BadRequest)
ErrMissingParamFile = NewError("missing required param: file", BadRequest)
ErrInvalidFilePath = NewError("invalid file path", BadRequest)
ErrInvalidImageURL = NewError("invalid image URL", BadRequest)
ErrMissingImageSource = NewError("cannot process the image due to missing or invalid params", BadRequest)
ErrNotImplemented = NewError("not implemented endpoint", NotImplemented)
ErrInvalidURLSignature = NewError("invalid URL signature", BadRequest)
ErrURLSignatureMismatch = NewError("URL signature mismatch", Forbidden)
)

8
log.go
View File

@ -10,7 +10,7 @@ import (
const formatPattern = "%s - - [%s] \"%s\" %d %d %.4f\n"
// LogRecords implements a Apache-compatible HTTP logging
// LogRecord implements an Apache-compatible HTTP logging
type LogRecord struct {
http.ResponseWriter
status int
@ -36,7 +36,7 @@ func (r *LogRecord) Write(p []byte) (int, error) {
return written, err
}
// WriteHeader
// WriteHeader calls ResponseWriter.WriteHeader() and sets the status code
func (r *LogRecord) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
@ -48,12 +48,12 @@ type LogHandler struct {
io io.Writer
}
// Creates a new logger
// NewLog creates a new logger
func NewLog(handler http.Handler, io io.Writer) http.Handler {
return &LogHandler{handler, io}
}
// Implementes the required method as standard HTTP handler, serving the request.
// Implements the required method as standard HTTP handler, serving the request.
func (h *LogHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
clientIP := r.RemoteAddr
if colon := strings.LastIndex(clientIP, ":"); colon != -1 {

View File

@ -121,7 +121,7 @@ func authorizeClient(next http.Handler, o ServerOptions) http.Handler {
}
if key != o.APIKey {
ErrorReply(r, w, ErrInvalidApiKey, o)
ErrorReply(r, w, ErrInvalidAPIKey, o)
return
}

View File

@ -20,7 +20,7 @@ func NewBodyImageSource(config *SourceConfig) ImageSource {
}
func (s *BodyImageSource) Matches(r *http.Request) bool {
return r.Method == "POST" || r.Method == "PUT"
return r.Method == http.MethodPost || r.Method == http.MethodPut
}
func (s *BodyImageSource) GetImage(r *http.Request) ([]byte, error) {
@ -40,7 +40,7 @@ func readFormBody(r *http.Request) ([]byte, error) {
return nil, err
}
file, _, err := r.FormFile("file")
file, _, err := r.FormFile(formFieldName)
if err != nil {
return nil, err
}

View File

@ -9,42 +9,43 @@ import (
"strings"
)
const ImageSourceTypeHttp ImageSourceType = "http"
const ImageSourceTypeHTTP ImageSourceType = "http"
const URLQueryKey = "url"
type HttpImageSource struct {
type HTTPImageSource struct {
Config *SourceConfig
}
func NewHttpImageSource(config *SourceConfig) ImageSource {
return &HttpImageSource{config}
func NewHTTPImageSource(config *SourceConfig) ImageSource {
return &HTTPImageSource{config}
}
func (s *HttpImageSource) Matches(r *http.Request) bool {
return r.Method == "GET" && r.URL.Query().Get("url") != ""
func (s *HTTPImageSource) Matches(r *http.Request) bool {
return r.Method == http.MethodGet && r.URL.Query().Get(URLQueryKey) != ""
}
func (s *HttpImageSource) GetImage(req *http.Request) ([]byte, error) {
func (s *HTTPImageSource) GetImage(req *http.Request) ([]byte, error) {
url, err := parseURL(req)
if err != nil {
return nil, ErrInvalidImageURL
}
if shouldRestrictOrigin(url, s.Config.AllowedOrigins) {
return nil, fmt.Errorf("Not allowed remote URL origin: %s", url.Host)
return nil, fmt.Errorf("not allowed remote URL origin: %s", url.Host)
}
return s.fetchImage(url, req)
}
func (s *HttpImageSource) fetchImage(url *url.URL, ireq *http.Request) ([]byte, error) {
func (s *HTTPImageSource) fetchImage(url *url.URL, ireq *http.Request) ([]byte, error) {
// Check remote image size by fetching HTTP Headers
if s.Config.MaxAllowedSize > 0 {
req := newHTTPRequest(s, ireq, "HEAD", url)
req := newHTTPRequest(s, ireq, http.MethodHead, url)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("Error fetching image http headers: %v", err)
return nil, fmt.Errorf("error fetching image http headers: %v", err)
}
res.Body.Close()
if res.StatusCode < 200 && res.StatusCode > 206 {
return nil, fmt.Errorf("Error fetching image http headers: (status=%d) (url=%s)", res.StatusCode, req.URL.String())
return nil, fmt.Errorf("error fetching image http headers: (status=%d) (url=%s)", res.StatusCode, req.URL.String())
}
contentLength, _ := strconv.Atoi(res.Header.Get("Content-Length"))
@ -54,25 +55,25 @@ func (s *HttpImageSource) fetchImage(url *url.URL, ireq *http.Request) ([]byte,
}
// Perform the request using the default client
req := newHTTPRequest(s, ireq, "GET", url)
req := newHTTPRequest(s, ireq, http.MethodGet, url)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("Error downloading image: %v", err)
return nil, fmt.Errorf("error downloading image: %v", err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
return nil, fmt.Errorf("Error downloading image: (status=%d) (url=%s)", res.StatusCode, req.URL.String())
return nil, fmt.Errorf("error downloading image: (status=%d) (url=%s)", res.StatusCode, req.URL.String())
}
// Read the body
buf, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("Unable to create image from response body: %s (url=%s)", req.URL.String(), err)
return nil, fmt.Errorf("unable to create image from response body: %s (url=%s)", req.URL.String(), err)
}
return buf, nil
}
func (s *HttpImageSource) setAuthorizationHeader(req *http.Request, ireq *http.Request) {
func (s *HTTPImageSource) setAuthorizationHeader(req *http.Request, ireq *http.Request) {
auth := s.Config.Authorization
if auth == "" {
auth = ireq.Header.Get("X-Forward-Authorization")
@ -86,11 +87,10 @@ func (s *HttpImageSource) setAuthorizationHeader(req *http.Request, ireq *http.R
}
func parseURL(request *http.Request) (*url.URL, error) {
queryUrl := request.URL.Query().Get("url")
return url.Parse(queryUrl)
return url.Parse(request.URL.Query().Get(URLQueryKey))
}
func newHTTPRequest(s *HttpImageSource, ireq *http.Request, method string, url *url.URL) *http.Request {
func newHTTPRequest(s *HTTPImageSource, ireq *http.Request, method string, url *url.URL) *http.Request {
req, _ := http.NewRequest(method, url.String(), nil)
req.Header.Set("User-Agent", "imaginary/"+Version)
req.URL = url
@ -131,5 +131,5 @@ func shouldRestrictOrigin(url *url.URL, origins []*url.URL) bool {
}
func init() {
RegisterSource(ImageSourceTypeHttp, NewHttpImageSource)
RegisterSource(ImageSourceTypeHTTP, NewHTTPImageSource)
}

View File

@ -21,7 +21,7 @@ func TestHttpImageSource(t *testing.T) {
}))
defer ts.Close()
source := NewHttpImageSource(&SourceConfig{})
source := NewHTTPImageSource(&SourceConfig{})
fakeHandler := func(w http.ResponseWriter, r *http.Request) {
if !source.Matches(r) {
t.Fatal("Cannot match the request")
@ -52,7 +52,7 @@ func TestHttpImageSourceAllowedOrigin(t *testing.T) {
origin, _ := url.Parse(ts.URL)
origins := []*url.URL{origin}
source := NewHttpImageSource(&SourceConfig{AllowedOrigins: origins})
source := NewHTTPImageSource(&SourceConfig{AllowedOrigins: origins})
fakeHandler := func(w http.ResponseWriter, r *http.Request) {
if !source.Matches(r) {
@ -78,7 +78,7 @@ func TestHttpImageSourceAllowedOrigin(t *testing.T) {
func TestHttpImageSourceNotAllowedOrigin(t *testing.T) {
origin, _ := url.Parse("http://foo")
origins := []*url.URL{origin}
source := NewHttpImageSource(&SourceConfig{AllowedOrigins: origins})
source := NewHTTPImageSource(&SourceConfig{AllowedOrigins: origins})
fakeHandler := func(w http.ResponseWriter, r *http.Request) {
if !source.Matches(r) {
@ -90,7 +90,7 @@ func TestHttpImageSourceNotAllowedOrigin(t *testing.T) {
t.Fatal("Error cannot be empty")
}
if err.Error() != "Not allowed remote URL origin: bar.com" {
if err.Error() != "not allowed remote URL origin: bar.com" {
t.Fatalf("Invalid error message: %s", err)
}
}
@ -110,7 +110,7 @@ func TestHttpImageSourceForwardAuthHeader(t *testing.T) {
r, _ := http.NewRequest("GET", "http://foo/bar?url=http://bar.com", nil)
r.Header.Set(header, "foobar")
source := &HttpImageSource{&SourceConfig{AuthForwarding: true}}
source := &HTTPImageSource{&SourceConfig{AuthForwarding: true}}
if !source.Matches(r) {
t.Fatal("Cannot match the request")
}
@ -133,7 +133,7 @@ func TestHttpImageSourceError(t *testing.T) {
}))
defer ts.Close()
source := NewHttpImageSource(&SourceConfig{})
source := NewHTTPImageSource(&SourceConfig{})
fakeHandler := func(w http.ResponseWriter, r *http.Request) {
if !source.Matches(r) {
t.Fatal("Cannot match the request")
@ -160,7 +160,7 @@ func TestHttpImageSourceExceedsMaximumAllowedLength(t *testing.T) {
}))
defer ts.Close()
source := NewHttpImageSource(&SourceConfig{
source := NewHTTPImageSource(&SourceConfig{
MaxAllowedSize: 1023,
})
fakeHandler := func(w http.ResponseWriter, r *http.Request) {
@ -193,46 +193,46 @@ func TestShouldRestrictOrigin(t *testing.T) {
}
t.Run("Plain origin", func(t *testing.T) {
testUrl := createURL("https://example.org/logo.jpg", t)
testURL := createURL("https://example.org/logo.jpg", t)
if shouldRestrictOrigin(testUrl, plainOrigins) {
t.Errorf("Expected '%s' to be allowed with origins: %+v", testUrl, plainOrigins)
if shouldRestrictOrigin(testURL, plainOrigins) {
t.Errorf("Expected '%s' to be allowed with origins: %+v", testURL, plainOrigins)
}
})
t.Run("Wildcard origin, plain URL", func(t *testing.T) {
testUrl := createURL("https://example.org/logo.jpg", t)
testURL := createURL("https://example.org/logo.jpg", t)
if shouldRestrictOrigin(testUrl, wildCardOrigins) {
t.Errorf("Expected '%s' to be allowed with origins: %+v", testUrl, wildCardOrigins)
if shouldRestrictOrigin(testURL, wildCardOrigins) {
t.Errorf("Expected '%s' to be allowed with origins: %+v", testURL, wildCardOrigins)
}
})
t.Run("Wildcard origin, sub domain URL", func(t *testing.T) {
testUrl := createURL("https://node-42.example.org/logo.jpg", t)
testURL := createURL("https://node-42.example.org/logo.jpg", t)
if shouldRestrictOrigin(testUrl, wildCardOrigins) {
t.Errorf("Expected '%s' to be allowed with origins: %+v", testUrl, wildCardOrigins)
if shouldRestrictOrigin(testURL, wildCardOrigins) {
t.Errorf("Expected '%s' to be allowed with origins: %+v", testURL, wildCardOrigins)
}
})
t.Run("Wildcard origin, sub-sub domain URL", func(t *testing.T) {
testUrl := createURL("https://n.s3.bucket.on.aws.org/logo.jpg", t)
testURL := createURL("https://n.s3.bucket.on.aws.org/logo.jpg", t)
if shouldRestrictOrigin(testUrl, wildCardOrigins) {
t.Errorf("Expected '%s' to be allowed with origins: %+v", testUrl, wildCardOrigins)
if shouldRestrictOrigin(testURL, wildCardOrigins) {
t.Errorf("Expected '%s' to be allowed with origins: %+v", testURL, wildCardOrigins)
}
})
t.Run("Wildcard origin, incorrect domain URL", func(t *testing.T) {
testUrl := createURL("https://myexample.org/logo.jpg", t)
testURL := createURL("https://myexample.org/logo.jpg", t)
if !shouldRestrictOrigin(testUrl, plainOrigins) {
t.Errorf("Expected '%s' to not be allowed with plain origins: %+v", testUrl, plainOrigins)
if !shouldRestrictOrigin(testURL, plainOrigins) {
t.Errorf("Expected '%s' to not be allowed with plain origins: %+v", testURL, plainOrigins)
}
if !shouldRestrictOrigin(testUrl, wildCardOrigins) {
t.Errorf("Expected '%s' to not be allowed with wildcard origins: %+v", testUrl, wildCardOrigins)
if !shouldRestrictOrigin(testURL, wildCardOrigins) {
t.Errorf("Expected '%s' to not be allowed with wildcard origins: %+v", testURL, wildCardOrigins)
}
})
}