Chore: Disable default golangci-lint filter (#29751)

* Disable default golangci-lint filter

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>

* Chore: Fix linter warnings

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
This commit is contained in:
Arve Knudsen
2020-12-15 09:32:06 +01:00
committed by GitHub
parent 5d4910dd52
commit c2cad26ca9
76 changed files with 598 additions and 274 deletions

View File

@@ -19,10 +19,13 @@ func TestAlertingUsageStats(t *testing.T) {
ae.Bus.AddHandler(func(query *models.GetAllAlertsQuery) error {
var createFake = func(file string) *simplejson.Json {
// Ignore gosec warning G304 since it's a test
// nolint:gosec
content, err := ioutil.ReadFile(file)
require.NoError(t, err, "expected to be able to read file")
j, _ := simplejson.NewJson(content)
j, err := simplejson.NewJson(content)
require.NoError(t, err)
return j
}

View File

@@ -387,8 +387,10 @@ func (pn *PushoverNotifier) genPushoverBody(evalContext *alerting.EvalContext, m
if err != nil {
return nil, b, err
}
if err := w.Close(); err != nil {
return nil, b, err
}
w.Close()
headers := map[string]string{
"Content-Type": w.FormDataContentType(),
}

View File

@@ -170,6 +170,11 @@ func (tn *TelegramNotifier) buildMessageInlineImage(evalContext *alerting.EvalCo
func (tn *TelegramNotifier) generateTelegramCmd(message string, messageField string, apiAction string, extraConf func(writer *multipart.Writer)) (*models.SendWebhookSync, error) {
var body bytes.Buffer
w := multipart.NewWriter(&body)
defer func() {
if err := w.Close(); err != nil {
tn.log.Warn("Failed to close writer", "err", err)
}
}()
fw, err := w.CreateFormField("chat_id")
if err != nil {
@@ -189,7 +194,9 @@ func (tn *TelegramNotifier) generateTelegramCmd(message string, messageField str
extraConf(w)
w.Close()
if err := w.Close(); err != nil {
return nil, err
}
tn.log.Info("Sending telegram notification", "chat_id", tn.ChatID, "bot_token", tn.BotToken, "apiAction", apiAction)
url := fmt.Sprintf(telegramAPIURL, tn.BotToken, apiAction)

View File

@@ -65,7 +65,9 @@ func TestInitContextWithAuthProxy_CachedInvalidUserID(t *testing.T) {
Logger: log.New("Test"),
}
req.Header.Set(svc.Cfg.AuthProxyHeaderName, name)
key := fmt.Sprintf(authproxy.CachePrefix, authproxy.HashCacheKey(name))
h, err := authproxy.HashCacheKey(name)
require.NoError(t, err)
key := fmt.Sprintf(authproxy.CachePrefix, h)
t.Logf("Injecting stale user ID in cache with key %q", key)
err = svc.RemoteCache.Set(key, int64(33), 0)

View File

@@ -141,25 +141,29 @@ func (auth *AuthProxy) IsAllowedIP() error {
))
}
func HashCacheKey(key string) string {
func HashCacheKey(key string) (string, error) {
hasher := fnv.New128a()
// according to the documentation, Hash.Write cannot error, but linter is complaining
hasher.Write([]byte(key)) // nolint: errcheck
return hex.EncodeToString(hasher.Sum(nil))
if _, err := hasher.Write([]byte(key)); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}
// getKey forms a key for the cache based on the headers received as part of the authentication flow.
// Our configuration supports multiple headers. The main header contains the email or username.
// And the additional ones that allow us to specify extra attributes: Name, Email or Groups.
func (auth *AuthProxy) getKey() string {
func (auth *AuthProxy) getKey() (string, error) {
key := strings.TrimSpace(auth.header) // start the key with the main header
auth.headersIterator(func(_, header string) {
key = strings.Join([]string{key, header}, "-") // compose the key with any additional headers
})
hashedKey := HashCacheKey(key)
return fmt.Sprintf(CachePrefix, hashedKey)
hashedKey, err := HashCacheKey(key)
if err != nil {
return "", err
}
return fmt.Sprintf(CachePrefix, hashedKey), nil
}
// Login logs in user ID by whatever means possible.
@@ -194,7 +198,10 @@ func (auth *AuthProxy) Login(logger log.Logger, ignoreCache bool) (int64, error)
// GetUserViaCache gets user ID from cache.
func (auth *AuthProxy) GetUserViaCache(logger log.Logger) (int64, error) {
cacheKey := auth.getKey()
cacheKey, err := auth.getKey()
if err != nil {
return 0, err
}
logger.Debug("Getting user ID via auth cache", "cacheKey", cacheKey)
userID, err := auth.remoteCache.Get(cacheKey)
if err != nil {
@@ -208,7 +215,10 @@ func (auth *AuthProxy) GetUserViaCache(logger log.Logger) (int64, error) {
// RemoveUserFromCache removes user from cache.
func (auth *AuthProxy) RemoveUserFromCache(logger log.Logger) error {
cacheKey := auth.getKey()
cacheKey, err := auth.getKey()
if err != nil {
return err
}
logger.Debug("Removing user from auth cache", "cacheKey", cacheKey)
if err := auth.remoteCache.Delete(cacheKey); err != nil {
return err
@@ -318,18 +328,20 @@ func (auth *AuthProxy) GetSignedInUser(userID int64) (*models.SignedInUser, erro
// Remember user in cache
func (auth *AuthProxy) Remember(id int64) error {
key := auth.getKey()
key, err := auth.getKey()
if err != nil {
return err
}
// Check if user already in cache
userID, _ := auth.remoteCache.Get(key)
if userID != nil {
userID, err := auth.remoteCache.Get(key)
if err == nil && userID != nil {
return nil
}
expiration := time.Duration(auth.cfg.AuthProxySyncTTL) * time.Minute
err := auth.remoteCache.Set(key, id, expiration)
if err != nil {
if err := auth.remoteCache.Set(key, id, expiration); err != nil {
return err
}

View File

@@ -87,12 +87,16 @@ func TestMiddlewareContext(t *testing.T) {
t.Run("When the cache only contains the main header with a simple cache key", func(t *testing.T) {
const id int64 = 33
// Set cache key
key := fmt.Sprintf(CachePrefix, HashCacheKey(hdrName))
err := cache.Set(key, id, 0)
h, err := HashCacheKey(hdrName)
require.NoError(t, err)
key := fmt.Sprintf(CachePrefix, h)
err = cache.Set(key, id, 0)
require.NoError(t, err)
// Set up the middleware
auth := prepareMiddleware(t, cache, nil)
assert.Equal(t, key, auth.getKey())
gotKey, err := auth.getKey()
require.NoError(t, err)
assert.Equal(t, key, gotKey)
gotID, err := auth.Login(logger, false)
require.NoError(t, err)
@@ -104,15 +108,17 @@ func TestMiddlewareContext(t *testing.T) {
const id int64 = 33
const group = "grafana-core-team"
key := fmt.Sprintf(CachePrefix, HashCacheKey(hdrName+"-"+group))
err := cache.Set(key, id, 0)
h, err := HashCacheKey(hdrName + "-" + group)
require.NoError(t, err)
key := fmt.Sprintf(CachePrefix, h)
err = cache.Set(key, id, 0)
require.NoError(t, err)
auth := prepareMiddleware(t, cache, func(req *http.Request, cfg *setting.Cfg) {
req.Header.Set("X-WEBAUTH-GROUPS", group)
cfg.AuthProxyHeaders = map[string]string{"Groups": "X-WEBAUTH-GROUPS"}
})
assert.Equal(t, "auth-proxy-sync-ttl:14f69b7023baa0ac98c96b31cec07bc0", auth.getKey())
assert.Equal(t, "auth-proxy-sync-ttl:14f69b7023baa0ac98c96b31cec07bc0", key)
gotID, err := auth.Login(logger, false)
require.NoError(t, err)

View File

@@ -64,8 +64,12 @@ func TestTokenRotationAtEndOfRequest(t *testing.T) {
ctxHdlr.rotateEndOfRequestFunc(reqContext, uts, token)(reqContext.Resp)
foundLoginCookie := false
// nolint:bodyclose
resp := rr.Result()
defer resp.Body.Close()
t.Cleanup(func() {
err := resp.Body.Close()
assert.NoError(t, err)
})
for _, c := range resp.Cookies() {
if c.Name == "login_token" {
foundLoginCookie = true

View File

@@ -5,6 +5,7 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestReadingLDAPSettings(t *testing.T) {
@@ -14,9 +15,10 @@ func TestReadingLDAPSettings(t *testing.T) {
}
func TestReadingLDAPSettingsWithEnvVariable(t *testing.T) {
os.Setenv("ENV_PASSWORD", "MySecret")
err := os.Setenv("ENV_PASSWORD", "MySecret")
require.NoError(t, err)
config, err := readConfig("testdata/ldap.toml")
assert.Nil(t, err, "No error when reading ldap config")
require.NoError(t, err)
assert.EqualValues(t, "MySecret", config.Servers[0].BindPassword)
}

View File

@@ -76,8 +76,11 @@ func (ns *NotificationService) sendWebRequestSync(ctx context.Context, webhook *
if err != nil {
return err
}
defer resp.Body.Close()
defer func() {
if err := resp.Body.Close(); err != nil {
ns.log.Warn("Failed to close response body", "err", err)
}
}()
if resp.StatusCode/100 == 2 {
ns.log.Debug("Webhook succeeded", "url", webhook.Url, "statuscode", resp.Status)

View File

@@ -19,10 +19,14 @@ import (
func TestValues(t *testing.T) {
Convey("Values", t, func() {
os.Setenv("INT", "1")
os.Setenv("STRING", "test")
os.Setenv("EMPTYSTRING", "")
os.Setenv("BOOL", "true")
err := os.Setenv("INT", "1")
So(err, ShouldBeNil)
err = os.Setenv("STRING", "test")
So(err, ShouldBeNil)
err = os.Setenv("EMPTYSTRING", "")
So(err, ShouldBeNil)
err = os.Setenv("BOOL", "true")
So(err, ShouldBeNil)
Convey("IntValue", func() {
type Data struct {
@@ -240,10 +244,14 @@ func TestValues(t *testing.T) {
})
Reset(func() {
os.Unsetenv("INT")
os.Unsetenv("STRING")
os.Unsetenv("EMPTYSTRING")
os.Unsetenv("BOOL")
err := os.Unsetenv("INT")
So(err, ShouldBeNil)
err = os.Unsetenv("STRING")
So(err, ShouldBeNil)
err = os.Unsetenv("EMPTYSTRING")
So(err, ShouldBeNil)
err = os.Unsetenv("BOOL")
So(err, ShouldBeNil)
})
})
}

View File

@@ -77,7 +77,11 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string,
}
// save response to file
defer resp.Body.Close()
defer func() {
if err := resp.Body.Close(); err != nil {
rs.log.Warn("Failed to close response body", "err", err)
}
}()
// check for timeout first
if errors.Is(reqContext.Err(), context.DeadlineExceeded) {