Skip to content

Commit

Permalink
refactor(test): add lint rule for messages starting with the component (
Browse files Browse the repository at this point in the history
#2045)

Signed-off-by: Ramkumar Chinchani <[email protected]>
Signed-off-by: Laurentiu Niculae <[email protected]>
Signed-off-by: Andrei Aaron <[email protected]>
  • Loading branch information
laurentiuNiculae authored Dec 8, 2023
1 parent 262a904 commit 79e1402
Show file tree
Hide file tree
Showing 81 changed files with 855 additions and 681 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/golangci-lint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,6 @@ jobs:
- name: Run linter from make target
run: |
make check
- name: Run log linter
run: |
make check-logs
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,10 @@ $(GOLINTER):
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(TOOLSDIR)/bin $(GOLINTER_VERSION)
$(GOLINTER) version

.PHONY: check-logs
check-logs:
@./scripts/check_logs.sh

.PHONY: check
check: $(if $(findstring ui,$(BUILD_LABELS)), ui)
check: ./golangcilint.yaml $(GOLINTER)
Expand Down
233 changes: 115 additions & 118 deletions errors/errors.go

Large diffs are not rendered by default.

52 changes: 27 additions & 25 deletions pkg/api/authn.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func (amw *AuthnMiddleware) sessionAuthn(ctlr *Controller, userAc *reqCtx.UserAc

groups, err := ctlr.MetaDB.GetUserGroups(request.Context())
if err != nil {
ctlr.Log.Err(err).Str("identity", identity).Msg("can not get user profile in DB")
ctlr.Log.Err(err).Str("identity", identity).Msg("failed to get user profile in DB")

return false, err
}
Expand Down Expand Up @@ -134,7 +134,7 @@ func (amw *AuthnMiddleware) basicAuthn(ctlr *Controller, userAc *reqCtx.UserAcce

// we have already populated the request context with userAc
if err := ctlr.MetaDB.SetUserGroups(request.Context(), groups); err != nil {
ctlr.Log.Error().Err(err).Str("identity", identity).Msg("couldn't update user profile")
ctlr.Log.Error().Err(err).Str("identity", identity).Msg("failed to update user profile")

return false, err
}
Expand Down Expand Up @@ -172,7 +172,7 @@ func (amw *AuthnMiddleware) basicAuthn(ctlr *Controller, userAc *reqCtx.UserAcce

// we have already populated the request context with userAc
if err := ctlr.MetaDB.SetUserGroups(request.Context(), groups); err != nil {
ctlr.Log.Error().Err(err).Str("identity", identity).Msg("couldn't update user profile")
ctlr.Log.Error().Err(err).Str("identity", identity).Msg("failed to update user profile")

return false, err
}
Expand All @@ -186,7 +186,7 @@ func (amw *AuthnMiddleware) basicAuthn(ctlr *Controller, userAc *reqCtx.UserAcce
apiKey := passphrase

if !strings.HasPrefix(apiKey, constants.APIKeysPrefix) {
ctlr.Log.Error().Msg("api token has invalid format")
ctlr.Log.Error().Msg("invalid api token format")

return false, nil
}
Expand All @@ -198,12 +198,12 @@ func (amw *AuthnMiddleware) basicAuthn(ctlr *Controller, userAc *reqCtx.UserAcce
storedIdentity, err := ctlr.MetaDB.GetUserAPIKeyInfo(hashedKey)
if err != nil {
if errors.Is(err, zerr.ErrUserAPIKeyNotFound) {
ctlr.Log.Info().Err(err).Msgf("can not find any user info for hashed key %s in DB", hashedKey)
ctlr.Log.Info().Err(err).Msgf("failed to find any user info for hashed key %s in DB", hashedKey)

return false, nil
}

ctlr.Log.Error().Err(err).Msgf("can not get user info for hashed key %s in DB", hashedKey)
ctlr.Log.Error().Err(err).Msgf("failed to get user info for hashed key %s in DB", hashedKey)

return false, err
}
Expand All @@ -215,7 +215,7 @@ func (amw *AuthnMiddleware) basicAuthn(ctlr *Controller, userAc *reqCtx.UserAcce
// check if api key expired
isExpired, err := ctlr.MetaDB.IsAPIKeyExpired(request.Context(), hashedKey)
if err != nil {
ctlr.Log.Err(err).Str("identity", identity).Msg("can not verify if api key expired")
ctlr.Log.Err(err).Str("identity", identity).Msg("failed to verify if api key expired")

return false, err
}
Expand All @@ -226,14 +226,14 @@ func (amw *AuthnMiddleware) basicAuthn(ctlr *Controller, userAc *reqCtx.UserAcce

err = ctlr.MetaDB.UpdateUserAPIKeyLastUsed(request.Context(), hashedKey)
if err != nil {
ctlr.Log.Err(err).Str("identity", identity).Msg("can not update user profile in DB")
ctlr.Log.Err(err).Str("identity", identity).Msg("failed to update user profile in DB")

return false, err
}

groups, err := ctlr.MetaDB.GetUserGroups(request.Context())
if err != nil {
ctlr.Log.Err(err).Str("identity", identity).Msg("can not get user's groups in DB")
ctlr.Log.Err(err).Str("identity", identity).Msg("failed to get user's groups in DB")

return false, err
}
Expand Down Expand Up @@ -376,7 +376,7 @@ func (amw *AuthnMiddleware) tryAuthnHandlers(ctlr *Controller) mux.MiddlewareFun
authenticated, err := amw.sessionAuthn(ctlr, userAc, response, request)
if err != nil {
if errors.Is(err, zerr.ErrUserDataNotFound) {
ctlr.Log.Err(err).Msg("can not find user profile in DB")
ctlr.Log.Err(err).Msg("failed to find user profile in DB")

authFail(response, request, ctlr.Config.HTTP.Realm, delay)
}
Expand Down Expand Up @@ -419,7 +419,7 @@ func bearerAuthHandler(ctlr *Controller) mux.MiddlewareFunc {
EmptyDefaultNamespace: true,
})
if err != nil {
ctlr.Log.Panic().Err(err).Msg("error creating bearer authorizer")
ctlr.Log.Panic().Err(err).Msg("failed to create bearer authorizer")
}

return func(next http.Handler) http.Handler {
Expand Down Expand Up @@ -452,7 +452,7 @@ func bearerAuthHandler(ctlr *Controller) mux.MiddlewareFunc {

permissions, err := authorizer.Authorize(header, action, name)
if err != nil {
ctlr.Log.Error().Err(err).Msg("issue parsing Authorization header")
ctlr.Log.Error().Err(err).Msg("failed to parse Authorization header")
response.Header().Set("Content-Type", "application/json")
zcommon.WriteJSON(response, http.StatusInternalServerError, apiErr.NewError(apiErr.UNSUPPORTED))

Expand Down Expand Up @@ -523,7 +523,7 @@ func (rh *RouteHandler) AuthURLHandler() http.HandlerFunc {

client, ok := rh.c.RelyingParties[provider]
if !ok {
rh.c.Log.Error().Msg("unrecognized openid provider")
rh.c.Log.Error().Msg("failed to authenticate due to unrecognized openid provider")

w.WriteHeader(http.StatusBadRequest)

Expand All @@ -547,7 +547,7 @@ func (rh *RouteHandler) AuthURLHandler() http.HandlerFunc {
// let the session set its own id
err := session.Save(r, w)
if err != nil {
rh.c.Log.Error().Err(err).Msg("unable to save http session")
rh.c.Log.Error().Err(err).Msg("failed to save http session")

w.WriteHeader(http.StatusInternalServerError)

Expand Down Expand Up @@ -720,7 +720,7 @@ func GetGithubUserInfo(ctx context.Context, client *github.Client, log log.Logge

userEmails, _, err := client.Users.ListEmails(ctx, nil)
if err != nil {
log.Error().Msg("couldn't set user record for empty email value")
log.Error().Msg("failed to set user record for empty email value")

return "", []string{}, err
}
Expand All @@ -737,7 +737,7 @@ func GetGithubUserInfo(ctx context.Context, client *github.Client, log log.Logge

orgs, _, err := client.Organizations.List(ctx, "", nil)
if err != nil {
log.Error().Msg("couldn't set user record for empty email value")
log.Error().Msg("failed to set user record for empty email value")

return "", []string{}, err
}
Expand All @@ -764,7 +764,7 @@ func saveUserLoggedSession(cookieStore sessions.Store, response http.ResponseWri
// let the session set its own id
err := session.Save(request, response)
if err != nil {
log.Error().Err(err).Str("identity", identity).Msg("unable to save http session")
log.Error().Err(err).Str("identity", identity).Msg("failed to save http session")

return err
}
Expand All @@ -790,13 +790,15 @@ func OAuth2Callback(ctlr *Controller, w http.ResponseWriter, r *http.Request, st

stateOrigin, ok := stateCookie.Values["state"].(string)
if !ok {
ctlr.Log.Error().Err(zerr.ErrInvalidStateCookie).Msg("openID: unable to get 'state' cookie from request")
ctlr.Log.Error().Err(zerr.ErrInvalidStateCookie).Str("component", "openID").
Msg(": failed to get 'state' cookie from request")

return "", zerr.ErrInvalidStateCookie
}

if stateOrigin != state {
ctlr.Log.Error().Err(zerr.ErrInvalidStateCookie).Msg("openID: 'state' cookie differs from the actual one")
ctlr.Log.Error().Err(zerr.ErrInvalidStateCookie).Str("component", "openID").
Msg(": 'state' cookie differs from the actual one")

return "", zerr.ErrInvalidStateCookie
}
Expand All @@ -813,7 +815,7 @@ func OAuth2Callback(ctlr *Controller, w http.ResponseWriter, r *http.Request, st
}

if err := ctlr.MetaDB.SetUserGroups(r.Context(), groups); err != nil {
ctlr.Log.Error().Err(err).Str("identity", email).Msg("couldn't update the user profile")
ctlr.Log.Error().Err(err).Str("identity", email).Msg("failed to update the user profile")

return "", err
}
Expand Down Expand Up @@ -841,7 +843,7 @@ func GetAuthUserFromRequestSession(cookieStore sessions.Store, request *http.Req
) (string, bool) {
session, err := cookieStore.Get(request, "session")
if err != nil {
log.Error().Err(err).Msg("can not decode existing session")
log.Error().Err(err).Msg("failed to decode existing session")
// expired cookie, no need to return err
return "", false
}
Expand All @@ -854,14 +856,14 @@ func GetAuthUserFromRequestSession(cookieStore sessions.Store, request *http.Req

authenticated := session.Values["authStatus"]
if authenticated != true {
log.Error().Msg("can not get `user` session value")
log.Error().Msg("failed to get `user` session value")

return "", false
}

identity, ok := session.Values["user"].(string)
if !ok {
log.Error().Msg("can not get `user` session value")
log.Error().Msg("failed to get `user` session value")

return "", false
}
Expand All @@ -873,7 +875,7 @@ func GenerateAPIKey(uuidGenerator guuid.Generator, log log.Logger,
) (string, string, error) {
apiKeyBase, err := uuidGenerator.NewV4()
if err != nil {
log.Error().Err(err).Msg("unable to generate uuid for api key base")
log.Error().Err(err).Msg("failed to generate uuid for api key base")

return "", "", err
}
Expand All @@ -883,7 +885,7 @@ func GenerateAPIKey(uuidGenerator guuid.Generator, log log.Logger,
// will be used for identifying a specific api key
apiKeyID, err := uuidGenerator.NewV4()
if err != nil {
log.Error().Err(err).Msg("unable to generate uuid for api key id")
log.Error().Err(err).Msg("failed to generate uuid for api key id")

return "", "", err
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/api/authn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func TestAPIKeys(t *testing.T) {
conf.Extensions.UI.Enable = &defaultVal

ctlr := api.NewController(conf)
ctlr.Log.Info().Int64("seedUser", seedUser).Int64("seedPass", seedPass).Msg("random seed for username & password")
ctlr.Log.Info().Int64("seedUser", seedUser).Int64("seedPass", seedPass).Msg("Random seed for username & password")
dir := t.TempDir()

ctlr.Config.Storage.RootDirectory = dir
Expand Down
2 changes: 1 addition & 1 deletion pkg/api/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ func (c *Controller) StartBackgroundTasks(reloadCtx context.Context) {
//nolint: contextcheck
syncOnDemand, err := ext.EnableSyncExtension(c.Config, c.MetaDB, c.StoreController, c.taskScheduler, c.Log)
if err != nil {
c.Log.Error().Err(err).Msg("unable to start sync extension")
c.Log.Error().Err(err).Msg("failed to start sync extension")
}

c.SyncOnDemand = syncOnDemand
Expand Down
2 changes: 1 addition & 1 deletion pkg/api/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8950,7 +8950,7 @@ func TestPeriodicGC(t *testing.T) {
So(err, ShouldBeNil)
So(string(data), ShouldContainSubstring,
"\"GC\":true,\"Commit\":false,\"GCDelay\":1000000000,\"GCInterval\":3600000000000")
So(string(data), ShouldContainSubstring, "failure walking storage root-dir") //nolint:lll
So(string(data), ShouldContainSubstring, "failed to walk storage root-dir") //nolint:lll
})
}

Expand Down
20 changes: 10 additions & 10 deletions pkg/api/ldap.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (lc *LDAPClient) Connect() error {
if !lc.UseSSL {
l, err = ldap.Dial("tcp", address)
if err != nil {
lc.Log.Error().Err(err).Str("address", address).Msg("non-TLS connection failed")
lc.Log.Error().Err(err).Str("address", address).Msg("failed to establish a TCP connection")

return err
}
Expand All @@ -68,7 +68,7 @@ func (lc *LDAPClient) Connect() error {
err = l.StartTLS(config)

if err != nil {
lc.Log.Error().Err(err).Str("address", address).Msg("TLS connection failed")
lc.Log.Error().Err(err).Str("address", address).Msg("failed to establish a TLS connection")

return err
}
Expand All @@ -85,7 +85,7 @@ func (lc *LDAPClient) Connect() error {
}
l, err = ldap.DialTLS("tcp", address, config)
if err != nil {
lc.Log.Error().Err(err).Str("address", address).Msg("TLS connection failed")
lc.Log.Error().Err(err).Str("address", address).Msg("failed to establish a TLS connection")

return err
}
Expand Down Expand Up @@ -143,7 +143,7 @@ func (lc *LDAPClient) Authenticate(username, password string) (bool, map[string]
if lc.BindPassword != "" {
err := lc.Conn.Bind(lc.BindDN, lc.BindPassword)
if err != nil {
lc.Log.Error().Err(err).Str("bindDN", lc.BindDN).Msg("bind failed")
lc.Log.Error().Err(err).Str("bindDN", lc.BindDN).Msg("failed to bind")
// clean up the cached conn, so we can retry
lc.Conn.Close()
lc.Conn = nil
Expand All @@ -153,7 +153,7 @@ func (lc *LDAPClient) Authenticate(username, password string) (bool, map[string]
} else {
err := lc.Conn.UnauthenticatedBind(lc.BindDN)
if err != nil {
lc.Log.Error().Err(err).Str("bindDN", lc.BindDN).Msg("bind failed")
lc.Log.Error().Err(err).Str("bindDN", lc.BindDN).Msg("failed to bind")
// clean up the cached conn, so we can retry
lc.Conn.Close()
lc.Conn = nil
Expand All @@ -167,7 +167,7 @@ func (lc *LDAPClient) Authenticate(username, password string) (bool, map[string]

// exhausted all retries?
if !connected {
lc.Log.Error().Err(errors.ErrLDAPBadConn).Msg("exhausted all retries")
lc.Log.Error().Err(errors.ErrLDAPBadConn).Msg("failed to authenticate, exhausted all retries")

return false, nil, nil, errors.ErrLDAPBadConn
}
Expand All @@ -194,23 +194,23 @@ func (lc *LDAPClient) Authenticate(username, password string) (bool, map[string]
if err != nil {
fmt.Printf("%v\n", err)
lc.Log.Error().Err(err).Str("bindDN", lc.BindDN).Str("username", username).
Str("baseDN", lc.Base).Msg("search failed")
Str("baseDN", lc.Base).Msg("failed to perform a search request")

return false, nil, nil, err
}

if len(search.Entries) < 1 {
err := errors.ErrBadUser
lc.Log.Error().Err(err).Str("bindDN", lc.BindDN).Str("username", username).
Str("baseDN", lc.Base).Msg("entries not found")
Str("baseDN", lc.Base).Msg("failed to find entry")

return false, nil, nil, err
}

if len(search.Entries) > 1 {
err := errors.ErrEntriesExceeded
lc.Log.Error().Err(err).Str("bindDN", lc.BindDN).Str("username", username).
Str("baseDN", lc.Base).Msg("too many entries")
Str("baseDN", lc.Base).Msg("failed to retrieve due to an excessive amount of entries")

return false, nil, nil, err
}
Expand All @@ -227,7 +227,7 @@ func (lc *LDAPClient) Authenticate(username, password string) (bool, map[string]
// Bind as the user to verify their password
err = lc.Conn.Bind(userDN, password)
if err != nil {
lc.Log.Error().Err(err).Str("bindDN", userDN).Msg("user bind failed")
lc.Log.Error().Err(err).Str("bindDN", userDN).Msg("failed to bind user")

return false, user, userGroups, err
}
Expand Down
Loading

0 comments on commit 79e1402

Please sign in to comment.