Skip to content

Commit

Permalink
style: Fix all linter errors
Browse files Browse the repository at this point in the history
  • Loading branch information
oxyno-zeta committed Sep 22, 2022
1 parent 0ebf411 commit 3ae37a6
Show file tree
Hide file tree
Showing 23 changed files with 64 additions and 51 deletions.
2 changes: 1 addition & 1 deletion pkg/s3-proxy/authx/authentication/basic-auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func (s *service) basicAuthMiddleware(res *config.Resource) func(http.Handler) h
}

// Check password
// nolint: forcetypeassert // Ignore this
//nolint: forcetypeassert // Ignore this
if cred.(*config.BasicAuthUserConfig).Password.Value == "" || cred.(*config.BasicAuthUserConfig).Password.Value != password {
// Create error
err := fmt.Errorf("username %s not authorized", username)
Expand Down
2 changes: 1 addition & 1 deletion pkg/s3-proxy/authx/authentication/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,5 +155,5 @@ func findResource(resL []*config.Resource, requestURI string, httpMethod string)
}

// Not found case
return nil, nil // nolint: nilnil // No need for a sentinel error in this case
return nil, nil //nolint: nilnil // No need for a sentinel error in this case
}
31 changes: 19 additions & 12 deletions pkg/s3-proxy/authx/authentication/oidc.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,10 @@ func (s *service) OIDCEndpoints(providerKey string, oidcCfg *config.OIDCAuthConf
})

mux.HandleFunc(mainRedirectURLCallbackPath, func(w http.ResponseWriter, r *http.Request) {
// Get context
ctx := r.Context()
// Get logger from request
logEntry := log.GetLoggerFromContext(r.Context())
logEntry := log.GetLoggerFromContext(ctx)

// ! In this particular case, no bucket request context because mounted in general and not per target

Expand All @@ -103,12 +105,12 @@ func (s *service) OIDCEndpoints(providerKey string, oidcCfg *config.OIDCAuthConf
}

// Split request query state to get redirect url and original state
split := strings.SplitN(reqQueryState, stateRedirectSeparator, 2) // nolint: gomnd // Ignoring because create by app just before
split := strings.SplitN(reqQueryState, stateRedirectSeparator, 2) //nolint: gomnd // Ignoring because create by app just before
// Prepare and affect values
reqState := split[0]
rdVal := ""
// Check if length is ok to include a redirect url
if len(split) == 2 { // nolint: gomnd // No constant for that
if len(split) == 2 { //nolint: gomnd // No constant for that
rdVal = split[1]
}

Expand Down Expand Up @@ -225,12 +227,14 @@ func (s *service) oidcAuthMiddleware(res *config.Resource) func(http.Handler) ht
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get oidc configuration
oidcAuthCfg := s.cfg.AuthProviders.OIDC[res.Provider]
// Get context
ctx := r.Context()
// Get logger from request
logEntry := log.GetLoggerFromContext(r.Context())
logEntry := log.GetLoggerFromContext(ctx)
// Get bucket request context from request
brctx := bucket.GetBucketRequestContextFromContext(r.Context())
brctx := bucket.GetBucketRequestContextFromContext(ctx)
// Get response handler
resHan := responsehandler.GetResponseHandlerFromContext(r.Context())
resHan := responsehandler.GetResponseHandlerFromContext(ctx)

// Get JWT Token from header or cookie
jwtContent, err := getJWTToken(logEntry, r, oidcAuthCfg.CookieName)
Expand Down Expand Up @@ -268,7 +272,7 @@ func (s *service) oidcAuthMiddleware(res *config.Resource) func(http.Handler) ht
}

// Parse JWT token
claims, err := parseAndValidateJWTToken(jwtContent, s.allVerifiers[res.Provider])
claims, err := parseAndValidateJWTToken(ctx, jwtContent, s.allVerifiers[res.Provider])
if err != nil {
logEntry.Error(err)
// Check if bucket request context doesn't exist to use local default files
Expand Down Expand Up @@ -311,9 +315,9 @@ func (s *service) oidcAuthMiddleware(res *config.Resource) func(http.Handler) ht
groups := make([]string, 0)
// Check if groups interface exists
if groupsInterface != nil {
// nolint: forcetypeassert // Ignore this
//nolint: forcetypeassert // Ignore this
for _, item := range groupsInterface.([]interface{}) {
// nolint: forcetypeassert // Ignore this
//nolint: forcetypeassert // Ignore this
groups = append(groups, item.(string))
}
}
Expand All @@ -336,7 +340,7 @@ func (s *service) oidcAuthMiddleware(res *config.Resource) func(http.Handler) ht
}

// Add user to request context by creating a new context
ctx := models.SetAuthenticatedUserInContext(r.Context(), ouser)
ctx = models.SetAuthenticatedUserInContext(ctx, ouser)
// Create new request with new context
r = r.WithContext(ctx)

Expand Down Expand Up @@ -366,8 +370,11 @@ func (s *service) oidcAuthMiddleware(res *config.Resource) func(http.Handler) ht
}
}

func parseAndValidateJWTToken(jwtContent string, verifier *oidc.IDTokenVerifier) (map[string]interface{}, error) {
ctx := context.Background()
func parseAndValidateJWTToken(
ctx context.Context,
jwtContent string,
verifier *oidc.IDTokenVerifier,
) (map[string]interface{}, error) {
// Create result map
var res map[string]interface{}

Expand Down
2 changes: 1 addition & 1 deletion pkg/s3-proxy/authx/authorization/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func Middleware(
// Check if case of opa server
if headerOIDCResource.AuthorizationOPAServer != nil {
var err error
authorized, err = isOPAServerAuthorized(r, user, headerOIDCResource)
authorized, err = isOPAServerAuthorized(r, user, headerOIDCResource) //nolint: contextcheck // False positive
if err != nil {
// Check if bucket request context doesn't exist to use local default files
if brctx == nil {
Expand Down
1 change: 1 addition & 0 deletions pkg/s3-proxy/bucket/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
var ErrRemovalFolder = errors.New("can't remove folder")

// Client represents a client in order to GET, PUT or DELETE file on a bucket with a html output.
//
//go:generate mockgen -destination=./mocks/mock_Client.go -package=mocks github.com/oxyno-zeta/s3-proxy/pkg/s3-proxy/bucket Client
type Client interface {
// Get allow to GET what's inside a request path
Expand Down
8 changes: 4 additions & 4 deletions pkg/s3-proxy/bucket/requestContext.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package bucket
import (
"context"
"fmt"
"io/ioutil"
"io"
"path"
"strings"

Expand Down Expand Up @@ -149,7 +149,7 @@ func (rctx *requestContext) Get(ctx context.Context, input *GetInput) {
// Check error
if err != nil {
// Check if error is a not found error
// nolint: gocritic // Don't want a switch
//nolint: gocritic // Don't want a switch
if errors.Is(err, s3client.ErrNotFound) {
// Test that redirect with trailing slash isn't asked and possible on this request
if rctx.targetCfg.Actions != nil && rctx.targetCfg.Actions.GET != nil &&
Expand Down Expand Up @@ -211,7 +211,7 @@ func (rctx *requestContext) manageGetFolder(ctx context.Context, key string, inp
// Check if error exists
if err != nil {
// Check if error is a not found error
// nolint: gocritic // Don't want a switch
//nolint: gocritic // Don't want a switch
if errors.Is(err, s3client.ErrNotFound) {
// Not found
resHan.NotFoundError(rctx.LoadFileContent)
Expand Down Expand Up @@ -540,7 +540,7 @@ func (rctx *requestContext) LoadFileContent(ctx context.Context, path string) (s
}

// Read all body
bb, err := ioutil.ReadAll(objOutput.Body)
bb, err := io.ReadAll(objOutput.Body)
// Check error
if err != nil {
return "", errors.WithStack(err)
Expand Down
2 changes: 1 addition & 1 deletion pkg/s3-proxy/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ const TemplateTargetKeyRewriteTargetType = "TEMPLATE"
var ErrMainBucketPathSupportNotValid = errors.New("main bucket path support option can be enabled only when only one bucket is configured")

// TemplateErrLoadingEnvCredentialEmpty Template Error when Loading Environment variable Credentials.
var TemplateErrLoadingEnvCredentialEmpty = "error loading credentials, environment variable %s is empty" // nolint: gosec // No credentials here, false positive
var TemplateErrLoadingEnvCredentialEmpty = "error loading credentials, environment variable %s is empty" //nolint: gosec // No credentials here, false positive

const oidcLoginPathTemplate = "/auth/%s"
const oidcCallbackPathTemplate = "/auth/%s/callback"
Expand Down
1 change: 1 addition & 0 deletions pkg/s3-proxy/config/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package config
import "github.com/oxyno-zeta/s3-proxy/pkg/s3-proxy/log"

// Manager
//
//go:generate mockgen -destination=./mocks/mock_Manager.go -package=mocks github.com/oxyno-zeta/s3-proxy/pkg/s3-proxy/config Manager
type Manager interface {
// Load configuration
Expand Down
9 changes: 4 additions & 5 deletions pkg/s3-proxy/config/managercontext.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package config

import (
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
Expand Down Expand Up @@ -39,7 +38,7 @@ func (ctx *managercontext) AddOnChangeHook(hook func()) {

func (ctx *managercontext) Load() error {
// List files
files, err := ioutil.ReadDir(mainConfigFolderPath)
files, err := os.ReadDir(mainConfigFolderPath)
if err != nil {
return errors.WithStack(err)
}
Expand Down Expand Up @@ -192,10 +191,10 @@ func (ctx *managercontext) loadDefaultConfigurationValues(vip *viper.Viper) {
vip.SetDefault("templates.delete.status", DefaultTemplateStatusNoContent)
}

func generateViperInstances(files []os.FileInfo) []*viper.Viper {
func generateViperInstances(files []os.DirEntry) []*viper.Viper {
list := make([]*viper.Viper, 0)
// Loop over static files to create viper instance for them
funk.ForEach(files, func(file os.FileInfo) {
funk.ForEach(files, func(file os.DirEntry) {
filename := file.Name()
// Create config file name
cfgFileName := strings.TrimSuffix(filename, path.Ext(filename))
Expand Down Expand Up @@ -529,7 +528,7 @@ func loadWebhookCfgCredentials(cfgList []*WebhookConfig) ([]*CredentialConfig, e
func loadCredential(credCfg *CredentialConfig) error {
if credCfg.Path != "" {
// Secret file
databytes, err := ioutil.ReadFile(credCfg.Path)
databytes, err := os.ReadFile(credCfg.Path)
if err != nil {
return errors.WithStack(err)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/s3-proxy/log/http-middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func (l *StructuredLoggerEntry) Write(status, bytes int, header http.Header, ela
l.Logger = l.Logger.WithFields(logrus.Fields{
"resp_status": status,
"resp_bytes_length": bytes,
"resp_elapsed_ms": float64(elapsed.Nanoseconds()) / 1000000.0, // nolint: gomnd // No constant for that
"resp_elapsed_ms": float64(elapsed.Nanoseconds()) / 1000000.0, //nolint: gomnd // No constant for that
})
logFunc := l.Logger.Infoln
// Check status code for warn logger
Expand Down
4 changes: 2 additions & 2 deletions pkg/s3-proxy/log/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,13 @@ func (ll *loggerIns) addPotentialWithError(elem interface{}) logrus.FieldLogger
}

// Check if error is matching stack trace interface
// nolint: errorlint // Ignore this because the aim is to catch stack trace error at first level
//nolint: errorlint // Ignore this because the aim is to catch stack trace error at first level
if err2, ok := err.(stackTracer); ok {
addStackTrace(err2)
}

// Check if error cause is matching stack trace interface
// nolint: errorlint // Ignore this because the aim is to catch stack trace error at first level
//nolint: errorlint // Ignore this because the aim is to catch stack trace error at first level
if err2, ok := errors.Cause(err).(stackTracer); ok {
addStackTrace(err2)
}
Expand Down
1 change: 1 addition & 0 deletions pkg/s3-proxy/metrics/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package metrics
import "net/http"

// Client Client metrics interface.
//
//go:generate mockgen -destination=./mocks/mock_Client.go -package=mocks github.com/oxyno-zeta/s3-proxy/pkg/s3-proxy/metrics Client
type Client interface {
// Will return a middleware to instrument http routers.
Expand Down
1 change: 1 addition & 0 deletions pkg/s3-proxy/response-handler/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ type DeleteInput struct {
}

// ResponseHandler will handle responses.
//
//go:generate mockgen -destination=./mocks/mock_ResponseHandler.go -package=mocks github.com/oxyno-zeta/s3-proxy/pkg/s3-proxy/response-handler ResponseHandler
type ResponseHandler interface {
// TargetList will answer for the target list response.
Expand Down
2 changes: 1 addition & 1 deletion pkg/s3-proxy/response-handler/contextkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ var responseHandlerCtxKey = &contextKey{name: "ResponseHandlerCtxKey"}

// GetResponseHandlerFromContext will return the response handler object from context.
func GetResponseHandlerFromContext(ctx context.Context) ResponseHandler {
// nolint: forcetypeassert // Ignore this
//nolint: forcetypeassert // Ignore this
return ctx.Value(responseHandlerCtxKey).(ResponseHandler)
}

Expand Down
7 changes: 4 additions & 3 deletions pkg/s3-proxy/response-handler/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ func determineHTTPStatus(obj *StreamInput) int {
func totalFileSizeEqualToContentRange(obj *StreamInput) bool {
totalSizeIsEqualToContentRange := false
// Calculate total file size
totalSize, err := strconv.ParseInt(getFileSizeAsString(obj), 10, 64) // nolint: gomnd // Ignoring because copied from other source
totalSize, err := strconv.ParseInt(getFileSizeAsString(obj), 10, 64) //nolint: gomnd // Ignoring because copied from other source
if err == nil {
if totalSize == (obj.ContentLength) {
totalSizeIsEqualToContentRange = true
Expand All @@ -141,7 +141,8 @@ func totalFileSizeEqualToContentRange(obj *StreamInput) bool {
return totalSizeIsEqualToContentRange
}

/**
/*
*
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
*/
func getFileSizeAsString(obj *StreamInput) string {
Expand All @@ -160,7 +161,7 @@ func setStrHeader(w http.ResponseWriter, key string, value string) {

func setIntHeader(w http.ResponseWriter, key string, value int64) {
if value > 0 {
w.Header().Add(key, strconv.FormatInt(value, 10)) // nolint: gomnd // Ignoring because copied from other source
w.Header().Add(key, strconv.FormatInt(value, 10)) //nolint: gomnd // Ignoring because copied from other source
}
}

Expand Down
2 changes: 2 additions & 0 deletions pkg/s3-proxy/s3client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
)

// Manager S3 client manager.
//
//go:generate mockgen -destination=./mocks/mock_Manager.go -package=mocks github.com/oxyno-zeta/s3-proxy/pkg/s3-proxy/s3client Manager
type Manager interface {
// GetClientForTarget will return a S3 client for a target.
Expand All @@ -21,6 +22,7 @@ type Manager interface {
}

// Client S3 Context interface.
//
//go:generate mockgen -destination=./mocks/mock_Client.go -package=mocks github.com/oxyno-zeta/s3-proxy/pkg/s3-proxy/s3client Client
type Client interface {
// ListFilesAndDirectories will list files and directories in S3.
Expand Down
8 changes: 4 additions & 4 deletions pkg/s3-proxy/s3client/s3Context.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func (s3ctx *s3Context) ListFilesAndDirectories(ctx context.Context, key string)
}

// Concat folders and files
// nolint:gocritic // Ignoring this: appendAssign: append result not assigned to the same slice
//nolint:gocritic // Ignoring this: appendAssign: append result not assigned to the same slice
all := append(folders, files...)

// Create info
Expand Down Expand Up @@ -193,11 +193,11 @@ func (s3ctx *s3Context) GetObject(ctx context.Context, input *GetInput) (*GetOut
// Check if error exists
if err != nil {
// Try to cast error into an AWS Error if possible
// nolint: errorlint // Cast
//nolint: errorlint // Cast
aerr, ok := err.(awserr.Error)
if ok {
// Check if it is a not found case
// nolint: gocritic // Because don't want to write a switch for the moment
//nolint: gocritic // Because don't want to write a switch for the moment
if aerr.Code() == s3.ErrCodeNoSuchKey {
return nil, nil, ErrNotFound
} else if aerr.Code() == "NotModified" {
Expand Down Expand Up @@ -348,7 +348,7 @@ func (s3ctx *s3Context) HeadObject(ctx context.Context, key string) (*HeadOutput
// Test error
if err != nil {
// Try to cast error into an AWS Error if possible
// nolint: errorlint // Cast
//nolint: errorlint // Cast
aerr, ok := err.(awserr.Error)
if ok {
// Issue not fixed: https://github.com/aws/aws-sdk-go/issues/1208
Expand Down
6 changes: 3 additions & 3 deletions pkg/s3-proxy/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ func (svr *Server) generateRouter() (http.Handler, error) {
resHan := responsehandler.GetResponseHandlerFromContext(req.Context())

// Get request path
requestPath := chi.URLParam(req, "*")
requestPath := chi.URLParam(req, "*") //nolint: contextcheck // False positive

// Unescape it
// Found a bug where sometimes the request path isn't unescaped
Expand Down Expand Up @@ -374,7 +374,7 @@ func (svr *Server) generateRouter() (http.Handler, error) {
resHan := responsehandler.GetResponseHandlerFromContext(req.Context())

// Get request path
requestPath := chi.URLParam(req, "*")
requestPath := chi.URLParam(req, "*") //nolint: contextcheck // False positive
// Unescape it
// Found a bug where sometimes the request path isn't unescaped
requestPath, err := url.PathUnescape(requestPath)
Expand Down Expand Up @@ -429,7 +429,7 @@ func (svr *Server) generateRouter() (http.Handler, error) {
// Get response handler
resHan := responsehandler.GetResponseHandlerFromContext(req.Context())
// Get request path
requestPath := chi.URLParam(req, "*")
requestPath := chi.URLParam(req, "*") //nolint: contextcheck // False positive
// Unescape it
// Found a bug where sometimes the request path isn't unescaped
requestPath, err := url.PathUnescape(requestPath)
Expand Down
5 changes: 2 additions & 3 deletions pkg/s3-proxy/server/server_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -4316,7 +4315,7 @@ func TestOIDCAuthentication(t *testing.T) {
return
}

bodyBytes, err := ioutil.ReadAll(resp.Body)
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
t.Error(err)
return
Expand Down Expand Up @@ -4356,7 +4355,7 @@ func TestOIDCAuthentication(t *testing.T) {
assert.Equal(t, tt.expectedResponsePath, resp.Request.URL.Path)

if tt.expectedBody != "" {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
bodyBytes, _ := io.ReadAll(resp.Body)
body := string(bodyBytes)
assert.Equal(t, tt.expectedBody, body)
}
Expand Down
Loading

0 comments on commit 3ae37a6

Please sign in to comment.