Skip to content

Commit

Permalink
Fix Sonar lints
Browse files Browse the repository at this point in the history
  • Loading branch information
fperot74 authored Apr 27, 2020
1 parent 3a38f0f commit 387e4f3
Show file tree
Hide file tree
Showing 17 changed files with 191 additions and 123 deletions.
2 changes: 1 addition & 1 deletion database/dbase.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ func (cfg *DbConfig) OpenDatabase() (sqltypes.CloudtrustDB, error) {
}
err = cfg.checkMigrationVersion(dbConn)
if err != nil {
dbConn.Close()
_ = dbConn.Close()
dbConn = nil
}
} else if cfg.ConnectionCheck {
Expand Down
2 changes: 1 addition & 1 deletion database/dbase_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func TestDbVersion(t *testing.T) {

var matchTests = map[string]bool{"0.9": false, "1.0": false, "1.1": true, "1.5": true, "2.0": true}
for k, v := range matchTests {
v2, err = newDbVersion(k)
v2, _ = newDbVersion(k)
assert.Equal(t, v, v2.matchesRequired(v1))
}
}
Expand Down
1 change: 1 addition & 0 deletions errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http"
)

// Constants for error messages
const (
MsgErrMissingParam = "missingParameter"

Expand Down
2 changes: 1 addition & 1 deletion http/accesslog_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func (h accessLogHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
}

defer func(begin time.Time) {
h.logger.Log("method", req.Method, "uri", uri, "status_code", writer.Status(), "size", writer.Size(), "time", time.Since(begin))
_ = h.logger.Log("method", req.Method, "uri", uri, "status_code", writer.Status(), "size", writer.Size(), "time", time.Since(begin))
}(time.Now())

h.handler.ServeHTTP(writer, req)
Expand Down
2 changes: 1 addition & 1 deletion http/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (

// MakeVersionHandler makes a HTTP handler that returns information about the version of the component.
func MakeVersionHandler(componentName, ComponentID, version, environment, gitCommit string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
var info = struct {
Name string `json:"name"`
ID string `json:"id"`
Expand Down
1 change: 1 addition & 0 deletions idgenerator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ func New(componentName, componentID string) IDGenerator {
}
}

// IDGenerator interface
type IDGenerator interface {
NextID() string
}
Expand Down
47 changes: 25 additions & 22 deletions log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import (

// Logger interface for logging with level
type Logger interface {
Debug(ctx context.Context, keyvals ...interface{}) error
Info(ctx context.Context, keyvals ...interface{}) error
Warn(ctx context.Context, keyvals ...interface{}) error
Error(ctx context.Context, keyvals ...interface{}) error
Debug(ctx context.Context, keyvals ...interface{})
Info(ctx context.Context, keyvals ...interface{})
Warn(ctx context.Context, keyvals ...interface{})
Error(ctx context.Context, keyvals ...interface{})
ToGoKitLogger() kit_log.Logger
}

Expand Down Expand Up @@ -67,47 +67,50 @@ func ConvertToLevel(strLevel string) (kit_level.Option, error) {
return level, nil
}

func (l *ctLogger) Debug(ctx context.Context, keyvals ...interface{}) error {
func (l *ctLogger) Debug(ctx context.Context, keyvals ...interface{}) {
keyvals = append(keyvals, extractInfoFromContext(ctx)...)
return kit_level.Debug(l.logger).Log(keyvals...)
_ = kit_level.Debug(l.logger).Log(keyvals...)
}

func (l *ctLogger) Info(ctx context.Context, keyvals ...interface{}) error {
func (l *ctLogger) Info(ctx context.Context, keyvals ...interface{}) {
keyvals = append(keyvals, extractInfoFromContext(ctx)...)
return kit_level.Info(l.logger).Log(keyvals...)
_ = kit_level.Info(l.logger).Log(keyvals...)
}

func (l *ctLogger) Warn(ctx context.Context, keyvals ...interface{}) error {
func (l *ctLogger) Warn(ctx context.Context, keyvals ...interface{}) {
keyvals = append(keyvals, extractInfoFromContext(ctx)...)
return kit_level.Warn(l.logger).Log(keyvals...)
_ = kit_level.Warn(l.logger).Log(keyvals...)
}

func (l *ctLogger) Error(ctx context.Context, keyvals ...interface{}) error {
func (l *ctLogger) Error(ctx context.Context, keyvals ...interface{}) {
keyvals = append(keyvals, extractInfoFromContext(ctx)...)
return kit_level.Error(l.logger).Log(keyvals...)
_ = kit_level.Error(l.logger).Log(keyvals...)
}

func (l *ctLogger) ToGoKitLogger() kit_log.Logger {
return l.logger
}

var (
contextInfo = map[string]cs.CtContext{
"user_id": cs.CtContextUserID,
"realm_id": cs.CtContextRealmID,
"corr_id": cs.CtContextCorrelationID,
}
)

func extractInfoFromContext(ctx context.Context) []interface{} {
var keyvals = []interface{}{}

if ctx == nil {
return keyvals
}

if ctx.Value(cs.CtContextUserID) != nil {
keyvals = append(keyvals, "user_id", ctx.Value(cs.CtContextUserID).(string))
}

if ctx.Value(cs.CtContextRealmID) != nil {
keyvals = append(keyvals, "realm_id", ctx.Value(cs.CtContextRealmID).(string))
}

if ctx.Value(cs.CtContextCorrelationID) != nil {
keyvals = append(keyvals, "corr_id", ctx.Value(cs.CtContextCorrelationID).(string))
for k, v := range contextInfo {
var value = ctx.Value(v)
if value != nil {
keyvals = append(keyvals, k, value.(string))
}
}

return keyvals
Expand Down
41 changes: 41 additions & 0 deletions log/log_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package log

import (
"context"
"testing"

cs "github.com/cloudtrust/common-service"
"github.com/stretchr/testify/assert"
)

func TestExtractInfoFromContext(t *testing.T) {
t.Run("Nil context", func(t *testing.T) {
assert.Len(t, extractInfoFromContext(nil), 0)
})

var ctx = context.TODO()
t.Run("Empty context", func(t *testing.T) {
assert.Len(t, extractInfoFromContext(ctx), 0)
})

ctx = context.WithValue(ctx, cs.CtContextAccessToken, "the-access-token")

t.Run("Added AccessToken", func(t *testing.T) {
assert.Len(t, extractInfoFromContext(ctx), 0)
})

ctx = context.WithValue(ctx, cs.CtContextUserID, "the-user-id")
t.Run("Added UserID", func(t *testing.T) {
assert.Len(t, extractInfoFromContext(ctx), 1*2)
})

ctx = context.WithValue(ctx, cs.CtContextRealmID, "the-realm-id")
t.Run("Added RealmID", func(t *testing.T) {
assert.Len(t, extractInfoFromContext(ctx), 2*2)
})

ctx = context.WithValue(ctx, cs.CtContextCorrelationID, "the-correlation-id")
t.Run("Added CorrelationID", func(t *testing.T) {
assert.Len(t, extractInfoFromContext(ctx), 3*2)
})
}
24 changes: 19 additions & 5 deletions log/nop_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,22 @@ type nopLogger struct{}
// NewNopLogger returns a logger that doesn't do anything.
func NewNopLogger() Logger { return &nopLogger{} }

func (*nopLogger) Debug(context.Context, ...interface{}) error { return nil }
func (*nopLogger) Info(context.Context, ...interface{}) error { return nil }
func (*nopLogger) Warn(context.Context, ...interface{}) error { return nil }
func (*nopLogger) Error(context.Context, ...interface{}) error { return nil }
func (*nopLogger) ToGoKitLogger() kit_log.Logger { return kit_log.NewNopLogger() }
func (*nopLogger) Debug(context.Context, ...interface{}) {
// Nothing to do in NopLogger
}

func (*nopLogger) Info(context.Context, ...interface{}) {
// Nothing to do in NopLogger
}

func (*nopLogger) Warn(context.Context, ...interface{}) {
// Nothing to do in NopLogger
}

func (*nopLogger) Error(context.Context, ...interface{}) {
// Nothing to do in NopLogger
}

func (*nopLogger) ToGoKitLogger() kit_log.Logger {
return kit_log.NewNopLogger()
}
26 changes: 19 additions & 7 deletions metrics/instrumenting.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ type influxMetrics struct {

// Close closes the influx client
func (m *influxMetrics) Close() {
m.influx.Close()
_ = m.influx.Close()
}

// NewCounter returns a go-kit Counter.
Expand Down Expand Up @@ -200,7 +200,9 @@ func (m *influxMetrics) Ping(timeout time.Duration) (time.Duration, string, erro
type NoopMetrics struct{}

// Close does nothing.
func (m *NoopMetrics) Close() {}
func (m *NoopMetrics) Close() {
// No operation
}

// NewCounter returns a Counter that does nothing.
func (m *NoopMetrics) NewCounter(name string) Counter { return &NoopCounter{} }
Expand All @@ -220,7 +222,9 @@ func (m *NoopMetrics) Stats(_ context.Context, name string, tags map[string]stri
//func (m *NoopMetrics) Write(bp influx.BatchPoints) error { return nil }

// WriteLoop does nothing.
func (m *NoopMetrics) WriteLoop(c <-chan time.Time) {}
func (m *NoopMetrics) WriteLoop(c <-chan time.Time) {
// No operation
}

// Ping does nothing.
func (m *NoopMetrics) Ping(timeout time.Duration) (time.Duration, string, error) {
Expand All @@ -234,7 +238,9 @@ type NoopCounter struct{}
func (c *NoopCounter) With(labelValues ...string) metrics.Counter { return c }

// Add does nothing.
func (c *NoopCounter) Add(delta float64) {}
func (c *NoopCounter) Add(delta float64) {
// No operation
}

// NoopGauge is a Gauge that does nothing.
type NoopGauge struct{}
Expand All @@ -243,10 +249,14 @@ type NoopGauge struct{}
func (g *NoopGauge) With(labelValues ...string) metrics.Gauge { return g }

// Set does nothing.
func (g *NoopGauge) Set(value float64) {}
func (g *NoopGauge) Set(value float64) {
// No operation
}

// Add does nothing.
func (g *NoopGauge) Add(delta float64) {}
func (g *NoopGauge) Add(delta float64) {
// No operation
}

// NoopHistogram is an Histogram that does nothing.
type NoopHistogram struct{}
Expand All @@ -255,4 +265,6 @@ type NoopHistogram struct{}
func (h *NoopHistogram) With(labelValues ...string) Histogram { return h }

// Observe does nothing.
func (h *NoopHistogram) Observe(value float64) {}
func (h *NoopHistogram) Observe(value float64) {
// No operation
}
24 changes: 12 additions & 12 deletions middleware/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func MakeHTTPBasicAuthenticationMW(passwordToMatch string, logger log.Logger) fu
var ctx = context.TODO()

if authorizationHeader == "" {
logger.Info(ctx, "Authorization Error", "Missing Authorization header")
logger.Info(ctx, "msg", "Authorization error: Missing Authorization header")
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrMissingParam+"."+errorhandler.AuthHeader), w)
return
}
Expand All @@ -35,7 +35,7 @@ func MakeHTTPBasicAuthenticationMW(passwordToMatch string, logger log.Logger) fu
var r = regexp.MustCompile(regexpBasicAuth)
var match = r.FindStringSubmatch(authorizationHeader)
if match == nil {
logger.Info(ctx, "Authorization Error", "Missing basic token")
logger.Info(ctx, "msg", "Authorization error: Missing basic token")
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrMissingParam+"."+errorhandler.BasicToken), w)
return
}
Expand All @@ -44,7 +44,7 @@ func MakeHTTPBasicAuthenticationMW(passwordToMatch string, logger log.Logger) fu
decodedToken, err := base64.StdEncoding.DecodeString(match[1])

if err != nil {
logger.Info(ctx, "Authorization Error", "Invalid base64 token")
logger.Info(ctx, "msg", "Authorization error: Invalid base64 token")
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrInvalidParam+"."+errorhandler.Token), w)
return
}
Expand All @@ -53,7 +53,7 @@ func MakeHTTPBasicAuthenticationMW(passwordToMatch string, logger log.Logger) fu
var tokenSubparts = strings.Split(string(decodedToken), ":")

if len(tokenSubparts) != 2 {
logger.Info(ctx, "Authorization Error", "Invalid token format (username:password)")
logger.Info(ctx, "msg", "Authorization error: Invalid token format (username:password)")
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrInvalidParam+"."+errorhandler.Token), w)
return
}
Expand All @@ -65,7 +65,7 @@ func MakeHTTPBasicAuthenticationMW(passwordToMatch string, logger log.Logger) fu

// Check password match
if password != passwordToMatch {
logger.Info(ctx, "Authorization Error", "Invalid password value")
logger.Info(ctx, "msg", "Authorization error: Invalid password value")
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrInvalidParam+"."+errorhandler.Token), w)
return
}
Expand Down Expand Up @@ -94,15 +94,15 @@ func MakeHTTPOIDCTokenValidationMW(keycloakClient KeycloakClient, audienceRequir
var ctx = context.TODO()

if authorizationHeader == "" {
logger.Info(ctx, "Authorization Error", "Missing Authorization header")
logger.Info(ctx, "msg", "Authorization error: Missing Authorization header")
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrMissingParam+"."+errorhandler.AuthHeader), w)
return
}

var r = regexp.MustCompile(`^[Bb]earer +([^ ]+)$`)
var match = r.FindStringSubmatch(authorizationHeader)
if match == nil {
logger.Info(ctx, "Authorization Error", "Missing bearer token")
logger.Info(ctx, "msg", "Authorization error: Missing bearer token")
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrMissingParam+"."+errorhandler.BearerToken), w)
return
}
Expand All @@ -112,7 +112,7 @@ func MakeHTTPOIDCTokenValidationMW(keycloakClient KeycloakClient, audienceRequir

payload, _, err := jwt.Parse(accessToken)
if err != nil {
logger.Info(ctx, "Authorization Error", err)
logger.Info(ctx, "msg", "Authorization error", "err", err)
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrInvalidParam+"."+errorhandler.Token), w)
return
}
Expand All @@ -134,7 +134,7 @@ func MakeHTTPOIDCTokenValidationMW(keycloakClient KeycloakClient, audienceRequir
groups = extractGroups(jot.Groups)

if !assertMatchingAudience(jot.Audience, audienceRequired) {
logger.Info(ctx, "Authorization Error", "Incorrect audience")
logger.Info(ctx, "msg", "Authorization error: Incorrect audience")
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrInvalidParam+"."+errorhandler.Token), w)
return
}
Expand All @@ -153,12 +153,12 @@ func MakeHTTPOIDCTokenValidationMW(keycloakClient KeycloakClient, audienceRequir
groups = extractGroups(jot.Groups)

if jot.Audience != audienceRequired {
logger.Info(ctx, "Authorization Error", "Incorrect audience")
logger.Info(ctx, "msg", "Authorization error: Incorrect audience")
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrInvalidParam+"."+errorhandler.Token), w)
return
}
} else {
logger.Info(ctx, "Authorization Error", err)
logger.Info(ctx, "msg", "Authorization error", "err", err)
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrInvalidParam+"."+errorhandler.Token), w)
return
}
Expand All @@ -172,7 +172,7 @@ func MakeHTTPOIDCTokenValidationMW(keycloakClient KeycloakClient, audienceRequir
ctx = context.WithValue(ctx, cs.CtContextIssuerDomain, issuerDomain)

if err = keycloakClient.VerifyToken(ctx, realm, accessToken); err != nil {
logger.Info(ctx, "Authorization Error", err)
logger.Info(ctx, "msg", "Authorization error", "err", err)
httpErrorHandler(ctx, http.StatusForbidden, errors.New(errorhandler.MsgErrInvalidParam+"."+errorhandler.Token), w)
return
}
Expand Down
Loading

0 comments on commit 387e4f3

Please sign in to comment.