diff --git a/.github/workflows/golangci-lint.yaml b/.github/workflows/golangci-lint.yaml new file mode 100644 index 000000000..72f10f87a --- /dev/null +++ b/.github/workflows/golangci-lint.yaml @@ -0,0 +1,38 @@ +name: golangci-lint + +on: + pull_request: + +permissions: + contents: read + +jobs: + golangci-lint: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Go + uses: actions/setup-go@v6 + with: + go-version-file: 'go.mod' + + - name: Install Ginkgo + run: go install github.com/onsi/ginkgo/v2/ginkgo + + - name: Install Mockery + run: go install github.com/vektra/mockery/v2@v2.53.5 + + - name: Install golangci-lint + run: make install-golangci-lint + + - name: Generate Mockery code + run: make mockery + + - name: Generate Gqlgen code + run: make gqlgen + + - name: Run golangci-lint + run: make lint diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..448c847cd --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,15 @@ +version: "2" +run: + modules-download-mode: readonly + allow-parallel-runners: true +linters: + disable-all: true + enable: + - govet + - staticcheck + - gocritic + - gosec + - errcheck + - unused + - unconvert + - goconst diff --git a/Makefile b/Makefile index e0b848d81..57442c1cf 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ ARCH := $(shell go env GOARCH) SHELL=/bin/bash MIGRATIONS_DIR=internal/database/mariadb/migrations/ -.PHONY: all test doc gqlgen mockery test-all test-e2e test-app test-db fmt compose-prepare compose-up compose-down compose-restart compose-build check-call-cached check-migration-files +.PHONY: all test doc gqlgen mockery test-all test-e2e test-app test-db fmt lint compose-prepare compose-up compose-down compose-restart compose-build check-call-cached check-migration-files # Source the .env file to use the env vars with make -include .env @@ -102,6 +102,12 @@ install-gofumpt: fmt: gofumpt -l -w . +install-golangci-lint: + go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.8.0 + +lint: + golangci-lint run + DOCKER_COMPOSE := docker-compose -f docker-compose.yaml DOCKER_COMPOSE_SERVICES := heureka-app heureka-db valkey compose-prepare: diff --git a/cmd/heureka/main.go b/cmd/heureka/main.go index e2fed2bd0..7b9ef6f01 100644 --- a/cmd/heureka/main.go +++ b/cmd/heureka/main.go @@ -14,16 +14,14 @@ import ( "github.com/sirupsen/logrus" ) -var mode string - func main() { - fmt.Println(util.HeurekaFiglet) + fmt.Print(util.HeurekaFiglet) var cfg util.Config log.InitLog() err := envconfig.Process("heureka", &cfg) if err != nil { - logrus.WithField("error", err).Fatal("Error while reading env config %s", "test") + logrus.WithField("error", err).Fatal(fmt.Sprintf("Error while reading env config %s", "test")) return } cfg.ConfigToConsole() diff --git a/internal/api/graphql/access/auth/noauth.go b/internal/api/graphql/access/auth/noauth.go index 18741de11..d345d6a84 100644 --- a/internal/api/graphql/access/auth/noauth.go +++ b/internal/api/graphql/access/auth/noauth.go @@ -10,10 +10,6 @@ import ( "github.com/sirupsen/logrus" ) -const ( - noAuthMethodName string = "NoAuthMethod" -) - type NoAuthMethod struct { logger *logrus.Logger authMethodName string @@ -25,5 +21,5 @@ func NewNoAuthMethod(l *logrus.Logger, authMethodName string, msg string) authMe } func (nam NoAuthMethod) Verify(*gin.Context) error { - return verifyError(nam.authMethodName, fmt.Errorf("Auth failed: %s", nam.msg)) + return verifyError(nam.authMethodName, fmt.Errorf("auth failed: %s", nam.msg)) } diff --git a/internal/api/graphql/access/auth/oidc.go b/internal/api/graphql/access/auth/oidc.go index 486781074..c9336ef26 100644 --- a/internal/api/graphql/access/auth/oidc.go +++ b/internal/api/graphql/access/auth/oidc.go @@ -82,7 +82,7 @@ func (oam OidcAuthMethod) Verify(c *gin.Context) error { var claims IDTokenClaims err = token.Claims(&claims) if err != nil { - return verifyError(oidcAuthMethodName, fmt.Errorf("Failed to parse token claims: %w", err)) + return verifyError(oidcAuthMethodName, fmt.Errorf("failed to parse token claims: %w", err)) } authctx.UserNameToContext(c, claims.Sub) diff --git a/internal/api/graphql/access/auth/token.go b/internal/api/graphql/access/auth/token.go index 7e255bbbc..fb967b358 100644 --- a/internal/api/graphql/access/auth/token.go +++ b/internal/api/graphql/access/auth/token.go @@ -49,7 +49,7 @@ func (tam TokenAuthMethod) Verify(c *gin.Context) error { return err } - authctx.UserNameToContext(c, claims.RegisteredClaims.Subject) + authctx.UserNameToContext(c, claims.Subject) return nil } @@ -59,10 +59,10 @@ func (tam TokenAuthMethod) parseTokenWithClaims(tokenString string) (*TokenClaim token, err := jwt.ParseWithClaims(tokenString, claims, tam.parse) if err != nil { tam.logger.Error("JWT parsing error: ", err) - err = verifyError(tokenAuthMethodName, fmt.Errorf("Token parsing error")) + err = verifyError(tokenAuthMethodName, fmt.Errorf("token parsing error")) } else if !token.Valid { tam.logger.Error("Invalid token") - err = verifyError(tokenAuthMethodName, fmt.Errorf("Invalid token")) + err = verifyError(tokenAuthMethodName, fmt.Errorf("invalid token")) } return claims, err } @@ -71,17 +71,17 @@ func (tam TokenAuthMethod) verifyTokenExpiration(tc *TokenClaims) error { var err error if tc.ExpiresAt == nil { tam.logger.Error("Missing ExpiresAt in token claims") - err = verifyError(tokenAuthMethodName, fmt.Errorf("Missing ExpiresAt in token claims")) + err = verifyError(tokenAuthMethodName, fmt.Errorf("missing ExpiresAt in token claims")) } else if tc.ExpiresAt.Before(time.Now()) { tam.logger.Warn("Expired token") - err = verifyError(tokenAuthMethodName, fmt.Errorf("Expired token")) + err = verifyError(tokenAuthMethodName, fmt.Errorf("expired token")) } return err } func (tam *TokenAuthMethod) parse(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("Invalid JWT parse method") + return nil, fmt.Errorf("invalid JWT parse method") } return tam.secret, nil } diff --git a/internal/api/graphql/access/auth/util.go b/internal/api/graphql/access/auth/util.go index da4d91848..33c98a931 100644 --- a/internal/api/graphql/access/auth/util.go +++ b/internal/api/graphql/access/auth/util.go @@ -40,10 +40,10 @@ func verifyError(methodName string, e error) error { func getAuthTokenFromHeader(header string, c *gin.Context) (string, error) { authHeader := c.GetHeader(header) if authHeader == "" { - return "", fmt.Errorf("No authorization header") + return "", fmt.Errorf("no authorization header") } if len(authHeader) < (len("Bearer ")+1) || !strings.Contains(authHeader, "Bearer ") { - return "", fmt.Errorf("Invalid authorization header") + return "", fmt.Errorf("invalid authorization header") } return strings.Split(authHeader, "Bearer ")[1], nil } diff --git a/internal/api/graphql/access/middleware/middleware.go b/internal/api/graphql/access/middleware/middleware.go index 1706a502c..46676f8ca 100644 --- a/internal/api/graphql/access/middleware/middleware.go +++ b/internal/api/graphql/access/middleware/middleware.go @@ -5,7 +5,7 @@ package middleware import ( "fmt" - "io/ioutil" + "io" "net/http" "reflect" @@ -14,6 +14,8 @@ import ( "github.com/cloudoperators/heureka/internal/util" + // nolint due to importing all functions from auth package + //nolint: staticcheck . "github.com/cloudoperators/heureka/internal/api/graphql/access/auth" authctx "github.com/cloudoperators/heureka/internal/api/graphql/access/context" ) @@ -57,20 +59,22 @@ func (a *Auth) Middleware() gin.HandlerFunc { return } authCtx.Next() - return } } func (a *Auth) appendInstance(am authMethod) { - if am != nil && !(reflect.ValueOf(am).Kind() == reflect.Ptr && reflect.ValueOf(am).IsNil()) { - a.chain = append(a.chain, am) + if am != nil { + v := reflect.ValueOf(am) + if v.Kind() != reflect.Ptr || !v.IsNil() { + a.chain = append(a.chain, am) + } } } func newLogger(enableLog bool) *logrus.Logger { l := logrus.New() if !enableLog { - l.SetOutput(ioutil.Discard) + l.SetOutput(io.Discard) } return l } diff --git a/internal/api/graphql/access/test/server.go b/internal/api/graphql/access/test/server.go index 53d0cf9df..c9b8c4244 100644 --- a/internal/api/graphql/access/test/server.go +++ b/internal/api/graphql/access/test/server.go @@ -6,7 +6,7 @@ package test import ( "context" "fmt" - "io/ioutil" + "io" "net/http" "time" @@ -36,7 +36,7 @@ func NewTestServer(auth *middleware.Auth, enableLog bool) *TestServer { port := util2.GetRandomFreePort() log := logrus.New() if !enableLog { - log.SetOutput(ioutil.Discard) + log.SetOutput(io.Discard) } return &TestServer{ port: port, @@ -57,6 +57,8 @@ func (ts *TestServer) StartInBackground() { ts.ctx, ts.cancel = context.WithCancel(context.Background()) + // nolint due to unset values for timeouts + //nolint:gosec ts.srv = &http.Server{Addr: fmt.Sprintf(":%s", ts.port), Handler: r} util2.FirstListenThenServe(ts.srv, ts.log) } diff --git a/internal/api/graphql/access/test/util.go b/internal/api/graphql/access/test/util.go index 9539cbafa..b3ec5288d 100644 --- a/internal/api/graphql/access/test/util.go +++ b/internal/api/graphql/access/test/util.go @@ -16,6 +16,8 @@ import ( "github.com/golang-jwt/jwt/v5" + // nolint due to importing all functions from gomega package + //nolint: staticcheck . "github.com/onsi/gomega" ) @@ -44,7 +46,7 @@ func unmarshalResponseData(resp *http.Response, respData interface{}) { func ExpectErrorMessage(resp *http.Response, expectedMsg string) { var respData struct { - Error string `json:"error" required:true` + Error string `json:"error"` } unmarshalResponseData(resp, &respData) Expect(respData.Error).To(Equal(expectedMsg)) @@ -52,7 +54,7 @@ func ExpectErrorMessage(resp *http.Response, expectedMsg string) { func ExpectRegexErrorMessage(resp *http.Response, expectedRegexMsg string, args ...interface{}) { var respData struct { - Error string `json:"error" required:true` + Error string `json:"error"` } unmarshalResponseData(resp, &respData) Expect(respData.Error).Should(MatchRegexp(expectedRegexMsg, args...)) diff --git a/internal/api/graphql/graph/baseResolver/component.go b/internal/api/graphql/graph/baseResolver/component.go index 9161ba217..73277cc57 100644 --- a/internal/api/graphql/graph/baseResolver/component.go +++ b/internal/api/graphql/graph/baseResolver/component.go @@ -46,7 +46,7 @@ func SingleComponentBaseResolver(app app.Heureka, ctx context.Context, parent *m return nil, nil } - var cr entity.ComponentResult = components.Elements[0] + cr := components.Elements[0] component := model.NewComponent(cr.Component) return &component, nil @@ -158,8 +158,7 @@ func ComponentIssueCountsBaseResolver(app app.Heureka, ctx context.Context, filt } } - switch parent.ParentName { - case model.ImageNodeName: + if parent.ParentName == model.ImageNodeName { componentId = []*int64{pid} } } diff --git a/internal/api/graphql/graph/baseResolver/component_instance.go b/internal/api/graphql/graph/baseResolver/component_instance.go index 8050e32af..275449741 100644 --- a/internal/api/graphql/graph/baseResolver/component_instance.go +++ b/internal/api/graphql/graph/baseResolver/component_instance.go @@ -5,6 +5,7 @@ package baseResolver import ( "context" + "fmt" "github.com/cloudoperators/heureka/internal/api/graphql/graph/model" "github.com/cloudoperators/heureka/internal/app" @@ -13,7 +14,7 @@ import ( "github.com/cloudoperators/heureka/internal/util" "github.com/samber/lo" "github.com/sirupsen/logrus" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" ) func SingleComponentInstanceBaseResolver(app app.Heureka, ctx context.Context, parent *model.NodeParent) (*model.ComponentInstance, error) { @@ -48,7 +49,7 @@ func SingleComponentInstanceBaseResolver(app app.Heureka, ctx context.Context, p return nil, nil } - var cir entity.ComponentInstanceResult = componentInstances.Elements[0] + cir := componentInstances.Elements[0] componentInstance := model.NewComponentInstance(cir.ComponentInstance) return &componentInstance, nil @@ -101,7 +102,7 @@ func ComponentInstanceBaseResolver(app app.Heureka, ctx context.Context, filter Project: filter.Project, Pod: filter.Pod, Container: filter.Container, - Type: lo.Map(filter.Type, func(item *model.ComponentInstanceTypes, _ int) *string { return pointer.String(item.String()) }), + Type: lo.Map(filter.Type, func(item *model.ComponentInstanceTypes, _ int) *string { return ptr.To(item.String()) }), IssueMatchId: imId, ServiceId: serviceId, ServiceCcrn: filter.ServiceCcrn, @@ -190,7 +191,7 @@ func ContextBaseResolver(app app.Heureka, ctx context.Context, filter *model.Com requestedFields := GetPreloads(ctx) logrus.WithFields(logrus.Fields{ "requestedFields": requestedFields, - }).Debug("Called ComponentInstanceFilterBaseResolver (%s)", filter) + }).Debug(fmt.Sprintf("Called ComponentInstanceFilterBaseResolver (%v)", filter)) if filter == nil { filter = &model.ComponentInstanceFilter{} @@ -210,7 +211,7 @@ func ContextBaseResolver(app app.Heureka, ctx context.Context, filter *model.Com Project: filter.Project, Pod: filter.Pod, Container: filter.Container, - Type: lo.Map(filter.Type, func(item *model.ComponentInstanceTypes, _ int) *string { return pointer.String(item.String()) }), + Type: lo.Map(filter.Type, func(item *model.ComponentInstanceTypes, _ int) *string { return ptr.To(item.String()) }), Context: contextFilters, Search: filter.Search, State: model.GetStateFilterType(filter.State), @@ -246,7 +247,7 @@ func ComponentInstanceFilterBaseResolver( requestedFields := GetPreloads(ctx) logrus.WithFields(logrus.Fields{ "requestedFields": requestedFields, - }).Debug("Called ComponentInstanceFilterBaseResolver (%s)", filterDisplay) + }).Debug(fmt.Sprintf("Called ComponentInstanceFilterBaseResolver (%v)", filterDisplay)) if filter == nil { filter = &model.ComponentInstanceFilter{} @@ -261,7 +262,7 @@ func ComponentInstanceFilterBaseResolver( Project: filter.Project, Pod: filter.Pod, Container: filter.Container, - Type: lo.Map(filter.Type, func(item *model.ComponentInstanceTypes, _ int) *string { return pointer.String(item.String()) }), + Type: lo.Map(filter.Type, func(item *model.ComponentInstanceTypes, _ int) *string { return ptr.To(item.String()) }), Search: filter.Search, State: model.GetStateFilterType(filter.State), } diff --git a/internal/api/graphql/graph/baseResolver/component_version.go b/internal/api/graphql/graph/baseResolver/component_version.go index 2ab7bae33..dad60dc5c 100644 --- a/internal/api/graphql/graph/baseResolver/component_version.go +++ b/internal/api/graphql/graph/baseResolver/component_version.go @@ -46,7 +46,7 @@ func SingleComponentVersionBaseResolver(app app.Heureka, ctx context.Context, pa return nil, nil } - var cvr entity.ComponentVersionResult = componentVersions.Elements[0] + cvr := componentVersions.Elements[0] componentVersion := model.NewComponentVersion(cvr.ComponentVersion) return &componentVersion, nil @@ -126,7 +126,7 @@ func ComponentVersionBaseResolver(app app.Heureka, ctx context.Context, filter * } componentVersions, err := app.ListComponentVersions(f, opt) - //@todo propper error handling + // @todo propper error handling if err != nil { return nil, NewResolverError("ComponentVersionBaseResolver", err.Error()) } diff --git a/internal/api/graphql/graph/baseResolver/custom_errors.go b/internal/api/graphql/graph/baseResolver/custom_errors.go index db492d8e9..bfcdc2138 100644 --- a/internal/api/graphql/graph/baseResolver/custom_errors.go +++ b/internal/api/graphql/graph/baseResolver/custom_errors.go @@ -154,11 +154,12 @@ func sanitizeErrorMessage(appErr *appErrors.Error) string { } case appErrors.InvalidArgument: - if appErr.Message != "" { + switch { + case appErr.Message != "": message = appErr.Message - } else if appErr.Entity != "" { + case appErr.Entity != "": message = "Invalid " + strings.ToLower(appErr.Entity) - } else { + default: message = "Invalid input" } diff --git a/internal/api/graphql/graph/baseResolver/image_version.go b/internal/api/graphql/graph/baseResolver/image_version.go index 971a7fe53..1207db72e 100644 --- a/internal/api/graphql/graph/baseResolver/image_version.go +++ b/internal/api/graphql/graph/baseResolver/image_version.go @@ -35,8 +35,7 @@ func ImageVersionBaseResolver(app app.Heureka, ctx context.Context, filter *mode return nil, NewResolverError("ImageVersionBaseResolver", "Bad Request - Error while parsing propagated ID") } - switch parent.ParentName { - case model.ImageNodeName: + if parent.ParentName == model.ImageNodeName { componentId = []*int64{pid} } } @@ -87,7 +86,7 @@ func ImageVersionBaseResolver(app app.Heureka, ctx context.Context, filter *mode if lo.Contains(requestedFields, "counts") { cvIds := lo.Map(componentVersions.Elements, func(e entity.ComponentVersionResult, _ int) *int64 { - return &e.ComponentVersion.Id + return &e.Id }) icFilter := &entity.IssueFilter{ diff --git a/internal/api/graphql/graph/baseResolver/issue.go b/internal/api/graphql/graph/baseResolver/issue.go index 8a09c0c2e..961017a6e 100644 --- a/internal/api/graphql/graph/baseResolver/issue.go +++ b/internal/api/graphql/graph/baseResolver/issue.go @@ -13,7 +13,7 @@ import ( "github.com/cloudoperators/heureka/internal/util" "github.com/samber/lo" "github.com/sirupsen/logrus" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" ) func GetIssueListOptions(requestedFields []string) *entity.IssueListOptions { @@ -56,7 +56,7 @@ func SingleIssueBaseResolver(app app.Heureka, ctx context.Context, parent *model return nil, nil } - var ir entity.IssueResult = issues.Elements[0] + ir := issues.Elements[0] issue := model.NewIssueWithAggregations(&ir) return &issue, nil @@ -107,14 +107,14 @@ func IssueBaseResolver(app app.Heureka, ctx context.Context, filter *model.Issue ActivityId: activityId, ComponentVersionId: cvId, PrimaryName: filter.PrimaryName, - Type: lo.Map(filter.IssueType, func(item *model.IssueTypes, _ int) *string { return pointer.String(item.String()) }), + Type: lo.Map(filter.IssueType, func(item *model.IssueTypes, _ int) *string { return ptr.To(item.String()) }), IssueRepositoryId: irId, Search: filter.Search, - IssueMatchStatus: nil, //@todo Implement - IssueMatchDiscoveryDate: nil, //@todo Implement - IssueMatchTargetRemediationDate: nil, //@todo Implement + IssueMatchStatus: nil, // @todo Implement + IssueMatchDiscoveryDate: nil, // @todo Implement + IssueMatchTargetRemediationDate: nil, // @todo Implement State: model.GetStateFilterType(filter.State), } @@ -195,12 +195,12 @@ func IssueNameBaseResolver(app app.Heureka, ctx context.Context, filter *model.I ServiceCCRN: filter.ServiceCcrn, PrimaryName: filter.PrimaryName, SupportGroupCCRN: filter.SupportGroupCcrn, - Type: lo.Map(filter.IssueType, func(item *model.IssueTypes, _ int) *string { return pointer.String(item.String()) }), + Type: lo.Map(filter.IssueType, func(item *model.IssueTypes, _ int) *string { return ptr.To(item.String()) }), IssueRepositoryId: irId, Search: filter.Search, - IssueMatchStatus: nil, //@todo Implement - IssueMatchDiscoveryDate: nil, //@todo Implement - IssueMatchTargetRemediationDate: nil, //@todo Implement + IssueMatchStatus: nil, // @todo Implement + IssueMatchDiscoveryDate: nil, // @todo Implement + IssueMatchTargetRemediationDate: nil, // @todo Implement State: model.GetStateFilterType(filter.State), } @@ -276,7 +276,7 @@ func IssueCountsBaseResolver(app app.Heureka, ctx context.Context, filter *model ServiceCCRN: filter.ServiceCcrn, SupportGroupCCRN: filter.SupportGroupCcrn, PrimaryName: filter.PrimaryName, - Type: lo.Map(filter.IssueType, func(item *model.IssueTypes, _ int) *string { return pointer.String(item.String()) }), + Type: lo.Map(filter.IssueType, func(item *model.IssueTypes, _ int) *string { return ptr.To(item.String()) }), Search: filter.Search, IssueRepositoryId: irIds, ComponentVersionId: cvIds, diff --git a/internal/api/graphql/graph/baseResolver/issue_match.go b/internal/api/graphql/graph/baseResolver/issue_match.go index 88eb4a993..3cc1a49f0 100644 --- a/internal/api/graphql/graph/baseResolver/issue_match.go +++ b/internal/api/graphql/graph/baseResolver/issue_match.go @@ -12,7 +12,7 @@ import ( "github.com/cloudoperators/heureka/internal/util" "github.com/samber/lo" "github.com/sirupsen/logrus" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" ) func SingleIssueMatchBaseResolver(app app.Heureka, ctx context.Context, parent *model.NodeParent) (*model.IssueMatch, error) { @@ -48,7 +48,7 @@ func SingleIssueMatchBaseResolver(app app.Heureka, ctx context.Context, parent * return nil, nil } - var imr entity.IssueMatchResult = issueMatches.Elements[0] + imr := issueMatches.Elements[0] issueMatch := model.NewIssueMatch(imr.IssueMatch) return &issueMatch, nil @@ -108,8 +108,8 @@ func IssueMatchBaseResolver(app app.Heureka, ctx context.Context, filter *model. Id: imIds, PaginatedX: entity.PaginatedX{First: first, After: after}, ServiceCCRN: filter.ServiceCcrn, - Status: lo.Map(filter.Status, func(item *model.IssueMatchStatusValues, _ int) *string { return pointer.String(item.String()) }), - SeverityValue: lo.Map(filter.Severity, func(item *model.SeverityValues, _ int) *string { return pointer.String(item.String()) }), + Status: lo.Map(filter.Status, func(item *model.IssueMatchStatusValues, _ int) *string { return ptr.To(item.String()) }), + SeverityValue: lo.Map(filter.Severity, func(item *model.SeverityValues, _ int) *string { return ptr.To(item.String()) }), SupportGroupCCRN: filter.SupportGroupCcrn, IssueId: issueId, EvidenceId: eId, @@ -118,7 +118,7 @@ func IssueMatchBaseResolver(app app.Heureka, ctx context.Context, filter *model. Search: filter.Search, ComponentCCRN: filter.ComponentCcrn, PrimaryName: filter.PrimaryName, - IssueType: lo.Map(filter.IssueType, func(item *model.IssueTypes, _ int) *string { return pointer.String(item.String()) }), + IssueType: lo.Map(filter.IssueType, func(item *model.IssueTypes, _ int) *string { return ptr.To(item.String()) }), ServiceOwnerUsername: filter.ServiceOwnerUsername, ServiceOwnerUniqueUserId: filter.ServiceOwnerUniqueUserID, State: model.GetStateFilterType(filter.State), diff --git a/internal/api/graphql/graph/baseResolver/issue_repository.go b/internal/api/graphql/graph/baseResolver/issue_repository.go index a48b6b6eb..3995c67ae 100644 --- a/internal/api/graphql/graph/baseResolver/issue_repository.go +++ b/internal/api/graphql/graph/baseResolver/issue_repository.go @@ -46,7 +46,7 @@ func SingleIssueRepositoryBaseResolver(app app.Heureka, ctx context.Context, par return nil, nil } - var irr entity.IssueRepositoryResult = issueRepositories.Elements[0] + irr := issueRepositories.Elements[0] issueRepository := model.NewIssueRepository(irr.IssueRepository) return &issueRepository, nil @@ -74,8 +74,7 @@ func IssueRepositoryBaseResolver(app app.Heureka, ctx context.Context, filter *m return nil, NewResolverError("IssueRepositoryBaseResolver", "Bad Request - Error while parsing propagated ID") } - switch parent.ParentName { - case model.ServiceNodeName: + if parent.ParentName == model.ServiceNodeName { serviceId = []*int64{pid} } } @@ -109,7 +108,7 @@ func IssueRepositoryBaseResolver(app app.Heureka, ctx context.Context, filter *m } if lo.Contains(requestedFields, "edges.priority") { - p := int(result.IssueRepositoryService.Priority) + p := int(result.Priority) edge.Priority = &p } diff --git a/internal/api/graphql/graph/baseResolver/issue_variant.go b/internal/api/graphql/graph/baseResolver/issue_variant.go index ac393acd5..09f62a3e0 100644 --- a/internal/api/graphql/graph/baseResolver/issue_variant.go +++ b/internal/api/graphql/graph/baseResolver/issue_variant.go @@ -45,7 +45,7 @@ func SingleIssueVariantBaseResolver(app app.Heureka, ctx context.Context, parent return nil, nil } - var ivr entity.IssueVariantResult = variants.Elements[0] + ivr := variants.Elements[0] variant := model.NewIssueVariant(ivr.IssueVariant) return &variant, nil @@ -147,8 +147,7 @@ func EffectiveIssueVariantBaseResolver(app app.Heureka, ctx context.Context, fil return nil, NewResolverError("EffectiveIssueVariantBaseResolver", "Bad Request - Error while parsing propagated ID") } - switch parent.ParentName { - case model.IssueMatchNodeName: + if parent.ParentName == model.IssueMatchNodeName { imId = []*int64{pid} } } diff --git a/internal/api/graphql/graph/baseResolver/remediation.go b/internal/api/graphql/graph/baseResolver/remediation.go index 76621b680..e503bc554 100644 --- a/internal/api/graphql/graph/baseResolver/remediation.go +++ b/internal/api/graphql/graph/baseResolver/remediation.go @@ -12,7 +12,7 @@ import ( appErrors "github.com/cloudoperators/heureka/internal/errors" "github.com/samber/lo" "github.com/sirupsen/logrus" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" ) func RemediationBaseResolver(app app.Heureka, ctx context.Context, filter *model.RemediationFilter, first *int, after *string, orderBy []*model.RemediationOrderBy, parent *model.NodeParent) (*model.RemediationConnection, error) { @@ -31,8 +31,7 @@ func RemediationBaseResolver(app app.Heureka, ctx context.Context, filter *model return nil, ToGraphQLError(appErrors.E(appErrors.Op("RemediationBaseResolver"), "Remediation", appErrors.InvalidArgument, "Error while parsing propagated ID")) } - switch parent.ParentName { - case model.ServiceNodeName: + if parent.ParentName == model.ServiceNodeName { serviceId = []*int64{pid} } } @@ -46,7 +45,7 @@ func RemediationBaseResolver(app app.Heureka, ctx context.Context, filter *model Service: filter.Service, Component: filter.Image, Issue: filter.Vulnerability, - Type: lo.Map(filter.Type, func(item *model.RemediationTypeValues, _ int) *string { return pointer.String(item.String()) }), + Type: lo.Map(filter.Type, func(item *model.RemediationTypeValues, _ int) *string { return ptr.To(item.String()) }), ServiceId: serviceId, State: model.GetStateFilterType(filter.State), Search: filter.Search, diff --git a/internal/api/graphql/graph/baseResolver/scannerrun.go b/internal/api/graphql/graph/baseResolver/scannerrun.go index 3cedde881..cfae94f8a 100644 --- a/internal/api/graphql/graph/baseResolver/scannerrun.go +++ b/internal/api/graphql/graph/baseResolver/scannerrun.go @@ -10,7 +10,7 @@ import ( "github.com/cloudoperators/heureka/internal/api/graphql/graph/model" "github.com/cloudoperators/heureka/internal/app" "github.com/cloudoperators/heureka/internal/entity" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" ) func ScannerRunTagFilterValues(app app.Heureka, ctx context.Context) ([]*string, error) { @@ -21,7 +21,7 @@ func ScannerRunTagFilterValues(app app.Heureka, ctx context.Context) ([]*string, res := make([]*string, len(tags)) for _, tag := range tags { - res = append(res, pointer.String(tag)) + res = append(res, ptr.To(tag)) } return res, nil @@ -70,7 +70,7 @@ func ScannerRuns(app app.Heureka, ctx context.Context, filter *model.ScannerRunF hasNext := false if first == nil { - first = pointer.Int(0) + first = ptr.To(0) } if totalCount > *first+int(*value) { @@ -78,7 +78,7 @@ func ScannerRuns(app app.Heureka, ctx context.Context, filter *model.ScannerRunF } if after == nil { - after = pointer.String("") + after = ptr.To("") } hasPrevious := len(*after) > 0 diff --git a/internal/api/graphql/graph/baseResolver/service.go b/internal/api/graphql/graph/baseResolver/service.go index 6581d127e..098db77c9 100644 --- a/internal/api/graphql/graph/baseResolver/service.go +++ b/internal/api/graphql/graph/baseResolver/service.go @@ -46,7 +46,7 @@ func SingleServiceBaseResolver(app app.Heureka, ctx context.Context, parent *mod return nil, nil } - var sr entity.ServiceResult = services.Elements[0] + sr := services.Elements[0] service := model.NewService(sr.Service) return &service, nil diff --git a/internal/api/graphql/graph/baseResolver/user.go b/internal/api/graphql/graph/baseResolver/user.go index b13796ad4..35069cf2b 100644 --- a/internal/api/graphql/graph/baseResolver/user.go +++ b/internal/api/graphql/graph/baseResolver/user.go @@ -46,7 +46,7 @@ func SingleUserBaseResolver(app app.Heureka, ctx context.Context, parent *model. return nil, nil } - var ur entity.UserResult = users.Elements[0] + ur := users.Elements[0] user := model.NewUser(ur.User) return &user, nil diff --git a/internal/api/graphql/graph/model/common.go b/internal/api/graphql/graph/model/common.go index 0606ea737..47e87f65b 100644 --- a/internal/api/graphql/graph/model/common.go +++ b/internal/api/graphql/graph/model/common.go @@ -5,6 +5,10 @@ package model import "fmt" +const ( + unknownType = "unknown" +) + type NodeName string func (e NodeName) String() string { @@ -60,7 +64,7 @@ func SeverityValue(s string) (SeverityValues, error) { case SeverityValuesCritical.String(): return SeverityValuesCritical, nil } - return SeverityValuesNone, fmt.Errorf("Invalid SeverityValues provided: %s", s) + return SeverityValuesNone, fmt.Errorf("invalid SeverityValues provided: %s", s) } func ComponentTypeValue(s string) (ComponentTypeValues, error) { @@ -72,7 +76,7 @@ func ComponentTypeValue(s string) (ComponentTypeValues, error) { case ComponentTypeValuesVirtualMachineImage.String(): return ComponentTypeValuesVirtualMachineImage, nil } - return "unknown", fmt.Errorf("Invalid ComponentTypeValues provided: %s", s) + return unknownType, fmt.Errorf("invalid ComponentTypeValues provided: %s", s) } func ComponentInstanceType(s string) (ComponentInstanceTypes, error) { @@ -102,5 +106,6 @@ func ComponentInstanceType(s string) (ComponentInstanceTypes, error) { case ComponentInstanceTypesProjectConfiguration.String(): return ComponentInstanceTypesProjectConfiguration, nil } - return "unknown", fmt.Errorf("Invalid ComponentInstanceType provided: %s", s) + + return unknownType, fmt.Errorf("invalid ComponentInstanceType provided: %s", s) } diff --git a/internal/api/graphql/graph/model/models.go b/internal/api/graphql/graph/model/models.go index d75d70163..5a92674db 100644 --- a/internal/api/graphql/graph/model/models.go +++ b/internal/api/graphql/graph/model/models.go @@ -80,20 +80,20 @@ func (od *OrderDirection) ToOrderDirectionEntity() entity.OrderDirection { func (sg *SupportGroupOrderBy) ToOrderEntity() entity.Order { var order entity.Order - switch *sg.By { - case SupportGroupOrderByFieldCcrn: + if *sg.By == SupportGroupOrderByFieldCcrn { order.By = entity.SupportGroupCcrn } + order.Direction = sg.Direction.ToOrderDirectionEntity() return order } func (cv *ComponentVersionOrderBy) ToOrderEntity() entity.Order { var order entity.Order - switch *cv.By { - case ComponentVersionOrderByFieldRepository: + if *cv.By == ComponentVersionOrderByFieldRepository { order.By = entity.ComponentVersionRepository } + order.Direction = cv.Direction.ToOrderDirectionEntity() return order } @@ -154,10 +154,10 @@ func (imo *IssueMatchOrderBy) ToOrderEntity() entity.Order { func (so *ServiceOrderBy) ToOrderEntity() entity.Order { var order entity.Order - switch *so.By { - case ServiceOrderByFieldCcrn: + if *so.By == ServiceOrderByFieldCcrn { order.By = entity.ServiceCcrn } + order.Direction = so.Direction.ToOrderDirectionEntity() return order } @@ -344,19 +344,19 @@ func NewIssueWithAggregations(issue *entity.IssueResult) Issue { if issue.IssueAggregations != nil { objectMetadata = IssueMetadata{ - ServiceCount: int(issue.IssueAggregations.AffectedServices), - ActivityCount: int(issue.IssueAggregations.Activities), + ServiceCount: int(issue.AffectedServices), + ActivityCount: int(issue.Activities), IssueMatchCount: int(issue.IssueAggregations.IssueMatches), - ComponentInstanceCount: int(issue.IssueAggregations.AffectedComponentInstances), + ComponentInstanceCount: int(issue.AffectedComponentInstances), ComponentVersionCount: int(issue.IssueAggregations.ComponentVersions), - EarliestDiscoveryDate: issue.IssueAggregations.EarliestDiscoveryDate.String(), - EarliestTargetRemediationDate: issue.IssueAggregations.EarliestTargetRemediationDate.String(), + EarliestDiscoveryDate: issue.EarliestDiscoveryDate.String(), + EarliestTargetRemediationDate: issue.EarliestTargetRemediationDate.String(), } } return Issue{ ID: fmt.Sprintf("%d", issue.Issue.Id), - PrimaryName: &issue.Issue.PrimaryName, + PrimaryName: &issue.PrimaryName, Type: &issueType, Description: &issue.Issue.Description, LastModified: &lastModified, @@ -567,8 +567,8 @@ func NewServiceWithAggregations(service *entity.ServiceResult) Service { if service.ServiceAggregations != nil { objectMetadata = ServiceMetadata{ - IssueMatchCount: int(service.ServiceAggregations.IssueMatches), - ComponentInstanceCount: int(service.ServiceAggregations.ComponentInstances), + IssueMatchCount: int(service.IssueMatches), + ComponentInstanceCount: int(service.ComponentInstances), } } @@ -785,17 +785,18 @@ func NewComponentInstanceEntity(componentInstance *ComponentInstanceInput) entit ciType = componentInstance.Type.String() } return entity.ComponentInstance{ - CCRN: rawCcrn, - Region: lo.FromPtr(componentInstance.Region), - Cluster: lo.FromPtr(componentInstance.Cluster), - Namespace: lo.FromPtr(componentInstance.Namespace), - Domain: lo.FromPtr(componentInstance.Domain), - Project: lo.FromPtr(componentInstance.Project), - Pod: lo.FromPtr(componentInstance.Pod), - Container: lo.FromPtr(componentInstance.Container), - Type: entity.NewComponentInstanceType(ciType), - Context: (*entity.Json)(&componentInstance.Context), - Count: int16(lo.FromPtr(componentInstance.Count)), + CCRN: rawCcrn, + Region: lo.FromPtr(componentInstance.Region), + Cluster: lo.FromPtr(componentInstance.Cluster), + Namespace: lo.FromPtr(componentInstance.Namespace), + Domain: lo.FromPtr(componentInstance.Domain), + Project: lo.FromPtr(componentInstance.Project), + Pod: lo.FromPtr(componentInstance.Pod), + Container: lo.FromPtr(componentInstance.Container), + Type: entity.NewComponentInstanceType(ciType), + Context: (*entity.Json)(&componentInstance.Context), + // nolint due to int16 won't overflow + Count: int16(lo.FromPtr(componentInstance.Count)), //nolint: gosec ComponentVersionId: componentVersionId, ServiceId: serviceId, ParentId: parentId, @@ -806,9 +807,10 @@ func GetStateFilterType(sf []StateFilter) []entity.StateFilterType { if len(sf) > 0 { s := make([]entity.StateFilterType, len(sf)) for i := range sf { - if sf[i] == StateFilterDeleted { + switch sf[i] { + case StateFilterDeleted: s[i] = entity.Deleted - } else if sf[i] == StateFilterActive { + case StateFilterActive: s[i] = entity.Active } } diff --git a/internal/api/graphql/graph/resolver/query.go b/internal/api/graphql/graph/resolver/query.go index f11dcfda9..65a6f2987 100644 --- a/internal/api/graphql/graph/resolver/query.go +++ b/internal/api/graphql/graph/resolver/query.go @@ -12,7 +12,7 @@ import ( "github.com/cloudoperators/heureka/internal/api/graphql/graph/baseResolver" "github.com/cloudoperators/heureka/internal/api/graphql/graph/model" "github.com/samber/lo" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" ) // SPDX-FileCopyrightText: 2025 SAP SE or an SAP affiliate company and Greenhouse contributors @@ -75,17 +75,17 @@ func (r *queryResolver) IssueMatchFilterValues(ctx context.Context) (*model.Issu Status: &model.FilterItem{ DisplayName: &baseResolver.FilterDisplayIssueMatchStatus, FilterName: &baseResolver.IssueMatchFilterStatus, - Values: lo.Map(model.AllIssueMatchStatusValuesOrdered, func(s model.IssueMatchStatusValues, _ int) *string { return pointer.String(s.String()) }), + Values: lo.Map(model.AllIssueMatchStatusValuesOrdered, func(s model.IssueMatchStatusValues, _ int) *string { return ptr.To(s.String()) }), }, IssueType: &model.FilterItem{ DisplayName: &baseResolver.FilterDisplayIssueType, FilterName: &baseResolver.IssueMatchFilterIssueType, - Values: lo.Map(model.AllIssueTypesOrdered, func(s model.IssueTypes, _ int) *string { return pointer.String(s.String()) }), + Values: lo.Map(model.AllIssueTypesOrdered, func(s model.IssueTypes, _ int) *string { return ptr.To(s.String()) }), }, Severity: &model.FilterItem{ DisplayName: &baseResolver.FilterDisplayIssueSeverity, FilterName: &baseResolver.IssueMatchFilterSeverity, - Values: lo.Map(model.AllSeverityValuesOrdered, func(s model.SeverityValues, _ int) *string { return pointer.String(s.String()) }), + Values: lo.Map(model.AllSeverityValuesOrdered, func(s model.SeverityValues, _ int) *string { return ptr.To(s.String()) }), }, }, nil } @@ -95,7 +95,7 @@ func (r *queryResolver) ComponentInstanceFilterValues(ctx context.Context) (*mod Type: &model.FilterItem{ DisplayName: &baseResolver.FilterDisplayComponentInstanceType, FilterName: &baseResolver.ComponentInstanceFilterType, - Values: lo.Map(model.AllComponentInstanceTypesOrdered, func(s model.ComponentInstanceTypes, _ int) *string { return pointer.String(s.String()) }), + Values: lo.Map(model.AllComponentInstanceTypesOrdered, func(s model.ComponentInstanceTypes, _ int) *string { return ptr.To(s.String()) }), }, }, nil } @@ -125,12 +125,13 @@ func (r *queryResolver) VulnerabilityFilterValues(ctx context.Context) (*model.V Severity: &model.FilterItem{ DisplayName: &baseResolver.FilterDisplayIssueSeverity, FilterName: &baseResolver.IssueMatchFilterSeverity, - Values: lo.Map(model.AllSeverityValuesOrdered, func(s model.SeverityValues, _ int) *string { return pointer.String(s.String()) }), + Values: lo.Map(model.AllSeverityValuesOrdered, func(s model.SeverityValues, _ int) *string { return ptr.To(s.String()) }), }, }, nil } func (r *queryResolver) Images(ctx context.Context, filter *model.ImageFilter, first *int, after *string) (*model.ImageConnection, error) { + //nolint:staticcheck ctx = context.WithValue(ctx, "serviceFilter", filter.Service) return baseResolver.ImageBaseResolver(r.App, ctx, filter, first, after) } diff --git a/internal/api/graphql/graph/scalar/json.go b/internal/api/graphql/graph/scalar/json.go index 45461bdc9..42408a6a7 100644 --- a/internal/api/graphql/graph/scalar/json.go +++ b/internal/api/graphql/graph/scalar/json.go @@ -16,17 +16,25 @@ type Json map[string]any func (m Json) MarshalGQL(w io.Writer) { if m == nil { - w.Write([]byte("null")) + if _, err := w.Write([]byte("null")); err != nil { + panic(fmt.Errorf("failed to write null value: %w", err)) + } + return } data, err := json.Marshal(map[string]any(m)) if err != nil { - w.Write([]byte("null")) + if _, err := w.Write([]byte("null")); err != nil { + panic(fmt.Errorf("failed to write null value: %w", err)) + } + return } - w.Write(data) + if _, err := w.Write(data); err != nil { + panic(fmt.Errorf("failed to write data: %w", err)) + } } func (m *Json) UnmarshalGQL(v any) error { @@ -41,10 +49,12 @@ func (m *Json) UnmarshalGQL(v any) error { return nil case string: jsonVal := util.ConvertStrToJsonNoError(&val) - *m = Json(*jsonVal) if jsonVal == nil { return fmt.Errorf("cannot unmarshal %T into Json", v) } + + *m = Json(*jsonVal) + return nil default: return fmt.Errorf("cannot unmarshal %T into Json", v) @@ -54,7 +64,10 @@ func (m *Json) UnmarshalGQL(v any) error { func MarshalJson(val map[string]any) graphql.Marshaler { return graphql.WriterFunc(func(w io.Writer) { if val == nil { - w.Write([]byte("null")) + if _, err := w.Write([]byte("null")); err != nil { + panic(fmt.Errorf("failed to write null value: %w", err)) + } + return } @@ -63,7 +76,9 @@ func MarshalJson(val map[string]any) graphql.Marshaler { panic(fmt.Errorf("failed to marshal json: %w", err)) } - w.Write(data) + if _, err := w.Write(data); err != nil { + panic(fmt.Errorf("failed to write data: %w", err)) + } }) } diff --git a/internal/app/activity/activity_handler_test.go b/internal/app/activity/activity_handler_test.go index 238e2b81d..c0aa54ab0 100644 --- a/internal/app/activity/activity_handler_test.go +++ b/internal/app/activity/activity_handler_test.go @@ -7,7 +7,6 @@ import ( "math" "testing" - "github.com/cloudoperators/heureka/internal/app/activity" a "github.com/cloudoperators/heureka/internal/app/activity" "github.com/cloudoperators/heureka/internal/app/common" "github.com/cloudoperators/heureka/internal/app/event" @@ -50,7 +49,7 @@ func activityFilter() *entity.ActivityFilter { var _ = Describe("When listing Activities", Label("app", "ListActivities"), func() { var ( db *mocks.MockDatabase - activityHandler activity.ActivityHandler + activityHandler a.ActivityHandler filter *entity.ActivityFilter options *entity.ListOptions ) @@ -159,7 +158,6 @@ var _ = Describe("When updating Activity", Label("app", "UpdateService"), func() activity = test.NewFakeActivityEntity() first := 10 var after int64 - after = 0 filter = &entity.ActivityFilter{ Paginated: entity.Paginated{ First: &first, @@ -205,7 +203,6 @@ var _ = Describe("When deleting Activity", Label("app", "DeleteActivity"), func( id = 1 first := 10 var after int64 - after = 0 filter = &entity.ActivityFilter{ Paginated: entity.Paginated{ First: &first, @@ -249,7 +246,6 @@ var _ = Describe("When modifying relationship of Service and Activity", Label("a activity = test.NewFakeActivityEntity() first := 10 var after int64 - after = 0 filter = &entity.ActivityFilter{ Paginated: entity.Paginated{ First: &first, @@ -303,7 +299,6 @@ var _ = Describe("When modifying relationship of Issue and Activity", Label("app activity = test.NewFakeActivityEntity() first := 10 var after int64 - after = 0 filter = &entity.ActivityFilter{ Paginated: entity.Paginated{ First: &first, diff --git a/internal/app/common/pagination_helpers.go b/internal/app/common/pagination_helpers.go index 04028f4f2..6283e70f7 100644 --- a/internal/app/common/pagination_helpers.go +++ b/internal/app/common/pagination_helpers.go @@ -16,7 +16,7 @@ func PreparePagination(filter *entity.Paginated, options *entity.ListOptions) { if filter.First != nil { first = *filter.First } - //@†odo add debug log entry + // @†odo add debug log entry listSize := first + 1 filter.First = &listSize } @@ -39,7 +39,7 @@ func EnsurePaginatedX(filter *entity.PaginatedX) { filter.First = &first } if filter.After == nil { - var after string = "" + after := "" filter.After = &after } } diff --git a/internal/app/common/user_id.go b/internal/app/common/user_id.go index 97c98ac0e..f4d255704 100644 --- a/internal/app/common/user_id.go +++ b/internal/app/common/user_id.go @@ -22,7 +22,7 @@ func GetCurrentUserId(ctx context.Context, db database.Database) (int64, error) if authentication_context.IsAuthenticationRequired(ctx) { uniqueUserId, err := authentication_context.UserNameFromContext(ctx) if err != nil { - return 0, fmt.Errorf("Could not get user name from context: %w", err) + return 0, fmt.Errorf("could not get user name from context: %w", err) } return getUserIdFromDb(db, uniqueUserId) @@ -35,7 +35,7 @@ func getUserIdFromDb(db database.Database, uniqueUserId string) (int64, error) { filter := &entity.UserFilter{UniqueUserID: []*string{&uniqueUserId}} ids, err := db.GetAllUserIds(filter) if err != nil { - return unknownUser, fmt.Errorf("Unable to get user ids %w", err) + return unknownUser, fmt.Errorf("unable to get user ids %w", err) } else if len(ids) < 1 { return unknownUser, nil } diff --git a/internal/app/component/component_handler.go b/internal/app/component/component_handler.go index 8019e0f98..d3ebd05d6 100644 --- a/internal/app/component/component_handler.go +++ b/internal/app/component/component_handler.go @@ -13,7 +13,6 @@ import ( "github.com/cloudoperators/heureka/internal/cache" "github.com/cloudoperators/heureka/internal/database" "github.com/cloudoperators/heureka/internal/entity" - "github.com/cloudoperators/heureka/internal/openfga" "github.com/sirupsen/logrus" ) @@ -28,7 +27,6 @@ type componentHandler struct { database database.Database eventRegistry event.EventRegistry cache cache.Cache - openfga openfga.Authorization } func NewComponentHandler(handlerContext common.HandlerContext) ComponentHandler { diff --git a/internal/app/component_instance/component_instance_handler_test.go b/internal/app/component_instance/component_instance_handler_test.go index dcfd61f35..9ca340cca 100644 --- a/internal/app/component_instance/component_instance_handler_test.go +++ b/internal/app/component_instance/component_instance_handler_test.go @@ -30,6 +30,10 @@ func TestComponentInstanceHandler(t *testing.T) { RunSpecs(t, "Component Instance Service Test Suite") } +const ( + recordSetType = "RecordSet" +) + var ( er event.EventRegistry authz openfga.Authorization @@ -209,7 +213,7 @@ var _ = Describe("When creating ComponentInstance", Label("app", "CreateComponen componentInstanceHandler = ci.NewComponentInstanceHandler(handlerContext) // Ensure type is allowed if ParentId is set - componentInstance.Type = "RecordSet" + componentInstance.Type = recordSetType componentInstance.ParentId = 1234 newComponentInstance, err := componentInstanceHandler.CreateComponentInstance(common.NewAdminContext(), &componentInstance, nil) Expect(err).To(BeNil(), "no error should be thrown") @@ -240,7 +244,7 @@ var _ = Describe("When creating ComponentInstance", Label("app", "CreateComponen componentInstanceHandler = ci.NewComponentInstanceHandler(handlerContext) // Ensure type is allowed if ParentId is set - componentInstance.Type = "RecordSet" + componentInstance.Type = recordSetType componentInstance.ParentId = 1234 // Set ComponentVersionId to 0 to test creation without it componentInstance.ComponentVersionId = 0 @@ -305,7 +309,7 @@ var _ = Describe("When updating ComponentInstance", Label("app", "UpdateComponen componentInstance.Project = "NewProject" componentInstance.Pod = "NewPod" componentInstance.Container = "NewContainer" - componentInstance.Type = "RecordSet" + componentInstance.Type = recordSetType componentInstance.Context = &entity.Json{"my_ip": "192.168.0.0"} componentInstance.ParentId = 1234 componentInstance.CCRN = dbtest.GenerateFakeCcrn(componentInstance.Cluster, componentInstance.Namespace) diff --git a/internal/app/event/event_registry_test.go b/internal/app/event/event_registry_test.go index 7d388bb91..8cf411be4 100644 --- a/internal/app/event/event_registry_test.go +++ b/internal/app/event/event_registry_test.go @@ -147,6 +147,7 @@ var _ = Describe("EventRegistry", Label("app", "event", "EventRegistry"), func() timeout := time.After(10 * time.Second) for { // Check for what's expected (all go routines have incremented the counter) + //nolint:staticcheck if atomic.LoadInt64(&eventHandled) == int64(numEvents) { break } diff --git a/internal/app/evidence/evidence_handler_test.go b/internal/app/evidence/evidence_handler_test.go index 9731dcd50..0d5a4438c 100644 --- a/internal/app/evidence/evidence_handler_test.go +++ b/internal/app/evidence/evidence_handler_test.go @@ -167,7 +167,6 @@ var _ = Describe("When updating Evidence", Label("app", "UpdateEvidence"), func( evidence = test.NewFakeEvidenceEntity() first := 10 var after int64 - after = 0 filter = &entity.EvidenceFilter{ Paginated: entity.Paginated{ First: &first, @@ -215,7 +214,6 @@ var _ = Describe("When deleting Evidence", Label("app", "DeleteEvidence"), func( id = 1 first := 10 var after int64 - after = 0 filter = &entity.EvidenceFilter{ Paginated: entity.Paginated{ First: &first, diff --git a/internal/app/heureka.go b/internal/app/heureka.go index da5b77fef..f9a20ea35 100644 --- a/internal/app/heureka.go +++ b/internal/app/heureka.go @@ -120,7 +120,7 @@ func NewHeurekaApp(ctx context.Context, wg *sync.WaitGroup, db database.Database func NewAppCache(ctx context.Context, wg *sync.WaitGroup, cfg util.Config) cache.Cache { var cacheConfig interface{} - if cfg.CacheEnable == true { + if cfg.CacheEnable { cacheBaseConfig := cache.CacheConfig{ MonitorInterval: time.Duration(cfg.CacheMonitorMSec) * time.Millisecond, MaxDbConcurrentRefreshes: cfg.CacheMaxDbConcurrentRefreshes, diff --git a/internal/app/issue/issue_handler_test.go b/internal/app/issue/issue_handler_test.go index b415d93ae..9ffe676ce 100644 --- a/internal/app/issue/issue_handler_test.go +++ b/internal/app/issue/issue_handler_test.go @@ -11,7 +11,6 @@ import ( "github.com/cloudoperators/heureka/internal/app/common" "github.com/cloudoperators/heureka/internal/app/event" "github.com/cloudoperators/heureka/internal/app/issue" - appIssue "github.com/cloudoperators/heureka/internal/app/issue" "github.com/cloudoperators/heureka/internal/database/mariadb" appErrors "github.com/cloudoperators/heureka/internal/errors" "github.com/cloudoperators/heureka/internal/openfga" @@ -232,7 +231,7 @@ var _ = Describe("When listing Issues", Label("app", "ListIssues"), func() { db.On("GetIssues", filter, []entity.Order{}).Return(issues, nil) db.On("GetAllIssueCursors", filter, []entity.Order{}).Return(cursors, nil) db.On("CountIssueTypes", filter).Return(issueTypeCounts, nil) - issueHandler = appIssue.NewIssueHandler(handlerContext) + issueHandler = issue.NewIssueHandler(handlerContext) res, err := issueHandler.ListIssues(filter, options) Expect(err).To(BeNil(), "no error should be thrown") Expect(*res.PageInfo.HasNextPage).To(BeEquivalentTo(hasNextPage), "correct hasNextPage indicator") @@ -744,9 +743,9 @@ var _ = Describe("When updating Issue", Label("app", "UpdateIssue"), func() { updatedIssue, err := issueHandler.UpdateIssue(common.NewAdminContext(), issueResult.Issue) Expect(err).To(BeNil(), "no error should be thrown") By("setting fields", func() { - Expect(updatedIssue.PrimaryName).To(BeEquivalentTo(issueResult.Issue.PrimaryName)) + Expect(updatedIssue.PrimaryName).To(BeEquivalentTo(issueResult.PrimaryName)) Expect(updatedIssue.Description).To(BeEquivalentTo(issueResult.Issue.Description)) - Expect(updatedIssue.Type.String()).To(BeEquivalentTo(issueResult.Issue.Type.String())) + Expect(updatedIssue.Type.String()).To(BeEquivalentTo(issueResult.Type.String())) }) }) }) diff --git a/internal/app/issue_match/issue_match_handler.go b/internal/app/issue_match/issue_match_handler.go index e6b275930..fd8f2e7b8 100644 --- a/internal/app/issue_match/issue_match_handler.go +++ b/internal/app/issue_match/issue_match_handler.go @@ -164,7 +164,7 @@ func (im *issueMatchHandler) CreateIssueMatch(ctx context.Context, issueMatch *e IssueId: []*int64{&issueMatch.IssueId}, } - //@todo discuss: may be moved to somewhere else? + // @todo discuss: may be moved to somewhere else? effectiveSeverity, err := im.severityHandler.GetSeverity(severityFilter) if err != nil { l.Error(err) diff --git a/internal/app/issue_match/issue_match_handler_events.go b/internal/app/issue_match/issue_match_handler_events.go index edfa2eebe..92b6c302e 100644 --- a/internal/app/issue_match/issue_match_handler_events.go +++ b/internal/app/issue_match/issue_match_handler_events.go @@ -188,10 +188,10 @@ func OnComponentVersionAssignmentToComponentInstance(db database.Database, compo // infered user from the component version issue macht issue_match := &entity.IssueMatch{ Metadata: entity.Metadata{ - CreatedBy: 1, //@todo discuss whatever we use a static system user or infer the user from the ComponentVersionIssue - UpdatedBy: 1, //@todo discuss whatever we use a static system user or infer the user from the ComponentVersionIssue + CreatedBy: 1, // @todo discuss whatever we use a static system user or infer the user from the ComponentVersionIssue + UpdatedBy: 1, // @todo discuss whatever we use a static system user or infer the user from the ComponentVersionIssue }, - UserId: 1, //@todo discuss whatever we use a static system user or infer the user from the ComponentVersionIssue + UserId: 1, // @todo discuss whatever we use a static system user or infer the user from the ComponentVersionIssue Status: entity.IssueMatchStatusValuesNew, Severity: issueVariantMap[issueId].Severity, // we got two simply take the first one ComponentInstanceId: componentInstanceID, diff --git a/internal/app/issue_repository/issue_repository_handler_test.go b/internal/app/issue_repository/issue_repository_handler_test.go index 3acf15514..f3292515a 100644 --- a/internal/app/issue_repository/issue_repository_handler_test.go +++ b/internal/app/issue_repository/issue_repository_handler_test.go @@ -129,7 +129,6 @@ var _ = Describe("When creating IssueRepository", Label("app", "CreateIssueRepos issueRepository = test.NewFakeIssueRepositoryEntity() first := 10 var after int64 - after = 0 filter = &entity.IssueRepositoryFilter{ Paginated: entity.Paginated{ First: &first, @@ -200,7 +199,6 @@ var _ = Describe("When updating IssueRepository", Label("app", "UpdateIssueRepos issueRepository = test.NewFakeIssueRepositoryEntity() first := 10 var after int64 - after = 0 filter = &entity.IssueRepositoryFilter{ Paginated: entity.Paginated{ First: &first, @@ -243,7 +241,6 @@ var _ = Describe("When deleting IssueRepository", Label("app", "DeleteIssueRepos id = 1 first := 10 var after int64 - after = 0 filter = &entity.IssueRepositoryFilter{ Paginated: entity.Paginated{ First: &first, diff --git a/internal/app/issue_variant/issue_variant_handler_test.go b/internal/app/issue_variant/issue_variant_handler_test.go index 589a433e4..74386796a 100644 --- a/internal/app/issue_variant/issue_variant_handler_test.go +++ b/internal/app/issue_variant/issue_variant_handler_test.go @@ -235,7 +235,6 @@ var _ = Describe("When creating IssueVariant", Label("app", "CreateIssueVariant" issueVariant = test.NewFakeIssueVariantEntity(nil) first := 10 var after int64 - after = 0 filter = &entity.IssueVariantFilter{ Paginated: entity.Paginated{ First: &first, @@ -287,7 +286,6 @@ var _ = Describe("When updating IssueVariant", Label("app", "UpdateIssueVariant" issueVariant = test.NewFakeIssueVariantEntity(nil) first := 10 var after int64 - after = 0 filter = &entity.IssueVariantFilter{ Paginated: entity.Paginated{ First: &first, @@ -339,7 +337,6 @@ var _ = Describe("When deleting IssueVariant", Label("app", "DeleteIssueVariant" id = 1 first := 10 var after int64 - after = 0 filter = &entity.IssueVariantFilter{ Paginated: entity.Paginated{ First: &first, diff --git a/internal/app/profiler/profiler.go b/internal/app/profiler/profiler.go index 7549413d2..736641bbc 100644 --- a/internal/app/profiler/profiler.go +++ b/internal/app/profiler/profiler.go @@ -46,6 +46,9 @@ func (p *Profiler) Stop() { } func (p *Profiler) cleanup() { - p.file.Close() + if err := p.file.Close(); err != nil { + log.Printf("[Profiler]: error during closing file: %s", err) + } + p.file = nil } diff --git a/internal/app/scanner_run/scanner_run_test.go b/internal/app/scanner_run/scanner_run_test.go index a492da3b2..35e6c681f 100644 --- a/internal/app/scanner_run/scanner_run_test.go +++ b/internal/app/scanner_run/scanner_run_test.go @@ -60,9 +60,10 @@ var _ = Describe("ScannerRun", Label("app", "CreateScannerRun"), func() { db.On("Autopatch").Return(true, nil) scannerRunHandler = NewScannerRunHandler(handlerContext) - scannerRunHandler.CreateScannerRun(sre) - _, err := scannerRunHandler.CompleteScannerRun(sre.UUID) + _, err := scannerRunHandler.CreateScannerRun(sre) + Expect(err).To(BeNil()) + _, err = scannerRunHandler.CompleteScannerRun(sre.UUID) Expect(err).To(BeNil()) }) @@ -71,9 +72,10 @@ var _ = Describe("ScannerRun", Label("app", "CreateScannerRun"), func() { db.On("FailScannerRun", sre.UUID, "Booom!").Return(true, nil) scannerRunHandler = NewScannerRunHandler(handlerContext) - scannerRunHandler.CreateScannerRun(sre) - _, err := scannerRunHandler.FailScannerRun(sre.UUID, "Booom!") + _, err := scannerRunHandler.CreateScannerRun(sre) + Expect(err).To(BeNil()) + _, err = scannerRunHandler.FailScannerRun(sre.UUID, "Booom!") Expect(err).To(BeNil()) }) diff --git a/internal/app/shared/issueVariant.go b/internal/app/shared/issueVariant.go index b2afc2b3f..357751366 100644 --- a/internal/app/shared/issueVariant.go +++ b/internal/app/shared/issueVariant.go @@ -30,13 +30,13 @@ func BuildIssueVariantMap(db database.Database, filter *entity.ServiceIssueVaria issueVariants, err := db.GetServiceIssueVariants(filter) if err != nil { l.WithField("event-step", "FetchIssueVariants").WithError(err).Error("Error while fetching issue variants") - return nil, fmt.Errorf("Error while fetching issue variants: %w", err) + return nil, fmt.Errorf("error while fetching issue variants: %w", err) } // No issue variants found, if len(issueVariants) < 1 { l.WithField("event-step", "FetchIssueVariants").Error("No issue variants found that are related to the issue repository") - return nil, fmt.Errorf("No issue variants found that are related to the issue repository") + return nil, fmt.Errorf("no issue variants found that are related to the issue repository") } // create a map of issue id to variants for easy access diff --git a/internal/app/user/user_handler_test.go b/internal/app/user/user_handler_test.go index 50d405b2a..2e6a21635 100644 --- a/internal/app/user/user_handler_test.go +++ b/internal/app/user/user_handler_test.go @@ -126,7 +126,6 @@ var _ = Describe("When creating User", Label("app", "CreateUser"), func() { user = test.NewFakeUserEntity() first := 10 var after int64 - after = 0 filter = &entity.UserFilter{ Paginated: entity.Paginated{ First: &first, @@ -170,7 +169,6 @@ var _ = Describe("When updating User", Label("app", "UpdateUser"), func() { user = test.NewFakeUserEntity() first := 10 var after int64 - after = 0 filter = &entity.UserFilter{ Paginated: entity.Paginated{ First: &first, @@ -214,7 +212,6 @@ var _ = Describe("When deleting User", Label("app", "DeleteUser"), func() { id = 1 first := 10 var after int64 - after = 0 filter = &entity.UserFilter{ Paginated: entity.Paginated{ First: &first, diff --git a/internal/cache/cache.go b/internal/cache/cache.go index 09179ce42..12845dd51 100644 --- a/internal/cache/cache.go +++ b/internal/cache/cache.go @@ -37,18 +37,18 @@ func NewCache(ctx context.Context, wg *sync.WaitGroup, config interface{}) Cache func getCallParameters(fn interface{}, args ...interface{}) (reflect.Value, []reflect.Value, error) { v := reflect.ValueOf(fn) if v.Kind() != reflect.Func { - return reflect.Value{}, []reflect.Value{}, errors.New("Expected function parameter is not a function") + return reflect.Value{}, []reflect.Value{}, errors.New("expected function parameter is not a function") } if len(args) != v.Type().NumIn() { - return reflect.Value{}, []reflect.Value{}, errors.New("Incorrect number of arguments for the function") + return reflect.Value{}, []reflect.Value{}, errors.New("incorrect number of arguments for the function") } in := make([]reflect.Value, len(args)) for i, arg := range args { argVal := reflect.ValueOf(arg) if !argVal.Type().AssignableTo(v.Type().In(i)) { - return reflect.Value{}, []reflect.Value{}, fmt.Errorf("Argument %d has incorrect type", i) + return reflect.Value{}, []reflect.Value{}, fmt.Errorf("argument %d has incorrect type", i) } in[i] = argVal } @@ -58,13 +58,13 @@ func getCallParameters(fn interface{}, args ...interface{}) (reflect.Value, []re func getReturnValues[T any](out []reflect.Value) (T, error) { var zero T if len(out) != 2 { - return zero, fmt.Errorf("Function call returned incorrect number of values") + return zero, fmt.Errorf("function call returned incorrect number of values") } // Assert first return to T result, ok := out[0].Interface().(T) if !ok { - return zero, fmt.Errorf("Type assertion to %T failed", zero) + return zero, fmt.Errorf("type assertion to %T failed", zero) } // Assert second return to error @@ -72,9 +72,9 @@ func getReturnValues[T any](out []reflect.Value) (T, error) { if errInterface != nil { err, ok := errInterface.(error) if !ok { - return zero, errors.New("Second return value is not an error") + return zero, errors.New("second return value is not an error") } - return zero, fmt.Errorf("Execution failed: %w", err) + return zero, fmt.Errorf("execution failed: %w", err) } return result, nil } @@ -90,12 +90,12 @@ func callEnabled[T any](c Cache, ttl time.Duration, fnname string, fn interface{ var zero T v, in, err := getCallParameters(fn, args...) if err != nil { - return zero, fmt.Errorf("Cache (param): Get call parameters failed: %w", err) + return zero, fmt.Errorf("cache (param): Get call parameters failed: %w", err) } key, err := c.CacheKey(fnname, fn, args...) if err != nil { - return zero, fmt.Errorf("Cache (key): Could not create cache key.") + return zero, fmt.Errorf("cache (key): Could not create cache key") } if s, ok, err := c.Get(key); err == nil && ok { @@ -115,7 +115,7 @@ func callEnabled[T any](c Cache, ttl time.Duration, fnname string, fn interface{ } _ = c.Invalidate(key) // poison-pill protection } else if err != nil { - return zero, fmt.Errorf("Cache (get): %w", err) + return zero, fmt.Errorf("cache (get): %w", err) } c.IncMiss() @@ -123,14 +123,14 @@ func callEnabled[T any](c Cache, ttl time.Duration, fnname string, fn interface{ result, err := getReturnValues[T](out) if err != nil { - return zero, fmt.Errorf("Cache (fcall): Return value error: %w", err) + return zero, fmt.Errorf("cache (fcall): Return value error: %w", err) } else if enc, encErr := encode(result); encErr == nil { err = c.Set(key, enc, ttl) if err != nil { - return zero, fmt.Errorf("Cache (set): %w", err) + return zero, fmt.Errorf("cache (set): %w", err) } } else { - return zero, fmt.Errorf("Cache (encode): %w", err) + return zero, fmt.Errorf("cache (encode): %w", err) } return result, nil @@ -140,7 +140,7 @@ func callDisabled[T any](fn interface{}, args ...interface{}) (T, error) { var zero T v, in, err := getCallParameters(fn, args...) if err != nil { - return zero, fmt.Errorf("NoCache (param): Get call parameters failed: %w", err) + return zero, fmt.Errorf("noCache (param): Get call parameters failed: %w", err) } out := v.Call(in) return getReturnValues[T](out) @@ -166,12 +166,13 @@ func decode[T any](s string) (T, error) { } func DecodeKey(key string, keyHash KeyHashType) (string, error) { - if keyHash == KEY_HASH_BASE64 { + switch keyHash { + case KEY_HASH_BASE64: return decodeBase64(key) - } else if keyHash == KEY_HASH_HEX { + case KEY_HASH_HEX: return decodeHex(key) - } else if keyHash == KEY_HASH_NONE { + case KEY_HASH_NONE: return key, nil } - return "", fmt.Errorf("Cache: Key hash '%s' could not be decoded", keyHash.String()) + return "", fmt.Errorf("cache: Key hash '%s' could not be decoded", keyHash.String()) } diff --git a/internal/cache/cache_base.go b/internal/cache/cache_base.go index d053bff6b..f2d3c7194 100644 --- a/internal/cache/cache_base.go +++ b/internal/cache/cache_base.go @@ -91,38 +91,39 @@ func (cb *CacheBase) startMonitorIfNeeded(interval time.Duration) { func (cb *CacheBase) IncHit() { cb.statMu.Lock() defer cb.statMu.Unlock() - cb.stat.Hit = cb.stat.Hit + 1 + cb.stat.Hit++ } func (cb *CacheBase) IncMiss() { cb.statMu.Lock() defer cb.statMu.Unlock() - cb.stat.Miss = cb.stat.Miss + 1 + cb.stat.Miss++ } -func (cb CacheBase) GetStat() Stat { +func (cb *CacheBase) GetStat() Stat { cb.statMu.RLock() defer cb.statMu.RUnlock() return cb.stat } -func (cb CacheBase) EncodeKey(key string) string { - if cb.keyHash == KEY_HASH_SHA256 { +func (cb *CacheBase) EncodeKey(key string) string { + switch cb.keyHash { + case KEY_HASH_SHA256: return encodeSHA256(key) - } else if cb.keyHash == KEY_HASH_SHA512 { + case KEY_HASH_SHA512: return encodeSHA512(key) - } else if cb.keyHash == KEY_HASH_HEX { + case KEY_HASH_HEX: return encodeHex(key) - } else if cb.keyHash == KEY_HASH_NONE { + case KEY_HASH_NONE: return key } return encodeBase64(key) } -func (cb CacheBase) CacheKey(fnname string, fn interface{}, args ...interface{}) (string, error) { +func (cb *CacheBase) CacheKey(fnname string, fn interface{}, args ...interface{}) (string, error) { key, err := cacheKeyJson(fnname, fn, args...) if err != nil { - return "", fmt.Errorf("Cache: could not create json cache key.") + return "", fmt.Errorf("cache: could not create json cache key") } return cb.EncodeKey(key), nil } diff --git a/internal/cache/in_memory_cache.go b/internal/cache/in_memory_cache.go index 488fa021b..a1ce85998 100644 --- a/internal/cache/in_memory_cache.go +++ b/internal/cache/in_memory_cache.go @@ -17,7 +17,7 @@ const ( ) type InMemoryCache struct { - CacheBase + *CacheBase gc *gocache.Cache } @@ -34,7 +34,7 @@ func NewInMemoryCache(ctx context.Context, wg *sync.WaitGroup, config InMemoryCa cacheBase := NewCacheBase(ctx, wg, config.CacheConfig) inMemoryCache := &InMemoryCache{ - CacheBase: *cacheBase, + CacheBase: cacheBase, gc: gocache.New(defaultTtl, cleanupInterval), } @@ -43,7 +43,7 @@ func NewInMemoryCache(ctx context.Context, wg *sync.WaitGroup, config InMemoryCa return inMemoryCache } -func (imc InMemoryCache) Get(key string) (string, bool, error) { +func (imc *InMemoryCache) Get(key string) (string, bool, error) { val, found := imc.gc.Get(key) if !found { return "", false, nil @@ -55,7 +55,7 @@ func (imc InMemoryCache) Get(key string) (string, bool, error) { return valStr, true, nil } -func (imc InMemoryCache) Set(key string, value string, ttl time.Duration) error { +func (imc *InMemoryCache) Set(key string, value string, ttl time.Duration) error { if ttl <= 0 { ttl = gocache.NoExpiration } @@ -63,11 +63,7 @@ func (imc InMemoryCache) Set(key string, value string, ttl time.Duration) error return nil } -func (imc InMemoryCache) Invalidate(key string) error { +func (imc *InMemoryCache) Invalidate(key string) error { imc.gc.Delete(key) return nil } - -func (imc *InMemoryCache) invalidateAll() { - imc.gc.Flush() -} diff --git a/internal/cache/valkey_cache.go b/internal/cache/valkey_cache.go index 1807a034b..1ac65fc9e 100644 --- a/internal/cache/valkey_cache.go +++ b/internal/cache/valkey_cache.go @@ -13,7 +13,7 @@ import ( ) type ValkeyCache struct { - CacheBase + *CacheBase client valkey.Client } @@ -43,7 +43,7 @@ func NewValkeyCache(ctx context.Context, wg *sync.WaitGroup, config ValkeyCacheC return nil } valkeyCache := &ValkeyCache{ - CacheBase: *cacheBase, + CacheBase: cacheBase, client: valkeyClient, } diff --git a/internal/database/mariadb/activity.go b/internal/database/mariadb/activity.go index 787964649..5322e04f4 100644 --- a/internal/database/mariadb/activity.go +++ b/internal/database/mariadb/activity.go @@ -138,8 +138,11 @@ func (s *SqlDatabase) GetAllActivityIds(filter *entity.ActivityFilter) ([]int64, if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performIdScan(stmt, filterParameters, l) } @@ -163,8 +166,11 @@ func (s *SqlDatabase) GetActivities(filter *entity.ActivityFilter) ([]entity.Act if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -190,8 +196,11 @@ func (s *SqlDatabase) CountActivities(filter *entity.ActivityFilter) (int64, err if err != nil { return -1, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performCountScan(stmt, filterParameters, l) } diff --git a/internal/database/mariadb/activity_test.go b/internal/database/mariadb/activity_test.go index 5a7631364..d0b8c94da 100644 --- a/internal/database/mariadb/activity_test.go +++ b/internal/database/mariadb/activity_test.go @@ -15,6 +15,9 @@ import ( "github.com/samber/lo" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("Activity", Label("database", "Activity"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -25,7 +28,7 @@ var _ = Describe("Activity", Label("database", "Activity"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All Activity IDs", Label("GetAllActivityIds"), func() { diff --git a/internal/database/mariadb/autopatch.go b/internal/database/mariadb/autopatch.go index df3820a6f..7d980f93c 100644 --- a/internal/database/mariadb/autopatch.go +++ b/internal/database/mariadb/autopatch.go @@ -7,6 +7,7 @@ import ( "github.com/cloudoperators/heureka/internal/entity" "github.com/cloudoperators/heureka/internal/util" "github.com/samber/lo" + "github.com/sirupsen/logrus" ) func (s *SqlDatabase) Autopatch() (bool, error) { @@ -28,7 +29,11 @@ func (s *SqlDatabase) fetchCompletedRunsWithNewestFirst() (map[string][]int, err if err != nil { return nil, err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + logrus.Warnf("error during closing rows: %s", err) + } + }() // tag -> list of runs (newest first) runs := map[string][]int{} @@ -205,7 +210,7 @@ func (s *SqlDatabase) getVersionIdsOfDisappearedInstances(disappearedInstances [ func (s *SqlDatabase) getComponentIdsOfDisappearedInstances(versions map[int64]struct{}) (map[int64]struct{}, error) { var versionsToFilter []*int64 - for v, _ := range versions { + for v := range versions { versionsToFilter = append(versionsToFilter, &v) } @@ -223,7 +228,7 @@ func (s *SqlDatabase) getComponentIdsOfDisappearedInstances(versions map[int64]s } func (s *SqlDatabase) deleteVersionIssuesOfDisappearedInstances(versionIdsOfDisappearedInstances map[int64]struct{}) error { - for vIdDi, _ := range versionIdsOfDisappearedInstances { + for vIdDi := range versionIdsOfDisappearedInstances { if err := s.RemoveAllIssuesFromComponentVersion(vIdDi); err != nil { return err } @@ -233,7 +238,7 @@ func (s *SqlDatabase) deleteVersionIssuesOfDisappearedInstances(versionIdsOfDisa } func (s *SqlDatabase) deleteVersionsOfDisappearedInstances(versionIdsOfDisappearedInstances map[int64]struct{}) error { - for vIdDi, _ := range versionIdsOfDisappearedInstances { + for vIdDi := range versionIdsOfDisappearedInstances { cif := entity.ComponentInstanceFilter{ComponentVersionId: []*int64{&vIdDi}} res, err := s.GetComponentInstances(&cif, nil) if err != nil { @@ -250,7 +255,7 @@ func (s *SqlDatabase) deleteVersionsOfDisappearedInstances(versionIdsOfDisappear } func (s *SqlDatabase) deleteComponentsOfDisappearedInstances(componentIdsOfDisappearedInstances map[int64]struct{}) error { - for cIdDi, _ := range componentIdsOfDisappearedInstances { + for cIdDi := range componentIdsOfDisappearedInstances { cvf := entity.ComponentVersionFilter{ComponentId: []*int64{&cIdDi}} res, err := s.GetComponentVersions(&cvf, nil) if err != nil { @@ -290,7 +295,11 @@ func (s *SqlDatabase) fetchComponentInstancesForRun(scannerRunId int) (map[int]s if err != nil { return nil, err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + logrus.Warnf("error during closing rows: %s", err) + } + }() instances := map[int]struct{}{} for rows.Next() { @@ -348,7 +357,7 @@ func (s *SqlDatabase) insertPatchIfNoInstanceExists(patch patchInfo) error { ) ` - res, err := s.db.Exec( + _, err := s.db.Exec( query, patch.serviceId, patch.serviceName, @@ -361,11 +370,5 @@ func (s *SqlDatabase) insertPatchIfNoInstanceExists(patch patchInfo) error { return err } - // Detection of skipped patch: - affected, _ := res.RowsAffected() - if affected == 0 { - // Patch was NOT inserted - } - return nil } diff --git a/internal/database/mariadb/autopatch_test.go b/internal/database/mariadb/autopatch_test.go index ab9c61e38..70c7d4489 100644 --- a/internal/database/mariadb/autopatch_test.go +++ b/internal/database/mariadb/autopatch_test.go @@ -41,7 +41,7 @@ func newAutoPatchTest() *autoPatchTest { } func (apt *autoPatchTest) TearDown() { - dbm.TestTearDown(apt.db) + _ = dbm.TestTearDown(apt.db) } func (apt *autoPatchTest) Run(tag string, info autoPatchTestInfo, fn func(db *mariadb.SqlDatabase) (bool, error)) { @@ -318,7 +318,7 @@ var _ = Describe("Autopatch", Label("database", "Autopatch"), func() { expectDeletedVersions: lo.ToPtr([]string{"V20"}), }, { - description: "WHEN 1 component with component version issues disappear from 2 components with different version and service", //THEN patch should be created and not used version should be removed and component version issues for not used version should be removed + description: "WHEN 1 component with component version issues disappear from 2 components with different version and service", // THEN patch should be created and not used version should be removed and component version issues for not used version should be removed scannerRuns: [][]string{{"CI1", "CI2"}, {"CI1"}}, dbSeeds: test.DbSeeds{ Issues: []string{"Issue1", "Issue2", "Issue3", "Issue4"}, @@ -334,14 +334,27 @@ var _ = Describe("Autopatch", Label("database", "Autopatch"), func() { {Issue: "Issue3", ComponentVersion: "V20"}, }, }, - expectedResults: []bool{false, true}, - expectedPatchCount: 1, - patchedComponentInstances: []string{"CI2"}, - expectDeletedVersions: lo.ToPtr([]string{"V20"}), - expectDeletedComponentVersionIssues: []test.ComponentVersionIssue{{"Issue1", "V20"}, {"Issue2", "V20"}, {"Issue3", "V20"}}, + expectedResults: []bool{false, true}, + expectedPatchCount: 1, + patchedComponentInstances: []string{"CI2"}, + expectDeletedVersions: lo.ToPtr([]string{"V20"}), + expectDeletedComponentVersionIssues: []test.ComponentVersionIssue{ + { + Issue: "Issue1", + ComponentVersion: "V20", + }, + { + Issue: "Issue2", + ComponentVersion: "V20", + }, + { + Issue: "Issue3", + ComponentVersion: "V20", + }, + }, }, { - description: "WHEN 1 component disappear from 2 components with the same component and different version and service", //THEN patch should be created and not used version should be removed and component should not be removed + description: "WHEN 1 component disappear from 2 components with the same component and different version and service", // THEN patch should be created and not used version should be removed and component should not be removed scannerRuns: [][]string{{"CI1", "CI2"}, {"CI1"}}, dbSeeds: test.DbSeeds{ Components: []test.ComponentData{ @@ -356,7 +369,7 @@ var _ = Describe("Autopatch", Label("database", "Autopatch"), func() { expectDeletedComponents: lo.ToPtr([]string{}), }, { - description: "WHEN 1 component disappear from 2 components with different component, version and service", //THEN patch should be created and not used version should be removed and not used component should be removed + description: "WHEN 1 component disappear from 2 components with different component, version and service", // THEN patch should be created and not used version should be removed and not used component should be removed scannerRuns: [][]string{{"CI1", "CI2"}, {"CI1"}}, dbSeeds: test.DbSeeds{ Components: []test.ComponentData{ @@ -371,7 +384,7 @@ var _ = Describe("Autopatch", Label("database", "Autopatch"), func() { expectDeletedComponents: lo.ToPtr([]string{"C2"}), }, { - description: "WHEN 4 scans detect disappearance of 1 component and the component appear and disappear again", //THEN two patches should be created for the same service and version + description: "WHEN 4 scans detect disappearance of 1 component and the component appear and disappear again", // THEN two patches should be created for the same service and version scannerRuns: [][]string{{"CI0", "CI1"}, {"CI0"}, {"CI0", "CI2"}, {"CI0"}}, dbSeeds: test.DbSeeds{ Components: []test.ComponentData{ diff --git a/internal/database/mariadb/component.go b/internal/database/mariadb/component.go index b5e34c588..3e1bacbd4 100644 --- a/internal/database/mariadb/component.go +++ b/internal/database/mariadb/component.go @@ -155,7 +155,7 @@ func (s *SqlDatabase) buildComponentStatement(baseQuery string, filter *entity.C filterStr := getComponentFilterString(filter) joins := s.getComponentJoins(filter, order) - cursorFields, err := DecodeCursor(filter.PaginatedX.After) + cursorFields, err := DecodeCursor(filter.After) if err != nil { return nil, nil, err } @@ -202,7 +202,7 @@ func (s *SqlDatabase) buildComponentStatement(baseQuery string, filter *entity.C filterParameters = buildQueryParameters(filterParameters, filter.ComponentVersionId) filterParameters = buildQueryParameters(filterParameters, filter.ServiceCCRN) if withCursor { - filterParameters = append(filterParameters, GetCursorQueryParameters(filter.PaginatedX.First, cursorFields)...) + filterParameters = append(filterParameters, GetCursorQueryParameters(filter.First, cursorFields)...) } return stmt, filterParameters, nil @@ -223,8 +223,11 @@ func (s *SqlDatabase) GetAllComponentIds(filter *entity.ComponentFilter) ([]int6 if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performIdScan(stmt, filterParameters, l) } @@ -248,8 +251,11 @@ func (s *SqlDatabase) GetAllComponentCursors(filter *entity.ComponentFilter, ord if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() rows, err := performListScan( stmt, @@ -268,7 +274,7 @@ func (s *SqlDatabase) GetAllComponentCursors(filter *entity.ComponentFilter, ord var isc entity.IssueSeverityCounts if row.RatingCount != nil { - isc = row.RatingCount.AsIssueSeverityCounts() + isc = row.AsIssueSeverityCounts() } cursor, _ := EncodeCursor(WithComponent(order, c, isc)) @@ -297,8 +303,11 @@ func (s *SqlDatabase) GetComponents(filter *entity.ComponentFilter, order []enti if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -309,7 +318,7 @@ func (s *SqlDatabase) GetComponents(filter *entity.ComponentFilter, order []enti var isc entity.IssueSeverityCounts if e.RatingCount != nil { - isc = e.RatingCount.AsIssueSeverityCounts() + isc = e.AsIssueSeverityCounts() } cursor, _ := EncodeCursor(WithComponent(order, c, isc)) @@ -339,8 +348,11 @@ func (s *SqlDatabase) CountComponents(filter *entity.ComponentFilter) (int64, er if err != nil { return -1, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performCountScan(stmt, filterParameters, l) } @@ -404,8 +416,11 @@ func (s *SqlDatabase) CountComponentVulnerabilities(filter *entity.ComponentFilt }).Error(msg) return nil, fmt.Errorf("%s", msg) } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -531,7 +546,11 @@ func (s *SqlDatabase) GetComponentCcrns(filter *entity.ComponentFilter) ([]strin l.Error("Error preparing statement: ", err) return nil, err } - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() // Execute the query rows, err := stmt.Queryx(filterParameters...) @@ -539,7 +558,11 @@ func (s *SqlDatabase) GetComponentCcrns(filter *entity.ComponentFilter) ([]strin l.Error("Error executing query: ", err) return nil, err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + l.Warnf("error during closing rows: %s", err) + } + }() // Collect the results componentCcrns := []string{} diff --git a/internal/database/mariadb/component_instance.go b/internal/database/mariadb/component_instance.go index c058a9c9e..0ebcf5091 100644 --- a/internal/database/mariadb/component_instance.go +++ b/internal/database/mariadb/component_instance.go @@ -13,8 +13,8 @@ import ( ) func ensureComponentInstanceFilter(f *entity.ComponentInstanceFilter) *entity.ComponentInstanceFilter { - var first int = 1000 - var after string = "" + first := 1000 + after := "" if f == nil { return &entity.ComponentInstanceFilter{ PaginatedX: entity.PaginatedX{ @@ -130,13 +130,15 @@ func getComponentInstanceUpdateFields(componentInstance *entity.ComponentInstanc return strings.Join(fl, ", ") } -func (s *SqlDatabase) buildComponentInstanceStatement(baseQuery string, filter *entity.ComponentInstanceFilter, withCursor bool, order []entity.Order, l *logrus.Entry) (Stmt, []interface{}, error) { +func (s *SqlDatabase) buildComponentInstanceStatement(baseQuery string, + filter *entity.ComponentInstanceFilter, withCursor bool, order []entity.Order, l *logrus.Entry, +) (Stmt, []interface{}, error) { var query string filter = ensureComponentInstanceFilter(filter) l.WithFields(logrus.Fields{"filter": filter}) filterStr := getComponentInstanceFilterString(filter) - cursorFields, err := DecodeCursor(filter.PaginatedX.After) + cursorFields, err := DecodeCursor(filter.After) if err != nil { return nil, nil, fmt.Errorf("failed to decode cursor: %w", err) } @@ -196,7 +198,7 @@ func (s *SqlDatabase) buildComponentInstanceStatement(baseQuery string, filter * filterParameters = buildQueryParameters(filterParameters, filter.ComponentVersionVersion) filterParameters = buildQueryParameters(filterParameters, filter.Search) if withCursor { - filterParameters = append(filterParameters, GetCursorQueryParameters(filter.PaginatedX.First, cursorFields)...) + filterParameters = append(filterParameters, GetCursorQueryParameters(filter.First, cursorFields)...) } return stmt, filterParameters, nil @@ -217,7 +219,11 @@ func (s *SqlDatabase) GetAllComponentInstanceIds(filter *entity.ComponentInstanc if err != nil { return nil, fmt.Errorf("failed to build ComponentInstance IDs query: %w", err) } - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() ids, err := performIdScan(stmt, filterParameters, l) if err != nil { @@ -227,7 +233,9 @@ func (s *SqlDatabase) GetAllComponentInstanceIds(filter *entity.ComponentInstanc return ids, nil } -func (s *SqlDatabase) GetComponentInstances(filter *entity.ComponentInstanceFilter, order []entity.Order) ([]entity.ComponentInstanceResult, error) { +func (s *SqlDatabase) GetComponentInstances(filter *entity.ComponentInstanceFilter, + order []entity.Order, +) ([]entity.ComponentInstanceResult, error) { l := logrus.WithFields(logrus.Fields{ "event": "database.GetComponentInstances", }) @@ -242,7 +250,11 @@ func (s *SqlDatabase) GetComponentInstances(filter *entity.ComponentInstanceFilt if err != nil { return nil, fmt.Errorf("failed to build ComponentInstances query: %w", err) } - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() results, err := performListScan( stmt, @@ -270,7 +282,9 @@ func (s *SqlDatabase) GetComponentInstances(filter *entity.ComponentInstanceFilt return results, nil } -func (s *SqlDatabase) GetAllComponentInstanceCursors(filter *entity.ComponentInstanceFilter, order []entity.Order) ([]string, error) { +func (s *SqlDatabase) GetAllComponentInstanceCursors(filter *entity.ComponentInstanceFilter, + order []entity.Order, +) ([]string, error) { l := logrus.WithFields(logrus.Fields{ "filter": filter, "event": "database.GetAllComponentInstanceCursors", @@ -325,7 +339,11 @@ func (s *SqlDatabase) CountComponentInstances(filter *entity.ComponentInstanceFi if err != nil { return -1, fmt.Errorf("failed to build ComponentInstance count query: %w", err) } - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() count, err := performCountScan(stmt, filterParameters, l) if err != nil { @@ -473,14 +491,22 @@ func (s *SqlDatabase) getComponentInstanceAttr(attrName string, filter *entity.C if err != nil { return nil, fmt.Errorf("failed to build ComponentInstance attribute query for %s: %w", attrName, err) } - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() // Execute the query rows, err := stmt.Queryx(filterParameters...) if err != nil { return nil, fmt.Errorf("failed to execute ComponentInstance attribute query for %s: %w", attrName, err) } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + l.Warnf("error during closing rows: %s", err) + } + }() // Collect the results attrVal := []string{} diff --git a/internal/database/mariadb/component_instance_test.go b/internal/database/mariadb/component_instance_test.go index ed62672af..3a7e62738 100644 --- a/internal/database/mariadb/component_instance_test.go +++ b/internal/database/mariadb/component_instance_test.go @@ -20,6 +20,14 @@ import ( "golang.org/x/text/language" ) +const ( + prev = "\U0010FFFF" + notExistentProject = "NotexistentProject" +) + +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -30,7 +38,7 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All ComponentInstance IDs", Label("GetAllComponentInstanceIds"), func() { @@ -100,6 +108,9 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), }) }) It("can filter by a single service ccrn that does exist", func() { + // nolint due to weak random number generator for test reason + // + //nolint:gosec ciRow := seedCollection.ComponentInstanceRows[rand.Intn(len(seedCollection.ComponentInstanceRows))] serviceRow, _ := lo.Find(seedCollection.ServiceRows, func(s mariadb.BaseServiceRow) bool { return s.Id.Int64 == ciRow.ServiceId.Int64 @@ -152,6 +163,7 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), }) It("can filter by a single componentVersion id that does exist", func() { // select a component version + cvRow := seedCollection.ComponentVersionRows[rand.Intn(len(seedCollection.ComponentVersionRows))] // collect all componentInstance ids that belong to the component version @@ -299,6 +311,7 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), }) It("can filter by a single issue match id that does exist", func() { // get a service that should return at least one issue + rnd := seedCollection.IssueMatchRows[rand.Intn(len(seedCollection.IssueMatchRows))] ciId := rnd.ComponentInstanceId.Int64 filter := &entity.ComponentInstanceFilter{ @@ -599,7 +612,7 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), It("can update componentInstance count correctly", func() { componentInstance := seedCollection.ComponentInstanceRows[0].AsComponentInstance() componentInstance.ParentId = 1 - componentInstance.Count = componentInstance.Count + 1 + componentInstance.Count++ err := db.UpdateComponentInstance(&componentInstance) By("throwing no error", func() { @@ -865,7 +878,7 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), ) }) It("and using notexisting value returns an empty list when no Project match the filter", func() { - notexistentProject := "NotexistentProject" + notexistentProject := notExistentProject issueComponentInstanceAttrFilterWithExpect( db.GetCcrn, &entity.ComponentInstanceFilter{Project: []*string{¬existentProject}}, @@ -1016,7 +1029,7 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), }) It("using one notexisting value of all CCRN attributes returns an empty list", func() { cir := seedCollection.GetComponentInstance() - notexistentProject := "NotexistentProject" + notexistentProject := notExistentProject issueComponentInstanceAttrFilterWithExpect( db.GetCcrn, &entity.ComponentInstanceFilter{ @@ -1057,10 +1070,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(c.CompareString(r.ComponentInstance.CCRN, prev)).Should(BeNumerically(">=", 0)) - prev = r.ComponentInstance.CCRN + prev = r.CCRN } }) }) @@ -1070,10 +1083,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Region, prev)).Should(BeNumerically(">=", 0)) - prev = r.ComponentInstance.Region + prev = r.Region } }) }) @@ -1083,10 +1096,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Namespace, prev)).Should(BeNumerically(">=", 0)) - prev = r.ComponentInstance.Namespace + prev = r.Namespace } }) }) @@ -1096,10 +1109,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Cluster, prev)).Should(BeNumerically(">=", 0)) - prev = r.ComponentInstance.Cluster + prev = r.Cluster } }) }) @@ -1109,10 +1122,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Domain, prev)).Should(BeNumerically(">=", 0)) - prev = r.ComponentInstance.Domain + prev = r.Domain } }) }) @@ -1122,10 +1135,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Project, prev)).Should(BeNumerically(">=", 0)) - prev = r.ComponentInstance.Project + prev = r.Project } }) }) @@ -1135,10 +1148,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Pod, prev)).Should(BeNumerically(">=", 0)) - prev = r.ComponentInstance.Pod + prev = r.Pod } }) }) @@ -1148,10 +1161,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Container, prev)).Should(BeNumerically(">=", 0)) - prev = r.ComponentInstance.Container + prev = r.Container } }) }) @@ -1161,10 +1174,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev int = -1 + prev := -1 for _, r := range res { Expect(r.ComponentInstance.Type.Index() >= prev).Should(BeTrue()) - prev = r.ComponentInstance.Type.Index() + prev = r.Type.Index() } }) }) @@ -1192,10 +1205,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(c.CompareString(r.ComponentInstance.CCRN, prev)).Should(BeNumerically("<=", 0)) - prev = r.ComponentInstance.CCRN + prev = r.CCRN } }) }) @@ -1205,10 +1218,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Region, prev)).Should(BeNumerically("<=", 0)) - prev = r.ComponentInstance.Region + prev = r.Region } }) }) @@ -1218,10 +1231,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Namespace, prev)).Should(BeNumerically("<=", 0)) - prev = r.ComponentInstance.Namespace + prev = r.Namespace } }) }) @@ -1231,10 +1244,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Cluster, prev)).Should(BeNumerically("<=", 0)) - prev = r.ComponentInstance.Cluster + prev = r.Cluster } }) }) @@ -1244,10 +1257,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Domain, prev)).Should(BeNumerically("<=", 0)) - prev = r.ComponentInstance.Domain + prev = r.Domain } }) }) @@ -1257,10 +1270,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Project, prev)).Should(BeNumerically("<=", 0)) - prev = r.ComponentInstance.Project + prev = r.Project } }) }) @@ -1270,10 +1283,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Pod, prev)).Should(BeNumerically("<=", 0)) - prev = r.ComponentInstance.Pod + prev = r.Pod } }) }) @@ -1283,10 +1296,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(c.CompareString(r.ComponentInstance.Container, prev)).Should(BeNumerically("<=", 0)) - prev = r.ComponentInstance.Container + prev = r.Container } }) }) @@ -1296,10 +1309,10 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), } testOrder(order, func(res []entity.ComponentInstanceResult) { - var prev int = math.MaxInt + prev := math.MaxInt for _, r := range res { Expect(r.ComponentInstance.Type.Index() <= prev).Should(BeTrue()) - prev = r.ComponentInstance.Type.Index() + prev = r.Type.Index() } }) }) @@ -1516,7 +1529,7 @@ var _ = Describe("ComponentInstance - ", Label("database", "ComponentInstance"), ) }) It("and using notexisting value filter returns an empty list when no Project match the filter", func() { - notexistentProject := "NotexistentProject" + notexistentProject := notExistentProject issueComponentInstanceAttrFilterWithExpect( db.GetProject, &entity.ComponentInstanceFilter{Project: []*string{¬existentProject}}, diff --git a/internal/database/mariadb/component_test.go b/internal/database/mariadb/component_test.go index 13ee8cd9a..19ac4e6d3 100644 --- a/internal/database/mariadb/component_test.go +++ b/internal/database/mariadb/component_test.go @@ -30,7 +30,7 @@ var _ = Describe("Component", Label("database", "Component"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All Component IDs", Label("GetAllComponentIds"), func() { @@ -56,6 +56,9 @@ var _ = Describe("Component", Label("database", "Component"), func() { ids = lo.Map(seedCollection.ComponentRows, func(c mariadb.ComponentRow, _ int) int64 { return c.Id.Int64 }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec randomId = ids[rand.Intn(len(ids))] }) Context("and using no filter", func() { @@ -103,6 +106,9 @@ var _ = Describe("Component", Label("database", "Component"), func() { var randomComponent mariadb.ComponentRow BeforeEach(func() { seedCollection = seeder.SeedDbWithNFakeData(10) + // nolint due to weak random number generator for test reason + // + //nolint:gosec randomComponent = seedCollection.ComponentRows[rand.Intn(len(seedCollection.ComponentRows))] }) @@ -172,6 +178,9 @@ var _ = Describe("Component", Label("database", "Component"), func() { testGetComponents(filter, []entity.Order{}, seedCollection.ComponentRows, func(entries []entity.ComponentResult) {}) }) It("can filter by a single service ccrn", func() { + // nolint due to weak random number generator for test reason + // + //nolint:gosec serviceRow := seedCollection.ServiceRows[rand.Intn(len(seedCollection.ServiceRows))] cvIds := lo.FilterMap(seedCollection.ComponentInstanceRows, func(cir mariadb.ComponentInstanceRow, _ int) (int64, bool) { @@ -251,6 +260,9 @@ var _ = Describe("Component", Label("database", "Component"), func() { BeforeEach(func() { seedCollection = seeder.SeedDbWithNFakeData(100) componentRows = seedCollection.ComponentRows + // nolint due to weak random number generator for test reason + // + //nolint:gosec randomComponent = componentRows[rand.Intn(len(componentRows))] count = len(componentRows) }) @@ -463,7 +475,7 @@ var _ = Describe("Ordering Components", Label("ComponentOrdering"), func() { }) AfterEach(func() { seeder.CloseDbConnection() - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) testOrder := func( @@ -516,7 +528,7 @@ var _ = Describe("Ordering Components", Label("ComponentOrdering"), func() { for i := 0; i < 10; i++ { issue := test.NewFakeIssue() issue.Type.String = entity.IssueTypeVulnerability.String() - seeder.InsertFakeIssue(issue) + _, _ = seeder.InsertFakeIssue(issue) } seeder.SeedComponents(5) var serviceCcrns []*string @@ -613,7 +625,7 @@ var _ = Describe("Ordering Components", Label("ComponentOrdering"), func() { } testOrder(order, func(res []entity.ComponentResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(c.CompareString(r.Repository, prev)).Should(BeNumerically(">=", 0)) prev = r.Repository @@ -649,7 +661,7 @@ var _ = Describe("Ordering Components", Label("ComponentOrdering"), func() { } testOrder(order, func(res []entity.ComponentResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(c.CompareString(r.Repository, prev)).Should(BeNumerically("<=", 0)) prev = r.Repository diff --git a/internal/database/mariadb/component_version.go b/internal/database/mariadb/component_version.go index f9e241e97..413049a21 100644 --- a/internal/database/mariadb/component_version.go +++ b/internal/database/mariadb/component_version.go @@ -15,8 +15,8 @@ import ( ) func ensureComponentVersionFilter(f *entity.ComponentVersionFilter) *entity.ComponentVersionFilter { - var first int = 1000 - var after string = "" + first := 1000 + after := "" if f == nil { return &entity.ComponentVersionFilter{ PaginatedX: entity.PaginatedX{ @@ -132,7 +132,7 @@ func (s *SqlDatabase) buildComponentVersionStatement(baseQuery string, filter *e filterStr := getComponentVersionFilterString(filter) joins := s.getComponentVersionJoins(filter, order) - cursorFields, err := DecodeCursor(filter.PaginatedX.After) + cursorFields, err := DecodeCursor(filter.After) if err != nil { return nil, nil, err } @@ -186,7 +186,7 @@ func (s *SqlDatabase) buildComponentVersionStatement(baseQuery string, filter *e filterParameters = buildQueryParameters(filterParameters, filter.ServiceId) filterParameters = buildQueryParameters(filterParameters, filter.IssueRepositoryId) if withCursor { - filterParameters = append(filterParameters, GetCursorQueryParameters(filter.PaginatedX.First, cursorFields)...) + filterParameters = append(filterParameters, GetCursorQueryParameters(filter.First, cursorFields)...) } return stmt, filterParameters, nil @@ -207,8 +207,11 @@ func (s *SqlDatabase) GetAllComponentVersionIds(filter *entity.ComponentVersionF if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performIdScan(stmt, filterParameters, l) } @@ -272,8 +275,11 @@ func (s *SqlDatabase) GetComponentVersions(filter *entity.ComponentVersionFilter if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -315,8 +321,11 @@ func (s *SqlDatabase) CountComponentVersions(filter *entity.ComponentVersionFilt if err != nil { return -1, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performCountScan(stmt, filterParameters, l) } diff --git a/internal/database/mariadb/component_version_test.go b/internal/database/mariadb/component_version_test.go index 510c18465..4370fde8c 100644 --- a/internal/database/mariadb/component_version_test.go +++ b/internal/database/mariadb/component_version_test.go @@ -16,6 +16,9 @@ import ( "github.com/samber/lo" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("ComponentVersion", Label("database", "ComponentVersion"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -26,7 +29,7 @@ var _ = Describe("ComponentVersion", Label("database", "ComponentVersion"), func Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All ComponentVersion IDs", Label("GetAllComponentVersionIds"), func() { @@ -206,6 +209,7 @@ var _ = Describe("ComponentVersion", Label("database", "ComponentVersion"), func }) It("can filter by a component id", func() { // select a component + componentRow := seedCollection.ComponentRows[rand.Intn(len(seedCollection.ComponentRows))] // collect all activity ids that belong to the component @@ -327,6 +331,7 @@ var _ = Describe("ComponentVersion", Label("database", "ComponentVersion"), func It("can filter by tag", func() { // Get an existing component version from the fixtures + cv := seedCollection.ComponentVersionRows[rand.Intn(len(seedCollection.ComponentVersionRows))] // Get the tag value directly from the fixture @@ -599,6 +604,7 @@ var _ = Describe("ComponentVersion", Label("database", "ComponentVersion"), func originalComponentId := componentVersion.ComponentId // Set a unique updated tag value + updatedTag := "updated-tag-" + fmt.Sprintf("%d", rand.Int()) componentVersion.Tag = updatedTag @@ -656,7 +662,7 @@ var _ = Describe("Ordering ComponentVersions", func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) testOrder := func( diff --git a/internal/database/mariadb/cursor.go b/internal/database/mariadb/cursor.go index 18fa4fb3d..1dad74b44 100644 --- a/internal/database/mariadb/cursor.go +++ b/internal/database/mariadb/cursor.go @@ -39,7 +39,10 @@ func EncodeCursor(opts ...NewCursor) (string, error) { if err != nil { return "", err } - encoder.Close() + if err := encoder.Close(); err != nil { + return "", fmt.Errorf("failed to close encoder: %w", err) + } + return buf.String(), nil } diff --git a/internal/database/mariadb/database.go b/internal/database/mariadb/database.go index 3561b0329..f1660752a 100644 --- a/internal/database/mariadb/database.go +++ b/internal/database/mariadb/database.go @@ -38,7 +38,11 @@ func NewSqlDatabase(cfg util.Config) (*SqlDatabase, error) { if err != nil { return nil, err } - db.Exec(fmt.Sprintf("USE %s", cfg.DBName)) + + if _, err := db.Exec(fmt.Sprintf("USE %s", cfg.DBName)); err != nil { + return nil, fmt.Errorf("failed to use specified db name: %w", err) + } + return &SqlDatabase{ db: db, defaultIssuePriority: cfg.DefaultIssuePriority, @@ -60,7 +64,7 @@ func (s *SqlDatabase) ConnectDB(dbName string) error { func (s *SqlDatabase) connectDB() error { _, err := s.db.Exec(fmt.Sprintf("CREATE SCHEMA IF NOT EXISTS %s ; USE %s", s.dbName, s.dbName)) if err != nil { - return fmt.Errorf("Could not use database '%s'. %w", s.dbName, err) + return fmt.Errorf("could not use database '%s'. %w", s.dbName, err) } return nil } @@ -170,8 +174,12 @@ func performExec[T any](s *SqlDatabase, query string, item T, l *logrus.Entry) ( }).Error(msg) return nil, fmt.Errorf("%s", msg) } + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() - defer stmt.Close() res, err := stmt.Exec(item) if err != nil { msg := err.Error() @@ -195,8 +203,12 @@ func performListScan[T DatabaseRow, E entity.HeurekaEntity | DatabaseRow](stmt S }).Error(msg) return nil, fmt.Errorf("%s", msg) } + defer func() { + if err := rows.Close(); err != nil { + l.Warnf("error during closing rows: %s", err) + } + }() - defer rows.Close() var listEntries []E for rows.Next() { var row T @@ -214,8 +226,12 @@ func performListScan[T DatabaseRow, E entity.HeurekaEntity | DatabaseRow](stmt S listEntries = listBuilder(listEntries, row) } + defer func() { + if err := rows.Close(); err != nil { + l.Warnf("error during closing rows: %s", err) + } + }() - rows.Close() l.WithFields( logrus.Fields{ "count": len(listEntries), @@ -237,7 +253,11 @@ func performIdScan(stmt Stmt, filterParameters []interface{}, l *logrus.Entry) ( return make([]int64, 0), fmt.Errorf("%s", msg) } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + l.Warnf("error during closing rows: %s", err) + } + }() var listEntries []int64 for rows.Next() { @@ -277,7 +297,11 @@ func performCountScan(stmt Stmt, filterParameters []interface{}, l *logrus.Entry return -1, fmt.Errorf("%s", msg) } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + l.Warnf("error during closing rows: %s", err) + } + }() rows.Next() var row int64 @@ -339,9 +363,10 @@ func buildStateFilterQuery(state []entity.StateFilterType, prefix string) string stateQueries = append(stateQueries, fmt.Sprintf("%s_deleted_at IS NULL", prefix)) } else { for i := range state { - if state[i] == entity.Active { + switch state[i] { + case entity.Active: stateQueries = append(stateQueries, fmt.Sprintf("%s_deleted_at IS NULL", prefix)) - } else if state[i] == entity.Deleted { + case entity.Deleted: stateQueries = append(stateQueries, fmt.Sprintf("%s_deleted_at IS NOT NULL", prefix)) } } diff --git a/internal/database/mariadb/db.go b/internal/database/mariadb/db.go index fe8f34046..2c01f4449 100644 --- a/internal/database/mariadb/db.go +++ b/internal/database/mariadb/db.go @@ -44,8 +44,10 @@ func NewDb(cfg util.Config) (Db, error) { if err != nil { return nil, err } - if cfg.DBTrace == true { + + if cfg.DBTrace { return &TraceDb{db: db}, nil } + return &QuietDb{db: db}, nil } diff --git a/internal/database/mariadb/entity.go b/internal/database/mariadb/entity.go index c4088466e..5cd1d0183 100644 --- a/internal/database/mariadb/entity.go +++ b/internal/database/mariadb/entity.go @@ -199,28 +199,28 @@ type IssueAggregationsRow struct { func (ibr *GetIssuesByRow) AsIssueWithAggregations() entity.IssueWithAggregations { return entity.IssueWithAggregations{ IssueAggregations: entity.IssueAggregations{ - Activities: lo.Max([]int64{0, GetInt64Value(ibr.IssueAggregationsRow.Activities)}), - IssueMatches: lo.Max([]int64{0, GetInt64Value(ibr.IssueAggregationsRow.IssueMatches)}), - AffectedServices: lo.Max([]int64{0, GetInt64Value(ibr.IssueAggregationsRow.AffectedServices)}), - ComponentVersions: lo.Max([]int64{0, GetInt64Value(ibr.IssueAggregationsRow.ComponentVersions)}), - AffectedComponentInstances: lo.Max([]int64{0, GetInt64Value(ibr.IssueAggregationsRow.AffectedComponentInstances)}), - EarliestTargetRemediationDate: GetTimeValue(ibr.IssueAggregationsRow.EarliestTargetRemediationDate), - EarliestDiscoveryDate: GetTimeValue(ibr.IssueAggregationsRow.EarliestDiscoveryDate), + Activities: lo.Max([]int64{0, GetInt64Value(ibr.Activities)}), + IssueMatches: lo.Max([]int64{0, GetInt64Value(ibr.IssueMatches)}), + AffectedServices: lo.Max([]int64{0, GetInt64Value(ibr.AffectedServices)}), + ComponentVersions: lo.Max([]int64{0, GetInt64Value(ibr.ComponentVersions)}), + AffectedComponentInstances: lo.Max([]int64{0, GetInt64Value(ibr.AffectedComponentInstances)}), + EarliestTargetRemediationDate: GetTimeValue(ibr.EarliestTargetRemediationDate), + EarliestDiscoveryDate: GetTimeValue(ibr.EarliestDiscoveryDate), }, Issue: entity.Issue{ - Id: GetInt64Value(ibr.IssueRow.Id), - PrimaryName: GetStringValue(ibr.IssueRow.PrimaryName), + Id: GetInt64Value(ibr.Id), + PrimaryName: GetStringValue(ibr.PrimaryName), Type: entity.NewIssueType(GetStringValue(ibr.Type)), - Description: GetStringValue(ibr.IssueRow.Description), + Description: GetStringValue(ibr.Description), IssueVariants: []entity.IssueVariant{}, IssueMatches: []entity.IssueMatch{}, Activity: []entity.Activity{}, Metadata: entity.Metadata{ - CreatedAt: GetTimeValue(ibr.IssueRow.CreatedAt), - CreatedBy: GetInt64Value(ibr.IssueRow.CreatedBy), - DeletedAt: GetTimeValue(ibr.IssueRow.DeletedAt), - UpdatedAt: GetTimeValue(ibr.IssueRow.UpdatedAt), - UpdatedBy: GetInt64Value(ibr.IssueRow.UpdatedBy), + CreatedAt: GetTimeValue(ibr.CreatedAt), + CreatedBy: GetInt64Value(ibr.CreatedBy), + DeletedAt: GetTimeValue(ibr.DeletedAt), + UpdatedAt: GetTimeValue(ibr.UpdatedAt), + UpdatedBy: GetInt64Value(ibr.UpdatedBy), }, }, } @@ -228,19 +228,19 @@ func (ibr *GetIssuesByRow) AsIssueWithAggregations() entity.IssueWithAggregation func (ibr *GetIssuesByRow) AsIssue() entity.Issue { return entity.Issue{ - Id: GetInt64Value(ibr.IssueRow.Id), - PrimaryName: GetStringValue(ibr.IssueRow.PrimaryName), + Id: GetInt64Value(ibr.Id), + PrimaryName: GetStringValue(ibr.PrimaryName), Type: entity.NewIssueType(GetStringValue(ibr.Type)), - Description: GetStringValue(ibr.IssueRow.Description), + Description: GetStringValue(ibr.Description), IssueVariants: []entity.IssueVariant{}, IssueMatches: []entity.IssueMatch{}, Activity: []entity.Activity{}, Metadata: entity.Metadata{ - CreatedAt: GetTimeValue(ibr.IssueRow.CreatedAt), - CreatedBy: GetInt64Value(ibr.IssueRow.CreatedBy), - DeletedAt: GetTimeValue(ibr.IssueRow.DeletedAt), - UpdatedAt: GetTimeValue(ibr.IssueRow.UpdatedAt), - UpdatedBy: GetInt64Value(ibr.IssueRow.UpdatedBy), + CreatedAt: GetTimeValue(ibr.CreatedAt), + CreatedBy: GetInt64Value(ibr.CreatedBy), + DeletedAt: GetTimeValue(ibr.DeletedAt), + UpdatedAt: GetTimeValue(ibr.UpdatedAt), + UpdatedBy: GetInt64Value(ibr.UpdatedBy), }, } } @@ -332,6 +332,9 @@ func (imr *IssueMatchRow) FromIssueMatch(im *entity.IssueMatch) { imr.UpdatedBy = sql.NullInt64{Int64: im.UpdatedBy, Valid: true} } +// nolint due to embedding structures with the same fields +// +//nolint:govet type IssueRepositoryRow struct { BaseIssueRepositoryRow IssueRepositoryServiceRow @@ -356,10 +359,10 @@ func (irr *IssueRepositoryRow) FromIssueRepository(ir *entity.IssueRepository) { irr.ServiceId = sql.NullInt64{Int64: ir.ServiceId, Valid: true} irr.IssueRepositoryId = sql.NullInt64{Int64: ir.IssueRepositoryId, Valid: true} irr.BaseIssueRepositoryRow.CreatedAt = sql.NullTime{Time: ir.BaseIssueRepository.CreatedAt, Valid: true} - irr.BaseIssueRepositoryRow.CreatedBy = sql.NullInt64{Int64: ir.BaseIssueRepository.CreatedBy, Valid: true} + irr.CreatedBy = sql.NullInt64{Int64: ir.BaseIssueRepository.CreatedBy, Valid: true} irr.BaseIssueRepositoryRow.DeletedAt = sql.NullTime{Time: ir.BaseIssueRepository.DeletedAt, Valid: true} irr.BaseIssueRepositoryRow.UpdatedAt = sql.NullTime{Time: ir.BaseIssueRepository.UpdatedAt, Valid: true} - irr.BaseIssueRepositoryRow.UpdatedBy = sql.NullInt64{Int64: ir.BaseIssueRepository.UpdatedBy, Valid: true} + irr.UpdatedBy = sql.NullInt64{Int64: ir.BaseIssueRepository.UpdatedBy, Valid: true} } func (birr *BaseIssueRepositoryRow) AsBaseIssueRepository() entity.BaseIssueRepository { @@ -408,10 +411,10 @@ func (irr *IssueRepositoryRow) AsIssueRepository() entity.IssueRepository { Services: nil, Metadata: entity.Metadata{ CreatedAt: GetTimeValue(irr.BaseIssueRepositoryRow.CreatedAt), - CreatedBy: GetInt64Value(irr.BaseIssueRepositoryRow.CreatedBy), + CreatedBy: GetInt64Value(irr.CreatedBy), DeletedAt: GetTimeValue(irr.BaseIssueRepositoryRow.DeletedAt), UpdatedAt: GetTimeValue(irr.BaseIssueRepositoryRow.UpdatedAt), - UpdatedBy: GetInt64Value(irr.BaseIssueRepositoryRow.UpdatedBy), + UpdatedBy: GetInt64Value(irr.UpdatedBy), }, }, IssueRepositoryService: entity.IssueRepositoryService{ @@ -483,13 +486,16 @@ func (ivr *IssueVariantRow) FromIssueVariant(iv *entity.IssueVariant) { ivr.UpdatedBy = sql.NullInt64{Int64: iv.UpdatedBy, Valid: true} } +// nolint due to embedding structures with the same fields +// +//nolint:govet type IssueVariantWithRepository struct { IssueRepositoryRow IssueVariantRow } func (ivwr *IssueVariantWithRepository) AsIssueVariantEntry() entity.IssueVariant { - rep := ivwr.IssueRepositoryRow.AsIssueRepository() + rep := ivwr.AsIssueRepository() var severity entity.Severity if ivwr.Vector.String == "" { @@ -499,32 +505,35 @@ func (ivwr *IssueVariantWithRepository) AsIssueVariantEntry() entity.IssueVarian } return entity.IssueVariant{ - Id: GetInt64Value(ivwr.IssueVariantRow.Id), + Id: GetInt64Value(ivwr.Id), IssueRepositoryId: GetInt64Value(ivwr.IssueRepositoryId), IssueRepository: &rep, - SecondaryName: GetStringValue(ivwr.IssueVariantRow.SecondaryName), + SecondaryName: GetStringValue(ivwr.SecondaryName), IssueId: GetInt64Value(ivwr.IssueId), Issue: nil, Severity: severity, Description: GetStringValue(ivwr.Description), ExternalUrl: GetStringValue(ivwr.ExternalUrl), Metadata: entity.Metadata{ - CreatedAt: GetTimeValue(ivwr.IssueVariantRow.CreatedAt), + CreatedAt: GetTimeValue(ivwr.CreatedAt), CreatedBy: GetInt64Value(ivwr.CreatedBy), - DeletedAt: GetTimeValue(ivwr.IssueVariantRow.DeletedAt), - UpdatedAt: GetTimeValue(ivwr.IssueVariantRow.UpdatedAt), + DeletedAt: GetTimeValue(ivwr.DeletedAt), + UpdatedAt: GetTimeValue(ivwr.UpdatedAt), UpdatedBy: GetInt64Value(ivwr.UpdatedBy), }, } } +// nolint due to embedding structures with the same fields +// +//nolint:govet type ServiceIssueVariantRow struct { IssueRepositoryRow IssueVariantRow } func (siv *ServiceIssueVariantRow) AsServiceIssueVariantEntry() entity.ServiceIssueVariant { - rep := siv.IssueRepositoryRow.AsIssueRepository() + rep := siv.AsIssueRepository() var severity entity.Severity if siv.Vector.String == "" { @@ -535,23 +544,23 @@ func (siv *ServiceIssueVariantRow) AsServiceIssueVariantEntry() entity.ServiceIs return entity.ServiceIssueVariant{ IssueVariant: entity.IssueVariant{ - Id: GetInt64Value(siv.IssueVariantRow.Id), + Id: GetInt64Value(siv.Id), IssueRepositoryId: GetInt64Value(siv.IssueRepositoryRow.IssueRepositoryId), IssueRepository: &rep, - SecondaryName: GetStringValue(siv.IssueVariantRow.SecondaryName), + SecondaryName: GetStringValue(siv.SecondaryName), IssueId: GetInt64Value(siv.IssueId), Issue: nil, Severity: severity, Description: GetStringValue(siv.Description), Metadata: entity.Metadata{ - CreatedAt: GetTimeValue(siv.IssueVariantRow.CreatedAt), + CreatedAt: GetTimeValue(siv.CreatedAt), CreatedBy: GetInt64Value(siv.CreatedBy), - DeletedAt: GetTimeValue(siv.IssueVariantRow.DeletedAt), - UpdatedAt: GetTimeValue(siv.IssueVariantRow.UpdatedAt), + DeletedAt: GetTimeValue(siv.DeletedAt), + UpdatedAt: GetTimeValue(siv.UpdatedAt), UpdatedBy: GetInt64Value(siv.UpdatedBy), }, }, - ServiceId: GetInt64Value(siv.IssueRepositoryServiceRow.ServiceId), + ServiceId: GetInt64Value(siv.ServiceId), Priority: GetInt64Value(siv.Priority), } } @@ -682,6 +691,9 @@ func (sgr *SupportGroupRow) FromSupportGroup(sg *entity.SupportGroup) { sgr.UpdatedBy = sql.NullInt64{Int64: sg.UpdatedBy, Valid: true} } +// nolint due to embedding structures with the same fields +// +//nolint:govet type ServiceRow struct { BaseServiceRow IssueRepositoryServiceRow @@ -735,10 +747,10 @@ func (sr *ServiceRow) AsService() entity.Service { Activities: []entity.Activity{}, Metadata: entity.Metadata{ CreatedAt: GetTimeValue(sr.BaseServiceRow.CreatedAt), - CreatedBy: GetInt64Value(sr.BaseServiceRow.CreatedBy), + CreatedBy: GetInt64Value(sr.CreatedBy), DeletedAt: GetTimeValue(sr.BaseServiceRow.DeletedAt), UpdatedAt: GetTimeValue(sr.BaseServiceRow.UpdatedAt), - UpdatedBy: GetInt64Value(sr.BaseServiceRow.UpdatedBy), + UpdatedBy: GetInt64Value(sr.UpdatedBy), }, }, IssueRepositoryService: entity.IssueRepositoryService{ @@ -755,12 +767,15 @@ func (sr *ServiceRow) FromService(s *entity.Service) { sr.Domain = sql.NullString{String: s.Domain, Valid: true} sr.Region = sql.NullString{String: s.Region, Valid: true} sr.BaseServiceRow.CreatedAt = sql.NullTime{Time: s.BaseService.CreatedAt, Valid: true} - sr.BaseServiceRow.CreatedBy = sql.NullInt64{Int64: s.BaseService.CreatedBy, Valid: true} + sr.CreatedBy = sql.NullInt64{Int64: s.BaseService.CreatedBy, Valid: true} sr.BaseServiceRow.DeletedAt = sql.NullTime{Time: s.BaseService.DeletedAt, Valid: true} sr.BaseServiceRow.UpdatedAt = sql.NullTime{Time: s.BaseService.UpdatedAt, Valid: true} - sr.BaseServiceRow.UpdatedBy = sql.NullInt64{Int64: s.BaseService.UpdatedBy, Valid: true} + sr.UpdatedBy = sql.NullInt64{Int64: s.BaseService.UpdatedBy, Valid: true} } +// nolint due to embedding structures with the same fields +// +//nolint:govet type GetServicesByRow struct { ServiceAggregationsRow ServiceRow @@ -774,29 +789,29 @@ type ServiceAggregationsRow struct { func (sbr *GetServicesByRow) AsServiceWithAggregations() entity.ServiceWithAggregations { return entity.ServiceWithAggregations{ ServiceAggregations: entity.ServiceAggregations{ - ComponentInstances: lo.Max([]int64{0, GetInt64Value(sbr.ServiceAggregationsRow.ComponentInstances)}), - IssueMatches: lo.Max([]int64{0, GetInt64Value(sbr.ServiceAggregationsRow.IssueMatches)}), + ComponentInstances: lo.Max([]int64{0, GetInt64Value(sbr.ComponentInstances)}), + IssueMatches: lo.Max([]int64{0, GetInt64Value(sbr.IssueMatches)}), }, Service: entity.Service{ BaseService: entity.BaseService{ - Id: GetInt64Value(sbr.BaseServiceRow.Id), - CCRN: GetStringValue(sbr.BaseServiceRow.CCRN), - Domain: GetStringValue(sbr.BaseServiceRow.Domain), - Region: GetStringValue(sbr.BaseServiceRow.Region), + Id: GetInt64Value(sbr.Id), + CCRN: GetStringValue(sbr.CCRN), + Domain: GetStringValue(sbr.Domain), + Region: GetStringValue(sbr.Region), Owners: []entity.User{}, Activities: []entity.Activity{}, Metadata: entity.Metadata{ CreatedAt: GetTimeValue(sbr.BaseServiceRow.CreatedAt), - CreatedBy: GetInt64Value(sbr.BaseServiceRow.CreatedBy), + CreatedBy: GetInt64Value(sbr.CreatedBy), DeletedAt: GetTimeValue(sbr.BaseServiceRow.DeletedAt), UpdatedAt: GetTimeValue(sbr.BaseServiceRow.UpdatedAt), - UpdatedBy: GetInt64Value(sbr.BaseServiceRow.UpdatedBy), + UpdatedBy: GetInt64Value(sbr.UpdatedBy), }, }, IssueRepositoryService: entity.IssueRepositoryService{ - ServiceId: GetInt64Value(sbr.IssueRepositoryServiceRow.ServiceId), - IssueRepositoryId: GetInt64Value(sbr.IssueRepositoryServiceRow.IssueRepositoryId), - Priority: GetInt64Value(sbr.IssueRepositoryServiceRow.Priority), + ServiceId: GetInt64Value(sbr.ServiceId), + IssueRepositoryId: GetInt64Value(sbr.IssueRepositoryId), + Priority: GetInt64Value(sbr.Priority), }, }, } diff --git a/internal/database/mariadb/evidence.go b/internal/database/mariadb/evidence.go index c17df8694..7d054be50 100644 --- a/internal/database/mariadb/evidence.go +++ b/internal/database/mariadb/evidence.go @@ -12,7 +12,7 @@ import ( ) func ensureEvidenceFilter(f *entity.EvidenceFilter) *entity.EvidenceFilter { - var first int = 1000 + first := 1000 var after int64 = 0 if f == nil { return &entity.EvidenceFilter{ @@ -144,8 +144,11 @@ func (s *SqlDatabase) GetAllEvidenceIds(filter *entity.EvidenceFilter) ([]int64, if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performIdScan(stmt, filterParameters, l) } @@ -169,8 +172,11 @@ func (s *SqlDatabase) GetEvidences(filter *entity.EvidenceFilter) ([]entity.Evid if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -196,8 +202,11 @@ func (s *SqlDatabase) CountEvidences(filter *entity.EvidenceFilter) (int64, erro if err != nil { return -1, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performCountScan(stmt, filterParameters, l) } diff --git a/internal/database/mariadb/evidence_test.go b/internal/database/mariadb/evidence_test.go index ac9145323..19b3e3350 100644 --- a/internal/database/mariadb/evidence_test.go +++ b/internal/database/mariadb/evidence_test.go @@ -17,6 +17,9 @@ import ( . "github.com/onsi/gomega" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("Evidence", Label("database", "Evidence"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -27,7 +30,7 @@ var _ = Describe("Evidence", Label("database", "Evidence"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All Evidence IDs", Label("GetAllEvidenceIds"), func() { diff --git a/internal/database/mariadb/issue.go b/internal/database/mariadb/issue.go index 21b5a9f00..daff6ce41 100644 --- a/internal/database/mariadb/issue.go +++ b/internal/database/mariadb/issue.go @@ -21,7 +21,7 @@ const ( func buildIssueFilterParametersWithCursor(filter *entity.IssueFilter, cursorFields []Field) []interface{} { filterParameters := buildIssueFilterParameters(filter, cursorFields) - filterParameters = append(filterParameters, GetCursorQueryParameters(filter.PaginatedX.First, cursorFields)...) + filterParameters = append(filterParameters, GetCursorQueryParameters(filter.First, cursorFields)...) return filterParameters } @@ -119,10 +119,15 @@ func getIssueJoins(filter *entity.IssueFilter, order []entity.Order) string { LEFT JOIN ComponentVersionIssue CVI ON I.issue_id = CVI.componentversionissue_issue_id `) - if len(filter.ComponentId) > 0 && !(len(filter.ServiceId) > 0 || len(filter.ServiceCCRN) > 0 || len(filter.SupportGroupCCRN) > 0 || filter.AllServices) { + if len(filter.ComponentId) > 0 && + len(filter.ServiceId) == 0 && + len(filter.ServiceCCRN) == 0 && + len(filter.SupportGroupCCRN) == 0 && + !filter.AllServices { + joins = fmt.Sprintf("%s\n%s", joins, ` - LEFT JOIN ComponentVersion CV ON CVI.componentversionissue_component_version_id = CV.componentversion_id - `) + LEFT JOIN ComponentVersion CV ON CVI.componentversionissue_component_version_id = CV.componentversion_id + `) } } @@ -148,7 +153,7 @@ func getIssueJoins(filter *entity.IssueFilter, order []entity.Order) string { func ensureIssueFilter(f *entity.IssueFilter) *entity.IssueFilter { first := 1000 - var after string = "" + after := "" if f == nil { return &entity.IssueFilter{ PaginatedX: entity.PaginatedX{ @@ -198,8 +203,7 @@ func getIssueUpdateFields(issue *entity.Issue) string { func getIssueColumns(order []entity.Order) string { columns := "" for _, o := range order { - switch o.By { - case entity.IssueVariantRating: + if o.By == entity.IssueVariantRating { columns = fmt.Sprintf("%s, MAX(CAST(IV.issuevariant_rating AS UNSIGNED)) AS issuevariant_rating_num", columns) } } @@ -246,7 +250,7 @@ func (s *SqlDatabase) buildIssueStatementWithCursor(baseQuery string, filter *en ifilter := ensureIssueFilter(filter) l.WithFields(logrus.Fields{"filter": ifilter}) - cursorFields, err := DecodeCursor(ifilter.PaginatedX.After) + cursorFields, err := DecodeCursor(ifilter.After) if err != nil { return nil, nil, err } @@ -276,7 +280,7 @@ func (s *SqlDatabase) buildIssueStatement(baseQuery string, filter *entity.Issue ifilter := ensureIssueFilter(filter) l.WithFields(logrus.Fields{"filter": ifilter}) - cursorFields, err := DecodeCursor(ifilter.PaginatedX.After) + cursorFields, err := DecodeCursor(ifilter.After) if err != nil { return nil, nil, err } @@ -355,7 +359,7 @@ func (s *SqlDatabase) GetIssuesWithAggregations(filter *entity.IssueFilter, orde filter = ensureIssueFilter(filter) filterStr := getIssueFilterString(filter) joins := getIssueJoins(filter, order) - cursorFields, err := DecodeCursor(filter.PaginatedX.After) + cursorFields, err := DecodeCursor(filter.After) if err != nil { return nil, err } @@ -391,8 +395,11 @@ func (s *SqlDatabase) GetIssuesWithAggregations(filter *entity.IssueFilter, orde filterParameters := buildIssueFilterParametersWithCursor(filter, cursorFields) // parameters for agg query filterParameters = append(filterParameters, buildIssueFilterParametersWithCursor(filter, cursorFields)...) - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -407,7 +414,7 @@ func (s *SqlDatabase) GetIssuesWithAggregations(filter *entity.IssueFilter, orde var ivRating int64 if e.IssueVariantRow != nil { - ivRating = e.IssueVariantRow.RatingNumerical.Int64 + ivRating = e.RatingNumerical.Int64 } cursor, _ := EncodeCursor(WithIssue(defaultOrder, issue.Issue, ivRating)) @@ -439,8 +446,11 @@ func (s *SqlDatabase) CountIssues(filter *entity.IssueFilter) (int64, error) { if err != nil { return -1, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performCountScan(stmt, filterParameters, l) } @@ -461,8 +471,11 @@ func (s *SqlDatabase) CountIssueTypes(filter *entity.IssueFilter) (*entity.Issue if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() counts, err := performListScan( stmt, @@ -506,8 +519,11 @@ func (s *SqlDatabase) GetAllIssueIds(filter *entity.IssueFilter) ([]int64, error if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performIdScan(stmt, filterParameters, l) } @@ -528,8 +544,11 @@ func (s *SqlDatabase) GetAllIssueCursors(filter *entity.IssueFilter, order []ent if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() rows, err := performListScan( stmt, @@ -547,7 +566,7 @@ func (s *SqlDatabase) GetAllIssueCursors(filter *entity.IssueFilter, order []ent issue := row.IssueRow.AsIssue() var ivRating int64 if row.IssueVariantRow != nil { - ivRating = row.IssueVariantRow.RatingNumerical.Int64 + ivRating = row.RatingNumerical.Int64 } cursor, _ := EncodeCursor(WithIssue(order, issue, ivRating)) @@ -574,8 +593,11 @@ func (s *SqlDatabase) GetIssues(filter *entity.IssueFilter, order []entity.Order if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -586,7 +608,7 @@ func (s *SqlDatabase) GetIssues(filter *entity.IssueFilter, order []entity.Order var ivRating int64 if e.IssueVariantRow != nil { - ivRating = e.IssueVariantRow.RatingNumerical.Int64 + ivRating = e.RatingNumerical.Int64 } cursor, _ := EncodeCursor(WithIssue(order, issue, ivRating)) @@ -789,7 +811,11 @@ func (s *SqlDatabase) GetIssueNames(filter *entity.IssueFilter) ([]string, error l.Error("Error preparing statement: ", err) return nil, err } - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() // Execute the query rows, err := stmt.Queryx(filterParameters...) @@ -797,7 +823,11 @@ func (s *SqlDatabase) GetIssueNames(filter *entity.IssueFilter) ([]string, error l.Error("Error executing query: ", err) return nil, err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + l.Warnf("error during closing rows: %s", err) + } + }() // Collect the results issueNames := []string{} diff --git a/internal/database/mariadb/issue_match.go b/internal/database/mariadb/issue_match.go index 8bb38e248..7870b0756 100644 --- a/internal/database/mariadb/issue_match.go +++ b/internal/database/mariadb/issue_match.go @@ -18,7 +18,7 @@ func ensureIssueMatchFilter(f *entity.IssueMatchFilter) *entity.IssueMatchFilter } first := 1000 - var after string = "" + after := "" return &entity.IssueMatchFilter{ PaginatedX: entity.PaginatedX{ First: &first, @@ -163,7 +163,7 @@ func (s *SqlDatabase) buildIssueMatchStatement(baseQuery string, filter *entity. l.WithFields(logrus.Fields{"filter": filter}) filterStr := getIssueMatchFilterString(filter) - cursorFields, err := DecodeCursor(filter.PaginatedX.After) + cursorFields, err := DecodeCursor(filter.After) if err != nil { return nil, nil, err } @@ -222,7 +222,7 @@ func (s *SqlDatabase) buildIssueMatchStatement(baseQuery string, filter *entity. filterParameters = buildQueryParametersCount(filterParameters, filter.Search, wildCardFilterParamCount) if withCursor { - filterParameters = append(filterParameters, GetCursorQueryParameters(filter.PaginatedX.First, cursorFields)...) + filterParameters = append(filterParameters, GetCursorQueryParameters(filter.First, cursorFields)...) } return stmt, filterParameters, nil @@ -283,7 +283,7 @@ func (s *SqlDatabase) GetAllIssueMatchCursors(filter *entity.IssueMatchFilter, o im.Issue = lo.ToPtr(row.IssueRow.AsIssue()) } if row.ComponentInstanceRow != nil { - im.ComponentInstance = lo.ToPtr(row.ComponentInstanceRow.AsComponentInstance()) + im.ComponentInstance = lo.ToPtr(row.AsComponentInstance()) } cursor, _ := EncodeCursor(WithIssueMatch(order, im)) @@ -308,8 +308,11 @@ func (s *SqlDatabase) GetIssueMatches(filter *entity.IssueMatchFilter, order []e if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -321,7 +324,7 @@ func (s *SqlDatabase) GetIssueMatches(filter *entity.IssueMatchFilter, order []e im.Issue = lo.ToPtr(e.IssueRow.AsIssue()) } if e.ComponentInstanceRow != nil { - im.ComponentInstance = lo.ToPtr(e.ComponentInstanceRow.AsComponentInstance()) + im.ComponentInstance = lo.ToPtr(e.AsComponentInstance()) } cursor, _ := EncodeCursor(WithIssueMatch(order, im)) diff --git a/internal/database/mariadb/issue_match_test.go b/internal/database/mariadb/issue_match_test.go index 58d413205..80bf3cfa3 100644 --- a/internal/database/mariadb/issue_match_test.go +++ b/internal/database/mariadb/issue_match_test.go @@ -19,6 +19,9 @@ import ( . "github.com/onsi/gomega" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("IssueMatch", Label("database", "IssueMatch"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -29,7 +32,7 @@ var _ = Describe("IssueMatch", Label("database", "IssueMatch"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All IssueMatch IDs", Label("GetAllIssueMatchIds"), func() { Context("and the database is empty", func() { @@ -106,6 +109,9 @@ var _ = Describe("IssueMatch", Label("database", "IssueMatch"), func() { }) }) It("can filter by a single issue id that does exist", func() { + // nolint due to weak random number generator for test reason + // + //nolint:gosec issueMatch := seedCollection.IssueMatchRows[rand.Intn(len(seedCollection.IssueMatchRows))] filter := &entity.IssueMatchFilter{ PaginatedX: entity.PaginatedX{}, @@ -497,7 +503,7 @@ var _ = Describe("IssueMatch", Label("database", "IssueMatch"), func() { }) It("does not influence the count when pagination is applied", func() { first := 1 - var after string = "" + after := "" filter := &entity.IssueMatchFilter{ PaginatedX: entity.PaginatedX{ First: &first, @@ -548,6 +554,10 @@ var _ = Describe("IssueMatch", Label("database", "IssueMatch"), func() { var user entity.User var issue entity.Issue var componentInstance entity.ComponentInstance + + // nolint due to weak random number generator for test reason + // + //nolint:gosec BeforeEach(func() { seeder.SeedDbWithNFakeData(10) seedCollection = seeder.SeedDbWithNFakeData(10) @@ -753,7 +763,7 @@ var _ = Describe("Ordering IssueMatches", func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) testOrder := func( @@ -809,7 +819,7 @@ var _ = Describe("Ordering IssueMatches", func() { } testOrder(order, func(res []entity.IssueMatchResult) { - var prev string = "" + prev := "" for _, r := range res { issue := seedCollection.GetIssueById(r.IssueId) Expect(issue).ShouldNot(BeNil()) @@ -829,7 +839,7 @@ var _ = Describe("Ordering IssueMatches", func() { } testOrder(order, func(res []entity.IssueMatchResult) { - var prev time.Time = time.Time{} + prev := time.Time{} for _, r := range res { Expect(r.TargetRemediationDate.After(prev)).Should(BeTrue()) prev = r.TargetRemediationDate @@ -868,7 +878,7 @@ var _ = Describe("Ordering IssueMatches", func() { } testOrder(order, func(res []entity.IssueMatchResult) { - var prev string = "" + prev := "" for _, r := range res { ci := seedCollection.GetComponentInstanceById(r.ComponentInstanceId) Expect(ci).ShouldNot(BeNil()) @@ -912,7 +922,7 @@ var _ = Describe("Ordering IssueMatches", func() { } testOrder(order, func(res []entity.IssueMatchResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { issue := seedCollection.GetIssueById(r.IssueId) Expect(issue).ShouldNot(BeNil()) @@ -932,7 +942,7 @@ var _ = Describe("Ordering IssueMatches", func() { } testOrder(order, func(res []entity.IssueMatchResult) { - var prev time.Time = time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC) + prev := time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC) for _, r := range res { Expect(r.TargetRemediationDate.Before(prev)).Should(BeTrue()) prev = r.TargetRemediationDate @@ -971,7 +981,7 @@ var _ = Describe("Ordering IssueMatches", func() { } testOrder(order, func(res []entity.IssueMatchResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { ci := seedCollection.GetComponentInstanceById(r.ComponentInstanceId) Expect(ci).ShouldNot(BeNil()) @@ -1005,7 +1015,7 @@ var _ = Describe("Ordering IssueMatches", func() { } testOrder(order, func(res []entity.IssueMatchResult) { - var prevTrd time.Time = time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC) + prevTrd := time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC) prevPn := "" for _, r := range res { issue := seedCollection.GetIssueById(r.IssueId) @@ -1028,7 +1038,7 @@ var _ = Describe("Ordering IssueMatches", func() { } testOrder(order, func(res []entity.IssueMatchResult) { - var prevTrd time.Time = time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC) + prevTrd := time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC) prevPn := "" for _, r := range res { issue := seedCollection.GetIssueById(r.IssueId) @@ -1054,7 +1064,7 @@ var _ = Describe("Ordering IssueMatches", func() { testOrder(order, func(res []entity.IssueMatchResult) { prevSeverity := 0 prevCiCcrn := "" - var prevTrd time.Time = time.Time{} + prevTrd := time.Time{} for _, r := range res { ci := seedCollection.GetComponentInstanceById(r.ComponentInstanceId) if test.SeverityToNumerical(r.Severity.Value) == prevSeverity { @@ -1088,7 +1098,7 @@ var _ = Describe("Using the Cursor on IssueMatches", func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) loadTestData := func() ([]mariadb.IssueMatchRow, []mariadb.IssueRow, []mariadb.ComponentInstanceRow, error) { matches, err := test.LoadIssueMatches(test.GetTestDataPath("testdata/issue_match_cursor/issue_match.json")) diff --git a/internal/database/mariadb/issue_repository.go b/internal/database/mariadb/issue_repository.go index e63558601..51b4dd735 100644 --- a/internal/database/mariadb/issue_repository.go +++ b/internal/database/mariadb/issue_repository.go @@ -60,7 +60,7 @@ func (s *SqlDatabase) getIssueRepositoryColumns(filter *entity.IssueRepositoryFi } func ensureIssueRepositoryFilter(f *entity.IssueRepositoryFilter) *entity.IssueRepositoryFilter { - var first int = 1000 + first := 1000 var after int64 = 0 if f == nil { return &entity.IssueRepositoryFilter{ @@ -146,8 +146,11 @@ func (s *SqlDatabase) GetAllIssueRepositoryIds(filter *entity.IssueRepositoryFil if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performIdScan(stmt, filterParameters, l) } @@ -172,8 +175,11 @@ func (s *SqlDatabase) GetIssueRepositories(filter *entity.IssueRepositoryFilter) if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -199,8 +205,11 @@ func (s *SqlDatabase) CountIssueRepositories(filter *entity.IssueRepositoryFilte if err != nil { return -1, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performCountScan(stmt, filterParameters, l) } diff --git a/internal/database/mariadb/issue_repository_test.go b/internal/database/mariadb/issue_repository_test.go index f65461bbf..7f8e29862 100644 --- a/internal/database/mariadb/issue_repository_test.go +++ b/internal/database/mariadb/issue_repository_test.go @@ -15,6 +15,9 @@ import ( "github.com/samber/lo" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("IssueRepository", Label("database", "IssueRepository"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -25,7 +28,7 @@ var _ = Describe("IssueRepository", Label("database", "IssueRepository"), func() Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All IssueRepository IDs", Label("GetAllIssueRepositoryIds"), func() { diff --git a/internal/database/mariadb/issue_test.go b/internal/database/mariadb/issue_test.go index c5035029c..0b194847a 100644 --- a/internal/database/mariadb/issue_test.go +++ b/internal/database/mariadb/issue_test.go @@ -21,6 +21,9 @@ import ( "github.com/samber/lo" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("Issue", Label("database", "Issue"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -31,7 +34,7 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All Issue IDs", Label("GetAllIssueIds"), func() { @@ -87,6 +90,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { }) }) Context("and using a filter", func() { + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter by a single issue id that does exist", func() { issueId := ids[rand.Intn(len(ids))] filter := &entity.IssueFilter{ @@ -167,6 +173,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { }) }) Context("and using a filter", func() { + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter by a single service name", func() { var row mariadb.BaseServiceRow searchingRow := true @@ -225,6 +234,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { Expect(len(entries)).To(BeEquivalentTo(len(expectedIssues))) }) }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter by a single issue Id", func() { row := seedCollection.IssueRows[rand.Intn(len(seedCollection.IssueRows))] filter := &entity.IssueFilter{Id: []*int64{&row.Id.Int64}} @@ -243,6 +255,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { Expect(entries[0].Issue.Id).To(BeEquivalentTo(row.Id.Int64)) }) }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter by a single service Id", func() { serviceRow := seedCollection.ServiceRows[rand.Intn(len(seedCollection.ServiceRows))] ciIds := lo.FilterMap(seedCollection.ComponentInstanceRows, func(c mariadb.ComponentInstanceRow, _ int) (int64, bool) { @@ -266,6 +281,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { } }) }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter by a single support group ccrn", func() { sgRow := seedCollection.SupportGroupRows[rand.Intn(len(seedCollection.SupportGroupRows))] serviceIds := lo.FilterMap(seedCollection.SupportGroupServiceRows, func(sgs mariadb.SupportGroupServiceRow, _ int) (int64, bool) { @@ -292,6 +310,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { } }) }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter by a single activity id", func() { // select an activity activityRow := seedCollection.ActivityRows[rand.Intn(len(seedCollection.ActivityRows))] @@ -318,6 +339,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { } }) }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter by a single component version id", func() { // select a componentVersion cvRow := seedCollection.ComponentVersionRows[rand.Intn(len(seedCollection.ComponentVersionRows))] @@ -344,6 +368,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { } }) }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter by a single component id", func() { // select a component cRow := seedCollection.ComponentRows[rand.Intn(len(seedCollection.ComponentRows))] @@ -378,6 +405,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { } }) }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter by a single issueVariant id", func() { // select an issueVariant issueVariantRow := seedCollection.IssueVariantRows[rand.Intn(len(seedCollection.IssueVariantRows))] @@ -399,6 +429,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { Expect(issueIds).To(ContainElement(issueVariantRow.IssueId.Int64)) }) }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter by a issueType", func() { issueType := entity.AllIssueTypes[rand.Intn(len(entity.AllIssueTypes))] @@ -427,6 +460,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { Expect(hasMatch).To(BeTrue(), "Entry should have at least one matching IssueMatchRow") } }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter by issueMatch severity", func() { for _, severity := range entity.AllSeverityValues { issueIds := lo.FilterMap(seedCollection.IssueMatchRows, func(im mariadb.IssueMatchRow, _ int) (int64, bool) { @@ -443,6 +479,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { } } }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter issue PrimaryName using wild card search", func() { row := seedCollection.IssueRows[rand.Intn(len(seedCollection.IssueRows))] @@ -477,6 +516,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { Expect(issueIds).To(ContainElement(row.Id.Int64)) }) }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec It("can filter issue variant SecondaryName using wild card search", func() { // select an issueVariant issueVariantRow := seedCollection.IssueVariantRows[rand.Intn(len(seedCollection.IssueVariantRows))] @@ -508,6 +550,9 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { Expect(issueIds).To(ContainElement(issueVariantRow.IssueId.Int64)) }) }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec When("filtered by IssueStatus", func() { var remediation entity.Remediation BeforeEach(func() { @@ -591,7 +636,7 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { BeforeEach(func() { newIssueRow := test.NewFakeIssue() newIssue := newIssueRow.AsIssue() - db.CreateIssue(&newIssue) + _, _ = db.CreateIssue(&newIssue) }) It("returns the issues with aggregations", func() { entriesWithAggregations, err := db.GetIssuesWithAggregations(nil, nil) @@ -638,7 +683,7 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { }) }) It("returns correct aggregation values", func() { - //Should be filled with a check for each aggregation value, + // Should be filled with a check for each aggregation value, // this is currently skipped due to the complexity of the test implementation // as we would need to implement for each of the aggregations a manual aggregation // based on the seederCollection. @@ -710,7 +755,7 @@ var _ = Describe("Issue", Label("database", "Issue"), func() { }) It("does not influence the count when pagination is applied", func() { first := 1 - var after string = "" + after := "" filter := &entity.IssueFilter{ PaginatedX: entity.PaginatedX{ First: &first, @@ -1084,7 +1129,7 @@ var _ = Describe("Ordering Issues", Label("IssueOrder"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) testOrder := func( @@ -1134,7 +1179,7 @@ var _ = Describe("Ordering Issues", Label("IssueOrder"), func() { } testOrder(order, func(res []entity.IssueResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(r).ShouldNot(BeNil()) Expect(r.PrimaryName >= prev).Should(BeTrue()) @@ -1189,7 +1234,7 @@ var _ = Describe("Ordering Issues", Label("IssueOrder"), func() { } testOrder(order, func(res []entity.IssueResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(r).ShouldNot(BeNil()) Expect(r.PrimaryName <= prev).Should(BeTrue()) diff --git a/internal/database/mariadb/issue_variant.go b/internal/database/mariadb/issue_variant.go index 289c79606..69dfc59f0 100644 --- a/internal/database/mariadb/issue_variant.go +++ b/internal/database/mariadb/issue_variant.go @@ -170,8 +170,11 @@ func (s *SqlDatabase) GetAllIssueVariantIds(filter *entity.IssueVariantFilter) ( if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performIdScan(stmt, filterParameters, l) } @@ -192,8 +195,11 @@ func (s *SqlDatabase) GetIssueVariants(filter *entity.IssueVariantFilter) ([]ent if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -219,8 +225,11 @@ func (s *SqlDatabase) CountIssueVariants(filter *entity.IssueVariantFilter) (int if err != nil { return -1, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performCountScan( stmt, diff --git a/internal/database/mariadb/issue_variant_test.go b/internal/database/mariadb/issue_variant_test.go index eb8e06e5b..0bd04bd85 100644 --- a/internal/database/mariadb/issue_variant_test.go +++ b/internal/database/mariadb/issue_variant_test.go @@ -15,6 +15,9 @@ import ( "github.com/samber/lo" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("IssueVariant - ", Label("database", "IssueVariant"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -25,7 +28,7 @@ var _ = Describe("IssueVariant - ", Label("database", "IssueVariant"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All IssueVariant IDs", Label("GetAllIssueVariantIds"), func() { @@ -80,6 +83,9 @@ var _ = Describe("IssueVariant - ", Label("database", "IssueVariant"), func() { }) }) }) + // nolint due to weak random number generator for test reason + // + //nolint:gosec Context("and using a filter", func() { It("can filter by a single issue variant id that does exist", func() { ivId := ids[rand.Intn(len(ids))] diff --git a/internal/database/mariadb/mariadb_suite_test.go b/internal/database/mariadb/mariadb_suite_test.go index 7a66411f0..37c895856 100644 --- a/internal/database/mariadb/mariadb_suite_test.go +++ b/internal/database/mariadb/mariadb_suite_test.go @@ -21,7 +21,7 @@ func TestMariadb(t *testing.T) { if err != nil { panic(err) } - util.SetEnvVars(fmt.Sprintf("%s/%s", projectDir, ".test.env")) + _ = util.SetEnvVars(fmt.Sprintf("%s/%s", projectDir, ".test.env")) RegisterFailHandler(Fail) RunSpecs(t, "MariaDB Suite") diff --git a/internal/database/mariadb/migration.go b/internal/database/mariadb/migration.go index 916c090c1..833334e00 100644 --- a/internal/database/mariadb/migration.go +++ b/internal/database/mariadb/migration.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "io/fs" + "log" "strings" "sync" @@ -26,12 +27,12 @@ var MigrationFs fs.FS = &migrationFiles func GetVersion(cfg util.Config) (string, error) { db, err := NewSqlDatabase(cfg) if err != nil { - return "", fmt.Errorf("Error while Creating Db") + return "", fmt.Errorf("error while Creating Db") } v, err := db.getVersion() if err != nil { - return "", fmt.Errorf("Error while checking Db migration: %w", err) + return "", fmt.Errorf("error while checking Db migration: %w", err) } return v, nil } @@ -39,13 +40,17 @@ func GetVersion(cfg util.Config) (string, error) { func (s *SqlDatabase) getVersion() (string, error) { m, err := s.openMigration() if err != nil { - return "", fmt.Errorf("Could not open migration without source: %w", err) + return "", fmt.Errorf("could not open migration without source: %w", err) } - defer m.Close() + defer func() { + if serr, derr := m.Close(); serr != nil || derr != nil { + log.Printf("error during closing migration: source - %s, database - %s", serr, derr) + } + }() v, d, err := getMigrationVersion(m) if err != nil { - return "", fmt.Errorf("Could not get migration version: %w", err) + return "", fmt.Errorf("could not get migration version: %w", err) } return versionToString(v, d), nil @@ -54,7 +59,7 @@ func (s *SqlDatabase) getVersion() (string, error) { func (s *SqlDatabase) openMigration() (*migrate.Migrate, error) { err := s.connectDB() if err != nil { - return nil, fmt.Errorf("Could not connect DB: %w", err) + return nil, fmt.Errorf("could not connect DB: %w", err) } d, err := iofs.New(MigrationFs, "migrations") @@ -103,7 +108,7 @@ func RunMigrations(cfg util.Config) error { } err = enableScheduler(cfg) if err != nil { - return fmt.Errorf("Error while Enabling Scheduler Db: %w", err) + return fmt.Errorf("error while Enabling Scheduler Db: %w", err) } return nil } @@ -114,7 +119,11 @@ func enableScheduler(cfg util.Config) error { logrus.WithError(err).Error(err) return err } - defer db.Close() + defer func() { + if err := db.Close(); err != nil { + logrus.WithError(err).Error(err) + } + }() _, err = db.Exec("SET GLOBAL event_scheduler = ON;") if err != nil { @@ -151,7 +160,7 @@ func runNewPostMigrationsSync(cfg util.Config) error { } err = db.WaitPostMigrations() if err != nil { - return fmt.Errorf("Error while waiting for post migration procedures: %w", err) + return fmt.Errorf("error while waiting for post migration procedures: %w", err) } return nil } @@ -161,9 +170,12 @@ func (s *SqlDatabase) runUpMigrations() error { if err != nil { return err } - defer m.Close() + defer func() { + if serr, derr := m.Close(); serr != nil || derr != nil { + log.Printf("error during closing migration: source - %s, database - %s", serr, derr) + } + }() - err = m.Up() if err := m.Up(); err != nil && err != migrate.ErrNoChange && err != io.EOF { return err } @@ -174,11 +186,11 @@ func (s *SqlDatabase) runUpMigrations() error { func runNewPostMigrations(cfg util.Config) (*SqlDatabase, error) { db, err := NewSqlDatabase(cfg) if err != nil { - return nil, fmt.Errorf("Error while Creating Db: %w", err) + return nil, fmt.Errorf("error while Creating Db: %w", err) } err = db.runPostMigrations() if err != nil { - return nil, fmt.Errorf("Error while starting Post Migration procedures: %w", err) + return nil, fmt.Errorf("error while starting Post Migration procedures: %w", err) } return db, nil } @@ -186,11 +198,11 @@ func runNewPostMigrations(cfg util.Config) (*SqlDatabase, error) { func runNewUpMigrations(cfg util.Config) error { db, err := NewSqlDatabase(cfg) if err != nil { - return fmt.Errorf("Error while Creating Db: %w", err) + return fmt.Errorf("error while Creating Db: %w", err) } err = db.runUpMigrations() if err != nil { - return fmt.Errorf("Error while Migrating Db: %w", err) + return fmt.Errorf("error while Migrating Db: %w", err) } return nil } @@ -216,7 +228,7 @@ func (s *SqlDatabase) getPostMigrationProcedures() ([]string, error) { exists, err := s.tableExists(PostMigrationProcedureRegistryTable) if err != nil { - return procs, fmt.Errorf("Could not check if table exists: %w", err) + return procs, fmt.Errorf("could not check if table exists: %w", err) } else if !exists { return procs, nil } @@ -239,18 +251,18 @@ func (pmc *postMigrationContext) appendErrorMessage(msg string) { pmc.mu.Unlock() } -func (pmc postMigrationContext) hasError() bool { +func (pmc *postMigrationContext) hasError() bool { return len(pmc.errs) > 0 } -func (pmc postMigrationContext) getError() error { - return fmt.Errorf("Error when exeute joined callers: [%s]", strings.Join(pmc.errs, "; ")) +func (pmc *postMigrationContext) getError() error { + return fmt.Errorf("error when exeute joined callers: [%s]", strings.Join(pmc.errs, "; ")) } func (s *SqlDatabase) runPostMigrations() error { procs, err := s.getPostMigrationProcedures() if err != nil { - return fmt.Errorf("Failed to get post migration procedures: %w", err) + return fmt.Errorf("failed to get post migration procedures: %w", err) } if err := s.checkProceduresExist(procs); err != nil { @@ -263,9 +275,9 @@ func (s *SqlDatabase) runPostMigrations() error { func (s *SqlDatabase) checkProceduresExist(procs []string) error { exists, err := s.proceduresExist(procs) if err != nil { - return fmt.Errorf("Could not check procedures exist: %w", err) + return fmt.Errorf("could not check procedures exist: %w", err) } else if !exists { - return fmt.Errorf("Some procedures [%s] do not exist", strings.Join(procs, ", ")) + return fmt.Errorf("some procedures [%s] do not exist", strings.Join(procs, ", ")) } return nil } @@ -324,7 +336,10 @@ func (s *SqlDatabase) runPostMigrationCleanupRoutineInBackground(procs []string) if err := s.WaitPostMigrations(); err != nil { logrus.WithError(err).Error(err) } - s.CloseConnection() + + if err := s.CloseConnection(); err != nil { + logrus.Warnf("error during closing connection: %s", err) + } }() } diff --git a/internal/database/mariadb/mv_vulnerabilities.go b/internal/database/mariadb/mv_vulnerabilities.go index 7df71f4af..93a896777 100644 --- a/internal/database/mariadb/mv_vulnerabilities.go +++ b/internal/database/mariadb/mv_vulnerabilities.go @@ -11,29 +11,36 @@ import ( ) func getCountTable(filter *entity.IssueFilter) string { - if filter.AllServices && filter.Unique { + switch { + case filter.AllServices && filter.Unique: // Total count of unique issues return "mvCountIssueRatingsUniqueService" - } else if filter.AllServices { - if len(filter.SupportGroupCCRN) > 0 { - // total count of issues in support group across all services - // service list view total count with support group filter - return "mvCountIssueRatingsService" - } else { - // total count of issues in all services (across all support groups) - // service list view total count without support group filter - return "mvCountIssueRatingsServiceWithoutSupportGroup" - } - } else if len(filter.SupportGroupCCRN) > 0 && len(filter.ServiceCCRN) == 0 && len(filter.ServiceId) == 0 { + + case filter.AllServices && len(filter.SupportGroupCCRN) > 0: + // total count of issues in support group across all services + // service list view total count with support group filter + return "mvCountIssueRatingsService" + + case filter.AllServices: + // total count of issues in all services (across all support groups) + // service list view total count without support group filter + return "mvCountIssueRatingsServiceWithoutSupportGroup" + + case len(filter.SupportGroupCCRN) > 0 && + len(filter.ServiceCCRN) == 0 && + len(filter.ServiceId) == 0: // Count issues in a support group return "mvCountIssueRatingsSupportGroup" - } else if len(filter.ComponentVersionId) > 0 { + + case len(filter.ComponentVersionId) > 0: // Count issues in a component version of a *service* return "mvCountIssueRatingsComponentVersion" - } else if len(filter.ServiceCCRN) > 0 || len(filter.ServiceId) > 0 { + + case len(filter.ServiceCCRN) > 0 || len(filter.ServiceId) > 0: // Count issues that appear in single service return "mvCountIssueRatingsServiceId" - } else { + + default: // Total count of issues return "mvCountIssueRatingsOther" } @@ -92,8 +99,11 @@ func (s *SqlDatabase) CountIssueRatings(filter *entity.IssueFilter) (*entity.Iss }).Error(msg) return nil, fmt.Errorf("%s", msg) } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() counts, err := performListScan( stmt, diff --git a/internal/database/mariadb/mv_vulnerabilities_test.go b/internal/database/mariadb/mv_vulnerabilities_test.go index dfe95d5ad..521a544cf 100644 --- a/internal/database/mariadb/mv_vulnerabilities_test.go +++ b/internal/database/mariadb/mv_vulnerabilities_test.go @@ -196,7 +196,7 @@ var _ = Describe("Counting Issues by Severity", Label("IssueCounts"), func() { } iv := test.NewFakeIssueVariant(seedCollection.IssueRepositoryRows, seedCollection.IssueRows) - seeder.InsertFakeIssueVariant(iv) + _, _ = seeder.InsertFakeIssueVariant(iv) testServicesTotalCountWithUnique(totalCounts) }) @@ -262,7 +262,7 @@ var _ = Describe("Counting Issues by Severity", Label("IssueCounts"), func() { Expect(seeder.RefreshCountIssueRatings()).To(BeNil()) }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("there are no remediations", Label("NoRemediations"), func() { diff --git a/internal/database/mariadb/patch.go b/internal/database/mariadb/patch.go index 29408fadb..05f25583e 100644 --- a/internal/database/mariadb/patch.go +++ b/internal/database/mariadb/patch.go @@ -5,7 +5,6 @@ package mariadb import ( "fmt" - "strings" "github.com/cloudoperators/heureka/internal/entity" "github.com/samber/lo" @@ -20,15 +19,15 @@ func buildPatchFilterParameters(filter *entity.PatchFilter, withCursor bool, cur filterParameters = buildQueryParameters(filterParameters, filter.ComponentVersionId) filterParameters = buildQueryParameters(filterParameters, filter.ComponentVersionName) if withCursor { - filterParameters = append(filterParameters, GetCursorQueryParameters(filter.PaginatedX.First, cursorFields)...) + filterParameters = append(filterParameters, GetCursorQueryParameters(filter.First, cursorFields)...) } return filterParameters } func ensurePatchFilter(filter *entity.PatchFilter) *entity.PatchFilter { - var first int = 1000 - var after string = "" + first := 1000 + after := "" if filter == nil { filter = &entity.PatchFilter{ PaginatedX: entity.PaginatedX{ @@ -46,29 +45,6 @@ func ensurePatchFilter(filter *entity.PatchFilter) *entity.PatchFilter { return filter } -func getPatchUpdateFields(patch *entity.Patch) string { - fl := []string{} - if patch.Id != 0 { - fl = append(fl, "patch_id = :patch_id") - } - if patch.ServiceId != 0 { - fl = append(fl, "patch_service_id = :patch_service_id") - } - if patch.ServiceName != "" { - fl = append(fl, "patch_service_name = :patch_service_name") - } - if patch.ComponentVersionId != 0 { - fl = append(fl, "patch_component_version_id = :patch_component_version_id") - } - if patch.ComponentVersionName != "" { - fl = append(fl, "patch_component_version_name = :patch_component_version_name") - } - if patch.UpdatedBy != 0 { - fl = append(fl, "patch_updated_by = :patch_updated_by") - } - return strings.Join(fl, ", ") -} - func getPatchFilterString(filter *entity.PatchFilter) string { var fl []string fl = append(fl, buildFilterQuery(filter.Id, "P.patch_id = ?", OP_OR)) @@ -85,7 +61,7 @@ func (s *SqlDatabase) buildPatchStatement(baseQuery string, filter *entity.Patch l.WithFields(logrus.Fields{"filter": filter}) filterStr := getPatchFilterString(filter) - cursorFields, err := DecodeCursor(filter.PaginatedX.After) + cursorFields, err := DecodeCursor(filter.After) if err != nil { return nil, nil, fmt.Errorf("failed to decode Patch cursor: %w", err) } @@ -145,8 +121,11 @@ func (s *SqlDatabase) GetPatches(filter *entity.PatchFilter, order []entity.Orde if err != nil { return nil, fmt.Errorf("failed to build Patch query: %w", err) } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() results, err := performListScan( stmt, @@ -187,8 +166,11 @@ func (s *SqlDatabase) CountPatches(filter *entity.PatchFilter) (int64, error) { if err != nil { return -1, fmt.Errorf("failed to build Patch count query: %w", err) } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() count, err := performCountScan(stmt, filterParameters, l) if err != nil { @@ -214,8 +196,11 @@ func (s *SqlDatabase) GetAllPatchCursors(filter *entity.PatchFilter, order []ent if err != nil { return nil, fmt.Errorf("failed to build Patch cursor query: %w", err) } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() rows, err := performListScan( stmt, diff --git a/internal/database/mariadb/patch_test.go b/internal/database/mariadb/patch_test.go index 6c550f13c..18a449471 100644 --- a/internal/database/mariadb/patch_test.go +++ b/internal/database/mariadb/patch_test.go @@ -13,6 +13,9 @@ import ( . "github.com/onsi/gomega" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("Patch", Label("database", "Patch"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -23,7 +26,7 @@ var _ = Describe("Patch", Label("database", "Patch"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting Patches", Label("GetPatches"), func() { diff --git a/internal/database/mariadb/remediation.go b/internal/database/mariadb/remediation.go index 75b4b4201..2781e43e3 100644 --- a/internal/database/mariadb/remediation.go +++ b/internal/database/mariadb/remediation.go @@ -25,14 +25,14 @@ func buildRemediationFilterParameters(filter *entity.RemediationFilter, withCurs filterParameters = buildQueryParameters(filterParameters, filter.IssueId) filterParameters = buildQueryParameters(filterParameters, filter.Search) if withCursor { - filterParameters = append(filterParameters, GetCursorQueryParameters(filter.PaginatedX.First, cursorFields)...) + filterParameters = append(filterParameters, GetCursorQueryParameters(filter.First, cursorFields)...) } return filterParameters } func ensureRemediationFilter(filter *entity.RemediationFilter) *entity.RemediationFilter { - var first int = 1000 - var after string = "" + first := 1000 + after := "" if filter == nil { filter = &entity.RemediationFilter{ PaginatedX: entity.PaginatedX{ @@ -112,7 +112,7 @@ func (s *SqlDatabase) buildRemediationStatement(baseQuery string, filter *entity l.WithFields(logrus.Fields{"filter": filter}) filterStr := getRemediationFilterString(filter) - cursorFields, err := DecodeCursor(filter.PaginatedX.After) + cursorFields, err := DecodeCursor(filter.After) if err != nil { return nil, nil, fmt.Errorf("failed to decode Remediation cursor: %w", err) } @@ -172,8 +172,11 @@ func (s *SqlDatabase) GetRemediations(filter *entity.RemediationFilter, order [] if err != nil { return nil, fmt.Errorf("failed to build Remediation query: %w", err) } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() results, err := performListScan( stmt, @@ -214,8 +217,11 @@ func (s *SqlDatabase) CountRemediations(filter *entity.RemediationFilter) (int64 if err != nil { return -1, fmt.Errorf("failed to build Remediation count query: %w", err) } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() count, err := performCountScan(stmt, filterParameters, l) if err != nil { @@ -241,8 +247,11 @@ func (s *SqlDatabase) GetAllRemediationCursors(filter *entity.RemediationFilter, if err != nil { return nil, fmt.Errorf("failed to build Remediation cursor query: %w", err) } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() rows, err := performListScan( stmt, diff --git a/internal/database/mariadb/remediation_test.go b/internal/database/mariadb/remediation_test.go index dfa70d23a..a5ee15d83 100644 --- a/internal/database/mariadb/remediation_test.go +++ b/internal/database/mariadb/remediation_test.go @@ -17,6 +17,9 @@ import ( . "github.com/onsi/gomega" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("Remediation", Label("database", "Remediation"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -27,7 +30,7 @@ var _ = Describe("Remediation", Label("database", "Remediation"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting Remediations", Label("GetRemediations"), func() { @@ -331,7 +334,7 @@ var _ = Describe("Remediation", Label("database", "Remediation"), func() { ids := []int64{} for _, entry := range entries { - ids = append(ids, entry.Remediation.Id) + ids = append(ids, entry.Id) } By("throwing no error", func() { @@ -383,7 +386,7 @@ var _ = Describe("Remediation", Label("database", "Remediation"), func() { seeder.SeedDbWithNFakeData(10) }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) It("orders by vulnerability asc", func() { order := []entity.Order{{By: entity.RemediationIssue, Direction: entity.OrderDirectionAsc}} @@ -405,7 +408,7 @@ var _ = Describe("Remediation", Label("database", "Remediation"), func() { By("throwing no error", func() { Expect(err).To(BeNil()) }) - weight := map[string]int{"None":1, "Low":2, "Medium":3, "High":4, "Critical":5} + weight := map[string]int{"None": 1, "Low": 2, "Medium": 3, "High": 4, "Critical": 5} prevW := 100 for _, e := range entries { w := weight[string(e.Severity)] diff --git a/internal/database/mariadb/scanner_run.go b/internal/database/mariadb/scanner_run.go index a1a6e9552..5b2eaa46d 100644 --- a/internal/database/mariadb/scanner_run.go +++ b/internal/database/mariadb/scanner_run.go @@ -4,6 +4,8 @@ package mariadb import ( + "log" + "github.com/cloudoperators/heureka/internal/entity" "github.com/sirupsen/logrus" ) @@ -120,8 +122,12 @@ func (s *SqlDatabase) GetScannerRuns(filter *entity.ScannerRunFilter) ([]entity. if err != nil { return nil, err } + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error during closing rows: %s", err) + } + }() - defer rows.Close() result := []entity.ScannerRun{} for rows.Next() { @@ -174,7 +180,7 @@ func applyScannerRunFilter(baseQuery string, filter *entity.ScannerRunFilter) ([ } func ensureScannerRunFilter(f *entity.ScannerRunFilter) *entity.ScannerRunFilter { - var first int = 100 + first := 100 var after int64 = 0 if f == nil { return &entity.ScannerRunFilter{ @@ -202,8 +208,12 @@ func (s *SqlDatabase) GetScannerRunTags() ([]string, error) { if err != nil { return nil, err } + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error during closing rows: %s", err) + } + }() - defer rows.Close() res := []string{} for rows.Next() { @@ -233,7 +243,9 @@ func (s *SqlDatabase) CountScannerRuns(filter *entity.ScannerRunFilter) (int, er var res int - row.Scan(&res) + if err := row.Scan(&res); err != nil { + return 0, err + } return res, nil } diff --git a/internal/database/mariadb/scanner_run_test.go b/internal/database/mariadb/scanner_run_test.go index 411630277..f8fce9e8a 100644 --- a/internal/database/mariadb/scanner_run_test.go +++ b/internal/database/mariadb/scanner_run_test.go @@ -18,7 +18,7 @@ var _ = Describe("ScannerRun", Label("database", "ScannerRun"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Creating a new ScannerRun", Label("Create"), func() { diff --git a/internal/database/mariadb/service.go b/internal/database/mariadb/service.go index 75967802e..71cf1a225 100644 --- a/internal/database/mariadb/service.go +++ b/internal/database/mariadb/service.go @@ -32,7 +32,7 @@ func buildServiceFilterParameters(filter *entity.ServiceFilter, withCursor bool, filterParameters = buildQueryParameters(filterParameters, filter.OwnerId) filterParameters = buildQueryParameters(filterParameters, filter.Search) if withCursor { - filterParameters = append(filterParameters, GetCursorQueryParameters(filter.PaginatedX.First, cursorFields)...) + filterParameters = append(filterParameters, GetCursorQueryParameters(filter.First, cursorFields)...) } return filterParameters } @@ -135,8 +135,8 @@ func (s *SqlDatabase) getServiceColumns(filter *entity.ServiceFilter, order []en } func ensureServiceFilter(f *entity.ServiceFilter) *entity.ServiceFilter { - var first int = 1000 - var after string = "" + first := 1000 + after := "" if f == nil { return &entity.ServiceFilter{ PaginatedX: entity.PaginatedX{ @@ -187,7 +187,7 @@ func (s *SqlDatabase) buildServiceStatement(baseQuery string, filter *entity.Ser l.WithFields(logrus.Fields{"filter": filter}) filterStr := getServiceFilterString(filter) - cursorFields, err := DecodeCursor(filter.PaginatedX.After) + cursorFields, err := DecodeCursor(filter.After) if err != nil { return nil, nil, err } @@ -247,8 +247,11 @@ func (s *SqlDatabase) CountServices(filter *entity.ServiceFilter) (int64, error) if err != nil { return -1, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performCountScan(stmt, filterParameters, l) } @@ -268,8 +271,11 @@ func (s *SqlDatabase) GetAllServiceIds(filter *entity.ServiceFilter) ([]int64, e if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performIdScan(stmt, filterParameters, l) } @@ -294,8 +300,11 @@ func (s *SqlDatabase) GetServices(filter *entity.ServiceFilter, order []entity.O if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -370,7 +379,7 @@ func (s *SqlDatabase) GetServicesWithAggregations(filter *entity.ServiceFilter, orderStr := CreateOrderString(order) joins := s.getServiceJoins(filter, order) columns := s.getServiceColumns(filter, order) - cursorFields, err := DecodeCursor(filter.PaginatedX.After) + cursorFields, err := DecodeCursor(filter.After) if err != nil { return nil, err } @@ -405,8 +414,11 @@ func (s *SqlDatabase) GetServicesWithAggregations(filter *entity.ServiceFilter, filterParameters := buildServiceFilterParameters(filter, true, cursorFields) // parameters for component instance query filterParameters = append(filterParameters, buildServiceFilterParameters(filter, true, cursorFields)...) - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -455,8 +467,11 @@ func (s *SqlDatabase) GetAllServiceCursors(filter *entity.ServiceFilter, order [ if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() rows, err := performListScan( stmt, @@ -698,7 +713,11 @@ func (s *SqlDatabase) getServiceAttr(attrName string, filter *entity.ServiceFilt l.Error("Error preparing statement: ", err) return nil, err } - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() // Execute the query rows, err := stmt.Queryx(filterParameters...) @@ -706,7 +725,11 @@ func (s *SqlDatabase) getServiceAttr(attrName string, filter *entity.ServiceFilt l.Error("Error executing query: ", err) return nil, err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + l.Warnf("error during closing rows: %s", err) + } + }() // Collect the results serviceAttrs := []string{} diff --git a/internal/database/mariadb/service_issue_variant.go b/internal/database/mariadb/service_issue_variant.go index 5dc72281c..8a7a167ae 100644 --- a/internal/database/mariadb/service_issue_variant.go +++ b/internal/database/mariadb/service_issue_variant.go @@ -114,8 +114,11 @@ func (s *SqlDatabase) GetServiceIssueVariants(filter *entity.ServiceIssueVariant if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, diff --git a/internal/database/mariadb/service_issue_variant_test.go b/internal/database/mariadb/service_issue_variant_test.go index 448eb5998..5ecacb0f1 100644 --- a/internal/database/mariadb/service_issue_variant_test.go +++ b/internal/database/mariadb/service_issue_variant_test.go @@ -27,7 +27,7 @@ var _ = Describe("ServiceIssueVariant - ", Label("database", "IssueVariant"), fu Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting ServiceIssueVariants", Label("GetServiceIssueVariants"), func() { @@ -248,7 +248,7 @@ var _ = Describe("ServiceIssueVariant - ", Label("database", "IssueVariant"), fu } // Create issue variants - _, err := seeder.InsertFakeIssueVariant(iv) + _, _ = seeder.InsertFakeIssueVariant(iv) // Link repository to service with priority irs := mariadb.IssueRepositoryServiceRow{ diff --git a/internal/database/mariadb/service_test.go b/internal/database/mariadb/service_test.go index 3609d21cf..72b84fb75 100644 --- a/internal/database/mariadb/service_test.go +++ b/internal/database/mariadb/service_test.go @@ -20,6 +20,9 @@ import ( pkg_util "github.com/cloudoperators/heureka/pkg/util" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("Service", Label("database", "Service"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -30,7 +33,7 @@ var _ = Describe("Service", Label("database", "Service"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All Service IDs", Label("GetAllServiceIds"), func() { @@ -523,7 +526,7 @@ var _ = Describe("Service", Label("database", "Service"), func() { BeforeEach(func() { newServiceRow := test.NewFakeService() newService := newServiceRow.AsService() - db.CreateService(&newService) + _, _ = db.CreateService(&newService) }) It("returns the services with aggregations", func() { entriesWithAggregations, err := db.GetServicesWithAggregations(nil, nil) @@ -567,7 +570,7 @@ var _ = Describe("Service", Label("database", "Service"), func() { }) }) It("returns correct aggregation values", func() { - //Should be filled with a check for each aggregation value, + // Should be filled with a check for each aggregation value, // this is currently skipped due to the complexity of the test implementation // as we would need to implement for each of the aggregations a manual aggregation // based on the seederCollection. @@ -1119,7 +1122,7 @@ var _ = Describe("Ordering Services", Label("ServiceOrdering"), func() { }) AfterEach(func() { seeder.CloseDbConnection() - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) testOrder := func( @@ -1244,10 +1247,10 @@ var _ = Describe("Ordering Services", Label("ServiceOrdering"), func() { } testOrder(order, func(res []entity.ServiceResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(c.CompareString(r.Service.CCRN, prev)).Should(BeNumerically(">=", 0)) - prev = r.Service.CCRN + prev = r.CCRN } }) }) @@ -1280,10 +1283,10 @@ var _ = Describe("Ordering Services", Label("ServiceOrdering"), func() { } testOrder(order, func(res []entity.ServiceResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(c.CompareString(r.Service.CCRN, prev)).Should(BeNumerically("<=", 0)) - prev = r.Service.CCRN + prev = r.CCRN } }) }) diff --git a/internal/database/mariadb/support_group.go b/internal/database/mariadb/support_group.go index 40efa3574..3f4d87143 100644 --- a/internal/database/mariadb/support_group.go +++ b/internal/database/mariadb/support_group.go @@ -58,8 +58,8 @@ func (s *SqlDatabase) getSupportGroupJoins(filter *entity.SupportGroupFilter) st } func ensureSupportGroupFilter(f *entity.SupportGroupFilter) *entity.SupportGroupFilter { - var first int = 1000 - var after string = "" + first := 1000 + after := "" if f == nil { return &entity.SupportGroupFilter{ PaginatedX: entity.PaginatedX{ @@ -88,7 +88,7 @@ func (s *SqlDatabase) buildSupportGroupStatement(baseQuery string, filter *entit l.WithFields(logrus.Fields{"filter": filter}) filterStr := getSupportGroupFilterString(filter) - cursorFields, err := DecodeCursor(filter.PaginatedX.After) + cursorFields, err := DecodeCursor(filter.After) if err != nil { return nil, nil, err } @@ -134,7 +134,7 @@ func (s *SqlDatabase) buildSupportGroupStatement(baseQuery string, filter *entit filterParameters = buildQueryParameters(filterParameters, filter.UserId) filterParameters = buildQueryParameters(filterParameters, filter.IssueId) if withCursor { - filterParameters = append(filterParameters, GetCursorQueryParameters(filter.PaginatedX.First, cursorFields)...) + filterParameters = append(filterParameters, GetCursorQueryParameters(filter.First, cursorFields)...) } return stmt, filterParameters, nil @@ -155,8 +155,11 @@ func (s *SqlDatabase) GetAllSupportGroupIds(filter *entity.SupportGroupFilter) ( if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performIdScan(stmt, filterParameters, l) } @@ -217,8 +220,11 @@ func (s *SqlDatabase) GetSupportGroups(filter *entity.SupportGroupFilter, order if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performListScan( stmt, @@ -254,8 +260,11 @@ func (s *SqlDatabase) CountSupportGroups(filter *entity.SupportGroupFilter) (int if err != nil { return -1, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performCountScan(stmt, filterParameters, l) } @@ -467,7 +476,11 @@ func (s *SqlDatabase) GetSupportGroupCcrns(filter *entity.SupportGroupFilter) ([ l.Error("Error preparing statement: ", err) return nil, err } - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() // Execute the query rows, err := stmt.Queryx(filterParameters...) @@ -475,7 +488,11 @@ func (s *SqlDatabase) GetSupportGroupCcrns(filter *entity.SupportGroupFilter) ([ l.Error("Error executing query: ", err) return nil, err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + l.Warnf("error during closing rows: %s", err) + } + }() // Collect the results supportGroupCcrns := []string{} diff --git a/internal/database/mariadb/support_group_test.go b/internal/database/mariadb/support_group_test.go index ccf6a066c..72b63e507 100644 --- a/internal/database/mariadb/support_group_test.go +++ b/internal/database/mariadb/support_group_test.go @@ -18,6 +18,9 @@ import ( . "github.com/onsi/gomega" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("SupportGroup", Label("database", "SupportGroup"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -28,7 +31,7 @@ var _ = Describe("SupportGroup", Label("database", "SupportGroup"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All SupportGroup IDs", Label("GetAllSupportGroupIds"), func() { @@ -284,10 +287,10 @@ var _ = Describe("SupportGroup", Label("database", "SupportGroup"), func() { }, } testOrder(order, func(res []entity.SupportGroupResult) { - var prev string = "" + prev := "" for _, r := range res { Expect(c.CompareString(r.SupportGroup.CCRN, prev)).Should(BeNumerically(">=", 0)) - prev = r.SupportGroup.CCRN + prev = r.CCRN } }) }) @@ -301,10 +304,10 @@ var _ = Describe("SupportGroup", Label("database", "SupportGroup"), func() { }, } testOrder(order, func(res []entity.SupportGroupResult) { - var prev string = "\U0010FFFF" + prev := prev for _, r := range res { Expect(c.CompareString(r.SupportGroup.CCRN, prev)).Should(BeNumerically("<=", 0)) - prev = r.SupportGroup.CCRN + prev = r.CCRN } }) }) diff --git a/internal/database/mariadb/test/common.go b/internal/database/mariadb/test/common.go index 21dff7035..a2133b8e7 100644 --- a/internal/database/mariadb/test/common.go +++ b/internal/database/mariadb/test/common.go @@ -14,6 +14,9 @@ import ( "github.com/cloudoperators/heureka/internal/database/mariadb" "github.com/cloudoperators/heureka/internal/entity" + + // nolint due to importing all functions from gomega package + //nolint: staticcheck . "github.com/onsi/gomega" ) @@ -29,7 +32,7 @@ func TestPaginationOfListWithOrder[F entity.HeurekaFilter, E entity.HeurekaEntit quotient, remainder := elementCount/pageSize, elementCount%pageSize expectedPages := quotient if remainder > 0 { - expectedPages = expectedPages + 1 + expectedPages++ } var after *int64 @@ -62,7 +65,7 @@ func TestPaginationOfList[F entity.HeurekaFilter, E entity.HeurekaEntity]( quotient, remainder := elementCount/pageSize, elementCount%pageSize expectedPages := quotient if remainder > 0 { - expectedPages = expectedPages + 1 + expectedPages++ } var after *int64 @@ -118,6 +121,7 @@ func GetTestDataPath(path string) string { // LoadIssueMatches loads issue matches from JSON file func LoadIssueMatches(filename string) ([]mariadb.IssueMatchRow, error) { // Read JSON file + //nolint: gosec data, err := os.ReadFile(filename) if err != nil { return nil, err @@ -154,6 +158,7 @@ func LoadIssueMatches(filename string) ([]mariadb.IssueMatchRow, error) { // LoadIssues loads issues from JSON file func LoadIssues(filename string) ([]mariadb.IssueRow, error) { + //nolint:gosec data, err := os.ReadFile(filename) if err != nil { return nil, err @@ -180,6 +185,7 @@ func LoadIssues(filename string) ([]mariadb.IssueRow, error) { // LoadComponentInstances loads component instances from JSON file func LoadComponentInstances(filename string) ([]mariadb.ComponentInstanceRow, error) { + //nolint:gosec data, err := os.ReadFile(filename) if err != nil { return nil, err @@ -209,6 +215,7 @@ func LoadComponentInstances(filename string) ([]mariadb.ComponentInstanceRow, er } func LoadComponentVersions(filename string) ([]mariadb.ComponentVersionRow, error) { + //nolint:gosec data, err := os.ReadFile(filename) if err != nil { return nil, err @@ -238,6 +245,7 @@ func LoadComponentVersions(filename string) ([]mariadb.ComponentVersionRow, erro } func LoadIssueVariants(filename string) ([]mariadb.IssueVariantRow, error) { + //nolint:gosec data, err := os.ReadFile(filename) if err != nil { return nil, err @@ -267,6 +275,7 @@ func LoadIssueVariants(filename string) ([]mariadb.IssueVariantRow, error) { } func LoadComponentVersionIssues(filename string) ([]mariadb.ComponentVersionIssueRow, error) { + //nolint:gosec data, err := os.ReadFile(filename) if err != nil { return nil, err @@ -290,6 +299,7 @@ func LoadComponentVersionIssues(filename string) ([]mariadb.ComponentVersionIssu } func LoadSupportGroupServices(filename string) ([]mariadb.SupportGroupServiceRow, error) { + //nolint:gosec data, err := os.ReadFile(filename) if err != nil { return nil, err @@ -313,6 +323,7 @@ func LoadSupportGroupServices(filename string) ([]mariadb.SupportGroupServiceRow } func loadIssueCountsFromFile(filename string, idKey string) (map[string]entity.IssueSeverityCounts, error) { + //nolint:gosec data, err := os.ReadFile(filename) if err != nil { return nil, err @@ -352,6 +363,7 @@ func LoadSupportGroupIssueCounts(filename string) (map[string]entity.IssueSeveri } func LoadIssueCounts(filename string) (entity.IssueSeverityCounts, error) { + //nolint:gosec data, err := os.ReadFile(filename) var issueCounts entity.IssueSeverityCounts if err != nil { diff --git a/internal/database/mariadb/test/database_manager.go b/internal/database/mariadb/test/database_manager.go index 1fff98683..20440f046 100644 --- a/internal/database/mariadb/test/database_manager.go +++ b/internal/database/mariadb/test/database_manager.go @@ -111,9 +111,15 @@ func (dbm *DatabaseManager) cleanupSchemas() error { func (dbm *DatabaseManager) TestTearDown(dbClient *mariadb.SqlDatabase) error { err := dbm.cleanupSchemas() - dbClient.CloseConnection() + if err := dbClient.CloseConnection(); err != nil { + return err + } + if dbm.dbClient != nil { - dbm.dbClient.CloseConnection() + if err := dbm.dbClient.CloseConnection(); err != nil { + return err + } + dbm.dbClient = nil } return err @@ -136,11 +142,11 @@ func (dbm *DatabaseManager) prepareDb(dbName string) error { err := dbm.dbClient.ConnectDB(dbm.Config.DBName) if err != nil { - return fmt.Errorf("Failure while connecting to DB") + return fmt.Errorf("failure while connecting to DB") } err = dbm.dbClient.GrantAccess(dbm.Config.DBUser, dbm.Config.DBName, "%") if err != nil { - return fmt.Errorf("Failure while granting privileges for new Schema") + return fmt.Errorf("failure while granting privileges for new Schema") } return nil } @@ -148,7 +154,7 @@ func (dbm *DatabaseManager) prepareDb(dbName string) error { func (dbm *DatabaseManager) createNewConnection() (*mariadb.SqlDatabase, error) { dbClient, err := mariadb.NewSqlDatabase(dbm.Config) if err != nil { - return nil, fmt.Errorf("Failure while loading DB Client for new Schema") + return nil, fmt.Errorf("failure while loading DB Client for new Schema") } return dbClient, nil diff --git a/internal/database/mariadb/test/fixture.go b/internal/database/mariadb/test/fixture.go index 56601d92e..e8003faaf 100644 --- a/internal/database/mariadb/test/fixture.go +++ b/internal/database/mariadb/test/fixture.go @@ -6,6 +6,7 @@ package test import ( "database/sql" "fmt" + "log" "math/rand" "strings" "time" @@ -229,10 +230,13 @@ func NewDatabaseSeeder(cfg util.Config) (*DatabaseSeeder, error) { } func (s *DatabaseSeeder) CloseDbConnection() { - s.db.Close() + _ = s.db.Close() } // Generate a random CVSS 3.1 vector +// nolint due to weak random number generator for test reason +// +//nolint:gosec func GenerateRandomCVSS31Vector() string { avValues := []string{"N", "A", "L", "P"} acValues := []string{"L", "H"} @@ -327,9 +331,9 @@ func GenerateRandomCVSS31Vector() string { func (s *DatabaseSeeder) SeedDbForServer(n int) *SeedCollection { users := s.SeedUsers(n) supportGroupsMap := s.SeedRealSupportGroups() - supportGroups := lo.Values[string, mariadb.SupportGroupRow](supportGroupsMap) + supportGroups := lo.Values(supportGroupsMap) servicesMap := s.SeedRealServices() - services := lo.Values[string, mariadb.BaseServiceRow](servicesMap) + services := lo.Values(servicesMap) components := s.SeedComponents(n) componentVersions := s.SeedComponentVersions(n, components) componentInstances := s.SeedComponentInstances(n, componentVersions, services) @@ -574,11 +578,15 @@ func (s *DatabaseSeeder) SeedIssueRepositories() []mariadb.BaseIssueRepositoryRo } row.Id = sql.NullInt64{Int64: id, Valid: true} repos[i] = row - i = i + 1 + i++ } + return repos } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedIssueMatches(num int, issues []mariadb.IssueRow, componentInstances []mariadb.ComponentInstanceRow, users []mariadb.UserRow) []mariadb.IssueMatchRow { var issueMatches []mariadb.IssueMatchRow for i := 0; i < num; i++ { @@ -668,6 +676,9 @@ func (s *DatabaseSeeder) SeedSupportGroups(num int) []mariadb.SupportGroupRow { return supportGroups } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedSupportGroupServices(num int, services []mariadb.BaseServiceRow, supportGroups []mariadb.SupportGroupRow) []mariadb.SupportGroupServiceRow { var rows []mariadb.SupportGroupServiceRow for i := 0; i < num; i++ { @@ -688,6 +699,9 @@ func (s *DatabaseSeeder) SeedSupportGroupServices(num int, services []mariadb.Ba return rows } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedSupportGroupUsers(num int, users []mariadb.UserRow, supportGroups []mariadb.SupportGroupRow) []mariadb.SupportGroupUserRow { var rows []mariadb.SupportGroupUserRow for i := 0; i < num; i++ { @@ -740,6 +754,9 @@ func (s *DatabaseSeeder) SeedComponents(num int) []mariadb.ComponentRow { return components } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedComponentVersions(num int, components []mariadb.ComponentRow) []mariadb.ComponentVersionRow { var componentVersions []mariadb.ComponentVersionRow for i := 0; i < num; i++ { @@ -759,6 +776,9 @@ func (s *DatabaseSeeder) SeedComponentVersions(num int, components []mariadb.Com return componentVersions } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedComponentInstances(num int, componentVersions []mariadb.ComponentVersionRow, services []mariadb.BaseServiceRow) []mariadb.ComponentInstanceRow { var componentInstances []mariadb.ComponentInstanceRow for i := 0; i < num; i++ { @@ -795,6 +815,9 @@ func (s *DatabaseSeeder) SeedUsers(num int) []mariadb.UserRow { return users } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedOwners(num int, services []mariadb.BaseServiceRow, users []mariadb.UserRow) []mariadb.OwnerRow { var owners []mariadb.OwnerRow for i := 0; i < num; i++ { @@ -830,6 +853,9 @@ func (s *DatabaseSeeder) SeedActivities(num int) []mariadb.ActivityRow { return activities } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedActivityHasServices(num int, activities []mariadb.ActivityRow, services []mariadb.BaseServiceRow) []mariadb.ActivityHasServiceRow { var ahsList []mariadb.ActivityHasServiceRow for i := 0; i < num; i++ { @@ -850,6 +876,9 @@ func (s *DatabaseSeeder) SeedActivityHasServices(num int, activities []mariadb.A return ahsList } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedIssueMatchEvidence(num int, im []mariadb.IssueMatchRow, e []mariadb.EvidenceRow) []mariadb.IssueMatchEvidenceRow { var imeList []mariadb.IssueMatchEvidenceRow for i := 0; i < num; i++ { @@ -871,6 +900,9 @@ func (s *DatabaseSeeder) SeedIssueMatchEvidence(num int, im []mariadb.IssueMatch return imeList } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedActivityHasIssues(num int, activities []mariadb.ActivityRow, issues []mariadb.IssueRow) []mariadb.ActivityHasIssueRow { ahiList := make([]mariadb.ActivityHasIssueRow, num) for i := 0; i < num; i++ { @@ -890,6 +922,9 @@ func (s *DatabaseSeeder) SeedActivityHasIssues(num int, activities []mariadb.Act return ahiList } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedEvidences(num int, activities []mariadb.ActivityRow, users []mariadb.UserRow) []mariadb.EvidenceRow { var evidences []mariadb.EvidenceRow for i := 0; i < num; i++ { @@ -911,6 +946,9 @@ func (s *DatabaseSeeder) SeedEvidences(num int, activities []mariadb.ActivityRow return evidences } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedComponentVersionIssues(num int, componentVersions []mariadb.ComponentVersionRow, issues []mariadb.IssueRow) []mariadb.ComponentVersionIssueRow { cviList := make([]mariadb.ComponentVersionIssueRow, num) for i := 0; i < num; i++ { @@ -931,6 +969,9 @@ func (s *DatabaseSeeder) SeedComponentVersionIssues(num int, componentVersions [ return cviList } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedIssueRepositoryServices(num int, services []mariadb.BaseServiceRow, issueRepositories []mariadb.BaseIssueRepositoryRow) []mariadb.IssueRepositoryServiceRow { var rows []mariadb.IssueRepositoryServiceRow for i := 0; i < num; i++ { @@ -952,6 +993,9 @@ func (s *DatabaseSeeder) SeedIssueRepositoryServices(num int, services []mariadb return rows } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func (s *DatabaseSeeder) SeedRemediations(num int, services []mariadb.BaseServiceRow, components []mariadb.ComponentRow, issues []mariadb.IssueRow) []mariadb.RemediationRow { var rows []mariadb.RemediationRow for i := 0; i < num; i++ { @@ -1440,7 +1484,11 @@ func (s *DatabaseSeeder) ExecPreparedNamed(query string, obj any) (int64, error) if err != nil { return 0, err } - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + log.Printf("error during closing statement: %s", err) + } + }() res, err := stmt.Exec(obj) if err != nil { @@ -1479,6 +1527,9 @@ func NewFakeIssue() mariadb.IssueRow { } } +// nolint due to weak random number generator for test reason +// +//nolint:gosec func NewFakeIssueVariant(repos []mariadb.BaseIssueRepositoryRow, disc []mariadb.IssueRow) mariadb.IssueVariantRow { variants := []string{"GHSA", "RHSA", "VMSA"} v := GenerateRandomCVSS31Vector() @@ -1580,7 +1631,7 @@ func GenerateFakeCcrn(cluster string, namespace string) string { func NewFakeComponentInstance() mariadb.ComponentInstanceRow { n := gofakeit.Int16() if n < 0 { - n = n * -1 + n *= -1 } region := gofakeit.RandomString([]string{"test-de-1", "test-de-2", "test-us-1", "test-jp-2", "test-jp-1"}) cluster := gofakeit.RandomString([]string{"test-de-1", "test-de-2", "test-us-1", "test-jp-2", "test-jp-1", "a-test-de-1", "a-test-de-2", "a-test-us-1", "a-test-jp-2", "a-test-jp-1", "v-test-de-1", "v-test-de-2", "v-test-us-1", "v-test-jp-2", "v-test-jp-1", "s-test-de-1", "s-test-de-2", "s-test-us-1", "s-test-jp-2", "s-test-jp-1"}) @@ -1901,7 +1952,7 @@ func (s *DatabaseSeeder) SeedRealSupportGroupService(services map[string]mariadb SupportGroupId: sql.NullInt64{Int64: supportGroups[sg].Id.Int64, Valid: true}, ServiceId: sql.NullInt64{Int64: services[service].Id.Int64, Valid: true}, } - s.InsertFakeSupportGroupService(sgsr) + _, _ = s.InsertFakeSupportGroupService(sgsr) sgs = append(sgs, sgsr) } return sgs @@ -1916,7 +1967,11 @@ func (s *DatabaseSeeder) Clear() error { if err != nil { return err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error during closing rows: %s", err) + } + }() var table string for rows.Next() { diff --git a/internal/database/mariadb/test/scanner_fixture.go b/internal/database/mariadb/test/scanner_fixture.go index 99e03c474..99e567af3 100644 --- a/internal/database/mariadb/test/scanner_fixture.go +++ b/internal/database/mariadb/test/scanner_fixture.go @@ -6,6 +6,7 @@ package test import ( "database/sql" "fmt" + "log" "time" "github.com/cloudoperators/heureka/internal/database/mariadb" @@ -65,7 +66,6 @@ type ScannerRunsSeeder struct { type componentInstanceData struct { componentVersionId int64 serviceId int64 - issueMatches []int64 } func NewScannerRunsSeeder(dbSeeder *DatabaseSeeder) *ScannerRunsSeeder { @@ -115,12 +115,11 @@ func (srs *ScannerRunsSeeder) processDbSeeds(dbs DbSeeds) error { func (srs *ScannerRunsSeeder) seedIssues(issues []string) error { for _, issue := range issues { if _, ok := srs.knownIssues[issue]; ok { - return fmt.Errorf("Trying to seed Issue that already exists: '%s'.", issue) + return fmt.Errorf("trying to seed Issue that already exists: '%s'", issue) } issueId, err := srs.dbSeeder.insertIssue(issue) if err != nil { return err - } srs.knownIssues[issue] = issueId @@ -131,20 +130,19 @@ func (srs *ScannerRunsSeeder) seedIssues(issues []string) error { func (srs *ScannerRunsSeeder) seedComponentVersionIssues(componentVersionIssues []ComponentVersionIssue) error { for _, cvi := range componentVersionIssues { if _, ok := srs.knownComponentVersionIssues[cvi]; ok { - return fmt.Errorf("Trying to seed ComponentVersionIssue that already exists: 'i: %s, cv: %s'.", cvi.Issue, cvi.ComponentVersion) + return fmt.Errorf("trying to seed ComponentVersionIssue that already exists: 'i: %s, cv: %s'", cvi.Issue, cvi.ComponentVersion) } issueId, ok := srs.knownIssues[cvi.Issue] if !ok { - return fmt.Errorf("Trying to seed ComponentVersionIssue but issue does not exist: 'i: %s, cv: %s'.", cvi.Issue, cvi.ComponentVersion) + return fmt.Errorf("trying to seed ComponentVersionIssue but issue does not exist: 'i: %s, cv: %s'", cvi.Issue, cvi.ComponentVersion) } componentVersionId, ok := srs.knownVersions[cvi.ComponentVersion] if !ok { - return fmt.Errorf("Trying to seed ComponentVersionIssue but component version does not exist: 'i: %s, cv: %s'.", cvi.Issue, cvi.ComponentVersion) + return fmt.Errorf("trying to seed ComponentVersionIssue but component version does not exist: 'i: %s, cv: %s'", cvi.Issue, cvi.ComponentVersion) } cviId, err := srs.dbSeeder.insertComponentVersionIssue(componentVersionId, issueId) if err != nil { return err - } srs.knownComponentVersionIssues[cvi] = cviId @@ -156,7 +154,7 @@ func (srs *ScannerRunsSeeder) seedComponentsData(components []ComponentData) err for _, component := range components { _, ok := srs.knownComponentInstances[component.Name] if ok { - return fmt.Errorf("ComponentInstance: '%s' already exists.", component.Name) + return fmt.Errorf("ComponentInstance: '%s' already exists", component.Name) } _, err := srs.seedComponentData(component) if err != nil { @@ -233,7 +231,7 @@ func (srs *ScannerRunsSeeder) insertNextComponent() (int64, error) { componentCcrn := fmt.Sprintf("component-%d", srs.componentCounter) srs.componentCounter++ if _, ok := srs.knownComponents[componentCcrn]; ok { - return 0, fmt.Errorf("Trying to insert Component which already exists: '%s'", componentCcrn) + return 0, fmt.Errorf("trying to insert Component which already exists: '%s'", componentCcrn) } return srs.insertComponent(componentCcrn) } @@ -261,7 +259,7 @@ func (srs *ScannerRunsSeeder) insertNextService() (int64, error) { serviceCcrn := fmt.Sprintf("service-%d", srs.serviceCounter) srs.serviceCounter++ if _, ok := srs.knownServices[serviceCcrn]; ok { - return 0, fmt.Errorf("Trying to insert Service which already exists: '%s'", serviceCcrn) + return 0, fmt.Errorf("trying to insert Service which already exists: '%s'", serviceCcrn) } return srs.insertService(serviceCcrn) } @@ -289,7 +287,7 @@ func (srs *ScannerRunsSeeder) insertNextComponentVersion(componentId int64) (int versionName := fmt.Sprintf("version-%d", srs.componentVersionCounter) srs.componentVersionCounter++ if _, ok := srs.knownVersions[versionName]; ok { - return 0, fmt.Errorf("Trying to insert ComponentVersion which already exists: '%s'", versionName) + return 0, fmt.Errorf("trying to insert ComponentVersion which already exists: '%s'", versionName) } return srs.insertComponentVersion(versionName, componentId) } @@ -307,7 +305,7 @@ func (srs *ScannerRunsSeeder) storeIssueMatchComponents(issueMatchComponents []I for _, imc := range issueMatchComponents { issue, ok := srs.knownIssues[imc.Issue] if !ok { - return fmt.Errorf("Issue from IssueMatchComponent not found in known Issues: '%s'", imc.Issue) + return fmt.Errorf("issue from IssueMatchComponent not found in known Issues: '%s'", imc.Issue) } srs.knownIssuesMatchComponents[imc.ComponentInstance] = append(srs.knownIssuesMatchComponents[imc.ComponentInstance], issue) } @@ -320,7 +318,6 @@ func (srs *ScannerRunsSeeder) processScannerRunInstance(srd ScannerRunDef) error res, err := srs.dbSeeder.insertScannerRunInstance(gofakeit.UUID(), srd.Tag, srd.Timestamp, srd.Timestamp, srd.IsCompleted) if err != nil { return err - } scannerRunId, err := res.LastInsertId() if err != nil { @@ -559,7 +556,11 @@ func (s *DatabaseSeeder) FetchPatchesByComponentInstanceCCRN( if err != nil { return nil, fmt.Errorf("failed to query patches by ccrn: %w", err) } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error during closing rows: %s", err) + } + }() var patches []mariadb.PatchRow @@ -604,7 +605,11 @@ func (s *DatabaseSeeder) FetchAllNamesOfDeletedIssueMatches() ([]string, error) if err != nil { return nil, fmt.Errorf("failed to query issue matches by id: %w", err) } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error during closing rows: %s", err) + } + }() var issueNames []string @@ -642,7 +647,11 @@ func (s *DatabaseSeeder) FetchAllNamesOfDeletedVersions() ([]string, error) { if err != nil { return nil, fmt.Errorf("failed to query versions: %w", err) } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error during closing rows: %s", err) + } + }() var versions []string @@ -680,7 +689,11 @@ func (s *DatabaseSeeder) FetchAllNamesOfDeletedComponents() ([]string, error) { if err != nil { return nil, fmt.Errorf("failed to query components: %w", err) } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error during closing rows: %s", err) + } + }() var components []string @@ -720,7 +733,11 @@ func (s *DatabaseSeeder) FetchAllNamesOfComponentVersionIssues() ([]ComponentVer if err != nil { return nil, fmt.Errorf("failed to query versions: %w", err) } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error during closing rows: %s", err) + } + }() var result []ComponentVersionIssue diff --git a/internal/database/mariadb/uniqueness_test.go b/internal/database/mariadb/uniqueness_test.go index f5b7f37dc..94601973f 100644 --- a/internal/database/mariadb/uniqueness_test.go +++ b/internal/database/mariadb/uniqueness_test.go @@ -41,7 +41,7 @@ var _ = Describe("Delete uniqueness", Ordered, Label("database", "Uniqueness"), }) AfterAll(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) for label, uut := range testTemplates { diff --git a/internal/database/mariadb/user.go b/internal/database/mariadb/user.go index 059312880..394b9c5c7 100644 --- a/internal/database/mariadb/user.go +++ b/internal/database/mariadb/user.go @@ -26,7 +26,7 @@ func getUserFilterString(filter *entity.UserFilter) string { } func ensureUserFilter(f *entity.UserFilter) *entity.UserFilter { - var first int = 1000 + first := 1000 var after int64 = 0 if f == nil { return &entity.UserFilter{ @@ -154,8 +154,11 @@ func (s *SqlDatabase) GetAllUserIds(filter *entity.UserFilter) ([]int64, error) if err != nil { return nil, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performIdScan(stmt, filterParameters, l) } @@ -179,8 +182,12 @@ func (s *SqlDatabase) GetUsers(filter *entity.UserFilter) ([]entity.User, error) if err != nil { return nil, err } + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() - defer stmt.Close() return performListScan( stmt, filterParameters, @@ -205,8 +212,11 @@ func (s *SqlDatabase) CountUsers(filter *entity.UserFilter) (int64, error) { if err != nil { return -1, err } - - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() return performCountScan(stmt, filterParameters, l) } @@ -317,7 +327,11 @@ func (s *SqlDatabase) GetUserNames(filter *entity.UserFilter) ([]string, error) l.Error("Error preparing statement: ", err) return nil, err } - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() // Execute the query rows, err := stmt.Queryx(filterParameters...) @@ -325,7 +339,11 @@ func (s *SqlDatabase) GetUserNames(filter *entity.UserFilter) ([]string, error) l.Error("Error executing query: ", err) return nil, err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + l.Warnf("error during closing rows: %s", err) + } + }() // Collect the results userNames := []string{} @@ -367,7 +385,11 @@ func (s *SqlDatabase) GetUniqueUserIDs(filter *entity.UserFilter) ([]string, err l.Error("Error preparing statement: ", err) return nil, err } - defer stmt.Close() + defer func() { + if err := stmt.Close(); err != nil { + l.Warnf("error during closing statement: %s", err) + } + }() // Execute the query rows, err := stmt.Queryx(filterParameters...) @@ -375,7 +397,11 @@ func (s *SqlDatabase) GetUniqueUserIDs(filter *entity.UserFilter) ([]string, err l.Error("Error executing query: ", err) return nil, err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + l.Warnf("error during closing rows: %s", err) + } + }() // Collect the results uniqueUserID := []string{} diff --git a/internal/database/mariadb/user_test.go b/internal/database/mariadb/user_test.go index 235cadb75..d8cda792a 100644 --- a/internal/database/mariadb/user_test.go +++ b/internal/database/mariadb/user_test.go @@ -16,6 +16,9 @@ import ( "github.com/samber/lo" ) +// nolint due to weak random number generator for test reason +// +//nolint:gosec var _ = Describe("User", Label("database", "User"), func() { var db *mariadb.SqlDatabase var seeder *test.DatabaseSeeder @@ -26,7 +29,7 @@ var _ = Describe("User", Label("database", "User"), func() { Expect(err).To(BeNil(), "Database Seeder Setup should work") }) AfterEach(func() { - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("Getting All User IDs", Label("GetAllUserIds"), func() { diff --git a/internal/e2e/activity_query_test.go b/internal/e2e/activity_query_test.go index 4875f2456..93d0f477b 100644 --- a/internal/e2e/activity_query_test.go +++ b/internal/e2e/activity_query_test.go @@ -44,7 +44,7 @@ var _ = Describe("Getting Activities via API", Label("e2e", "Activity"), func() AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -120,7 +120,7 @@ var _ = Describe("Getting Activities via API", Label("e2e", "Activity"), func() // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/activity/directRelations.graphql") Expect(err).To(BeNil()) @@ -197,7 +197,7 @@ var _ = Describe("Creating Activity via API", Label("e2e", "Activities"), func() AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -211,7 +211,7 @@ var _ = Describe("Creating Activity via API", Label("e2e", "Activities"), func() // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/activity/create.graphql") Expect(err).To(BeNil()) @@ -258,7 +258,7 @@ var _ = Describe("Updating activity via API", Label("e2e", "Activities"), func() AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -273,7 +273,7 @@ var _ = Describe("Updating activity via API", Label("e2e", "Activities"), func() // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/activity/update.graphql") Expect(err).To(BeNil()) @@ -322,7 +322,7 @@ var _ = Describe("Deleting Activity via API", Label("e2e", "Activities"), func() AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -337,7 +337,7 @@ var _ = Describe("Deleting Activity via API", Label("e2e", "Activities"), func() // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/activity/delete.graphql") Expect(err).To(BeNil()) @@ -383,7 +383,7 @@ var _ = Describe("Modifying Services of Activity via API", Label("e2e", "Service AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -398,7 +398,7 @@ var _ = Describe("Modifying Services of Activity via API", Label("e2e", "Service // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/activity/addService.graphql") Expect(err).To(BeNil()) @@ -443,7 +443,7 @@ var _ = Describe("Modifying Services of Activity via API", Label("e2e", "Service // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/activity/removeService.graphql") Expect(err).To(BeNil()) @@ -500,7 +500,7 @@ var _ = Describe("Modifying Issues of Activity via API", Label("e2e", "ServiceIs AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -515,7 +515,7 @@ var _ = Describe("Modifying Issues of Activity via API", Label("e2e", "ServiceIs // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/activity/addIssue.graphql") Expect(err).To(BeNil()) @@ -560,7 +560,7 @@ var _ = Describe("Modifying Issues of Activity via API", Label("e2e", "ServiceIs // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/activity/removeIssue.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/authentication_test.go b/internal/e2e/authentication_test.go index 5ac2b5d17..0fce6ad7e 100644 --- a/internal/e2e/authentication_test.go +++ b/internal/e2e/authentication_test.go @@ -153,7 +153,7 @@ func (at *authenticationTest) getTestIssueCreatedByAndUpdatedBySystemUser() enti func (at *authenticationTest) teardown() { e2e_common.ServerTeardown(at.server) at.oidcProvider.Stop() - dbm.TestTearDown(at.db) + _ = dbm.TestTearDown(at.db) } func (at *authenticationTest) createIssueByUser(issue entity.Issue, user entity.User) model.Issue { diff --git a/internal/e2e/cache_test.go b/internal/e2e/cache_test.go index a0a77eb5d..e278f6d5e 100644 --- a/internal/e2e/cache_test.go +++ b/internal/e2e/cache_test.go @@ -100,7 +100,7 @@ func (ct *cacheTest) startDbProxy() { func (ct *cacheTest) teardown() { e2e_common.ServerTeardown(ct.server) - dbm.TestTearDown(ct.db) + _ = dbm.TestTearDown(ct.db) if ct.dbProxy != nil { ct.dbProxy.Stop() } diff --git a/internal/e2e/common/gql.go b/internal/e2e/common/gql.go index 580734b52..1ed28c07f 100644 --- a/internal/e2e/common/gql.go +++ b/internal/e2e/common/gql.go @@ -10,6 +10,9 @@ import ( util2 "github.com/cloudoperators/heureka/pkg/util" "github.com/machinebox/graphql" + + // nolint due to importing all functions from gomega package + //nolint: staticcheck . "github.com/onsi/gomega" "github.com/sirupsen/logrus" ) @@ -34,6 +37,7 @@ func ExecuteGqlQueryFromFileWithHeaders[T any](port string, queryFilePath string func newClientAndRequestForGqlFileQuery(port string, queryFilePath string, vars map[string]interface{}, headers map[string]string) (*graphql.Client, *graphql.Request) { client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", port)) + //nolint:gosec b, err := os.ReadFile(queryFilePath) Expect(err).To(BeNil()) str := string(b) diff --git a/internal/e2e/common/issue.go b/internal/e2e/common/issue.go index 595b5e39f..c0c4c7304 100644 --- a/internal/e2e/common/issue.go +++ b/internal/e2e/common/issue.go @@ -12,6 +12,8 @@ import ( util2 "github.com/cloudoperators/heureka/pkg/util" "github.com/machinebox/graphql" + // nolint due to importing all functions from gomega package + //nolint: staticcheck . "github.com/onsi/gomega" "github.com/sirupsen/logrus" ) @@ -25,7 +27,7 @@ type Issue struct { func QueryCreateIssue(port string, issue Issue) *model.Issue { client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/create.graphql") Expect(err).To(BeNil()) str := string(b) @@ -53,7 +55,7 @@ func QueryUpdateIssue(port string, issue Issue, iid string) *model.Issue { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/update.graphql") Expect(err).To(BeNil()) str := string(b) @@ -81,7 +83,7 @@ func QueryDeleteIssue(port string, iid string) string { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/delete.graphql") Expect(err).To(BeNil()) str := string(b) @@ -105,7 +107,7 @@ func QueryGetIssueWithReqVars(port string, vars map[string]interface{}) *model.I // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/listIssues.graphql") Expect(err).To(BeNil()) str := string(b) diff --git a/internal/e2e/common/proxy.go b/internal/e2e/common/proxy.go index 2926ddb20..d26fd1339 100644 --- a/internal/e2e/common/proxy.go +++ b/internal/e2e/common/proxy.go @@ -44,7 +44,7 @@ func (p *PausableProxy) Start() error { func (p *PausableProxy) Stop() { close(p.stopChan) - p.listener.Close() + _ = p.listener.Close() p.wg.Wait() } @@ -107,19 +107,25 @@ func (p *PausableProxy) handleConnection(src net.Conn) { dst, err := net.Dial("tcp", p.targetAddr) if err != nil { log.Println("Failed to connect to target:", err) - src.Close() + _ = src.Close() return } go func() { - defer src.Close() - defer dst.Close() - io.Copy(dst, src) + defer func() { + _ = dst.Close() + _ = src.Close() + }() + + _, _ = io.Copy(dst, src) }() go func() { - defer src.Close() - defer dst.Close() - io.Copy(src, dst) + defer func() { + _ = dst.Close() + _ = src.Close() + }() + + _, _ = io.Copy(src, dst) }() } diff --git a/internal/e2e/common/server.go b/internal/e2e/common/server.go index c2e6d5fc4..37ade3544 100644 --- a/internal/e2e/common/server.go +++ b/internal/e2e/common/server.go @@ -6,6 +6,9 @@ package e2e_common import ( "github.com/cloudoperators/heureka/internal/server" "github.com/cloudoperators/heureka/internal/util" + + // nolint due to importing all functions from gomega package + //nolint: staticcheck . "github.com/onsi/gomega" ) diff --git a/internal/e2e/common/user.go b/internal/e2e/common/user.go index 0255546be..e3ff701f2 100644 --- a/internal/e2e/common/user.go +++ b/internal/e2e/common/user.go @@ -14,6 +14,8 @@ import ( util2 "github.com/cloudoperators/heureka/pkg/util" "github.com/machinebox/graphql" + // nolint due to importing all functions from gomega package + //nolint: staticcheck . "github.com/onsi/gomega" "github.com/samber/lo" "github.com/sirupsen/logrus" @@ -96,7 +98,7 @@ type User struct { func QueryCreateUser(port string, user User) *model.User { client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/user/create.graphql") Expect(err).To(BeNil()) str := string(b) @@ -125,7 +127,7 @@ func QueryUpdateUser(port string, user User, uid string) *model.User { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/user/update.graphql") Expect(err).To(BeNil()) str := string(b) @@ -153,7 +155,7 @@ func QueryGetUser(port string, uniqueUserId string) *model.UserConnection { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/user/listUsers.graphql") Expect(err).To(BeNil()) str := string(b) diff --git a/internal/e2e/component_filter_query_test.go b/internal/e2e/component_filter_query_test.go index 2b942cfb2..2a7a5f841 100644 --- a/internal/e2e/component_filter_query_test.go +++ b/internal/e2e/component_filter_query_test.go @@ -43,7 +43,7 @@ var _ = Describe("Getting ComponentFilterValues via API", Label("e2e", "Componen AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { diff --git a/internal/e2e/component_instance_filter_test.go b/internal/e2e/component_instance_filter_test.go index 5263422e7..c2574aceb 100644 --- a/internal/e2e/component_instance_filter_test.go +++ b/internal/e2e/component_instance_filter_test.go @@ -43,7 +43,7 @@ var _ = Describe("Getting ComponentInstanceFilterValues via API", Label("e2e", " AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -51,7 +51,7 @@ var _ = Describe("Getting ComponentInstanceFilterValues via API", Label("e2e", " // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentInstanceFilter/ccrn.graphqls") Expect(err).To(BeNil()) @@ -275,7 +275,7 @@ var _ = Describe("Getting ComponentInstanceFilterValues via API", Label("e2e", " func queryComponentInstanceFilter(port string, gqlQueryFilePath string) model.ComponentInstanceFilterValue { client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", port)) - + //nolint:gosec b, err := os.ReadFile(gqlQueryFilePath) Expect(err).To(BeNil()) diff --git a/internal/e2e/component_instance_query_test.go b/internal/e2e/component_instance_query_test.go index 66e4c1d14..ebada8849 100644 --- a/internal/e2e/component_instance_query_test.go +++ b/internal/e2e/component_instance_query_test.go @@ -47,7 +47,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -55,7 +55,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentInstance/minimal.graphql") Expect(err).To(BeNil()) @@ -90,7 +90,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentInstance/minimal.graphql") Expect(err).To(BeNil()) @@ -123,7 +123,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentInstance/directRelations.graphql") Expect(err).To(BeNil()) @@ -209,7 +209,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentInstance/withOrder.graphql") Expect(err).To(BeNil()) @@ -237,7 +237,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn Expect(err).To(BeNil(), "Error while unmarshaling") By("- returns the expected content in order", func() { - var prev string = "" + prev := "" for _, ci := range componentInstances.Edges { Expect(c.CompareString(*ci.Node.Region, prev)).Should(BeNumerically(">=", 0)) prev = *ci.Node.Region @@ -252,7 +252,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn Expect(err).To(BeNil(), "Error while unmarshaling") By("- returns the expected content in order", func() { - var prev string = "" + prev := "" for _, ci := range componentInstances.Edges { Expect(c.CompareString(*ci.Node.Namespace, prev)).Should(BeNumerically(">=", 0)) prev = *ci.Node.Namespace @@ -267,7 +267,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn Expect(err).To(BeNil(), "Error while unmarshaling") By("- returns the expected content in order", func() { - var prev string = "" + prev := "" for _, ci := range componentInstances.Edges { Expect(c.CompareString(*ci.Node.Cluster, prev)).Should(BeNumerically(">=", 0)) prev = *ci.Node.Cluster @@ -282,7 +282,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn Expect(err).To(BeNil(), "Error while unmarshaling") By("- returns the expected content in order", func() { - var prev string = "" + prev := "" for _, ci := range componentInstances.Edges { Expect(c.CompareString(*ci.Node.Domain, prev)).Should(BeNumerically(">=", 0)) prev = *ci.Node.Domain @@ -297,7 +297,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn Expect(err).To(BeNil(), "Error while unmarshaling") By("- returns the expected content in order", func() { - var prev string = "" + prev := "" for _, ci := range componentInstances.Edges { Expect(c.CompareString(*ci.Node.Project, prev)).Should(BeNumerically(">=", 0)) prev = *ci.Node.Project @@ -312,7 +312,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn Expect(err).To(BeNil(), "Error while unmarshaling") By("- returns the expected content in order", func() { - var prev string = "" + prev := "" for _, ci := range componentInstances.Edges { Expect(c.CompareString(*ci.Node.Pod, prev)).Should(BeNumerically(">=", 0)) prev = *ci.Node.Pod @@ -327,7 +327,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn Expect(err).To(BeNil(), "Error while unmarshaling") By("- returns the expected content in order", func() { - var prev string = "" + prev := "" for _, ci := range componentInstances.Edges { Expect(c.CompareString(*ci.Node.Container, prev)).Should(BeNumerically(">=", 0)) prev = *ci.Node.Container @@ -342,7 +342,7 @@ var _ = Describe("Getting ComponentInstances via API", Label("e2e", "ComponentIn Expect(err).To(BeNil(), "Error while unmarshaling") By("- returns the expected content in order", func() { - var prev int = -1 + prev := -1 for _, ci := range componentInstances.Edges { citEntity := entity.NewComponentInstanceType(ci.Node.Type.String()) Expect(citEntity.Index() >= prev).Should(BeTrue()) @@ -374,7 +374,7 @@ var _ = Describe("Creating ComponentInstance via API", Label("e2e", "ComponentIn AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -384,7 +384,7 @@ var _ = Describe("Creating ComponentInstance via API", Label("e2e", "ComponentIn componentInstance = testentity.NewFakeComponentInstanceEntity() componentInstance.ComponentVersionId = seedCollection.ComponentVersionRows[0].Id.Int64 componentInstance.ServiceId = seedCollection.ServiceRows[0].Id.Int64 - seeder.SeedScannerRunInstances("4b6d3167-473a-4150-87b3-01da70096727") + _ = seeder.SeedScannerRunInstances("4b6d3167-473a-4150-87b3-01da70096727") }) Context("and a mutation query is performed", Label("create.graphql"), func() { @@ -392,7 +392,7 @@ var _ = Describe("Creating ComponentInstance via API", Label("e2e", "ComponentIn // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentInstance/create.graphql") Expect(err).To(BeNil()) @@ -456,7 +456,7 @@ var _ = Describe("Updating componentInstance via API", Label("e2e", "ComponentIn AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -471,7 +471,7 @@ var _ = Describe("Updating componentInstance via API", Label("e2e", "ComponentIn // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentInstance/update.graphql") Expect(err).To(BeNil()) @@ -528,7 +528,7 @@ var _ = Describe("Deleting ComponentInstance via API", Label("e2e", "ComponentIn AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -543,7 +543,7 @@ var _ = Describe("Deleting ComponentInstance via API", Label("e2e", "ComponentIn // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentInstance/delete.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/component_query_test.go b/internal/e2e/component_query_test.go index 832fb6679..f9251f258 100644 --- a/internal/e2e/component_query_test.go +++ b/internal/e2e/component_query_test.go @@ -46,7 +46,7 @@ var _ = Describe("Getting Components via API", Label("e2e", "Components"), func( AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -54,7 +54,7 @@ var _ = Describe("Getting Components via API", Label("e2e", "Components"), func( // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/component/minimal.graphql") Expect(err).To(BeNil()) @@ -89,7 +89,7 @@ var _ = Describe("Getting Components via API", Label("e2e", "Components"), func( // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/component/minimal.graphql") Expect(err).To(BeNil()) @@ -122,7 +122,7 @@ var _ = Describe("Getting Components via API", Label("e2e", "Components"), func( // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/component/directRelations.graphql") Expect(err).To(BeNil()) @@ -204,7 +204,7 @@ var _ = Describe("Creating Component via API", Label("e2e", "Components"), func( AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -219,7 +219,7 @@ var _ = Describe("Creating Component via API", Label("e2e", "Components"), func( // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/component/create.graphql") Expect(err).To(BeNil()) @@ -270,7 +270,7 @@ var _ = Describe("Updating Component via API", Label("e2e", "Components"), func( AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -285,7 +285,7 @@ var _ = Describe("Updating Component via API", Label("e2e", "Components"), func( // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/component/update.graphql") Expect(err).To(BeNil()) @@ -335,7 +335,7 @@ var _ = Describe("Deleting Component via API", Label("e2e", "Components"), func( AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -350,7 +350,7 @@ var _ = Describe("Deleting Component via API", Label("e2e", "Components"), func( // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/component/delete.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/component_version_query_test.go b/internal/e2e/component_version_query_test.go index 2e266216a..2ce8e76bb 100644 --- a/internal/e2e/component_version_query_test.go +++ b/internal/e2e/component_version_query_test.go @@ -45,7 +45,7 @@ var _ = Describe("Getting ComponentVersions via API", Label("e2e", "ComponentVer AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -53,7 +53,7 @@ var _ = Describe("Getting ComponentVersions via API", Label("e2e", "ComponentVer // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentVersion/minimal.graphql") Expect(err).To(BeNil()) @@ -88,7 +88,7 @@ var _ = Describe("Getting ComponentVersions via API", Label("e2e", "ComponentVer // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentVersion/minimal.graphql") Expect(err).To(BeNil()) @@ -121,7 +121,7 @@ var _ = Describe("Getting ComponentVersions via API", Label("e2e", "ComponentVer // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentVersion/directRelations.graphql") Expect(err).To(BeNil()) @@ -237,7 +237,7 @@ var _ = Describe("Ordering ComponentVersion via API", Label("e2e", "ComponentVer AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) loadTestData := func() ([]mariadb.IssueVariantRow, []mariadb.ComponentVersionIssueRow, error) { @@ -326,7 +326,7 @@ var _ = Describe("Creating ComponentVersion via API", Label("e2e", "ComponentVer AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -341,7 +341,7 @@ var _ = Describe("Creating ComponentVersion via API", Label("e2e", "ComponentVer // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentVersion/create.graphql") Expect(err).To(BeNil()) @@ -393,7 +393,7 @@ var _ = Describe("Updating ComponentVersion via API", Label("e2e", "ComponentVer AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -408,7 +408,7 @@ var _ = Describe("Updating ComponentVersion via API", Label("e2e", "ComponentVer // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentVersion/update.graphql") Expect(err).To(BeNil()) @@ -461,7 +461,7 @@ var _ = Describe("Deleting ComponentVersion via API", Label("e2e", "ComponentVer AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -476,7 +476,7 @@ var _ = Describe("Deleting ComponentVersion via API", Label("e2e", "ComponentVer // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/componentVersion/delete.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/db_migration_test.go b/internal/e2e/db_migration_test.go index 181252edc..43eed222c 100644 --- a/internal/e2e/db_migration_test.go +++ b/internal/e2e/db_migration_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/jmoiron/sqlx" + "github.com/sirupsen/logrus" "github.com/cloudoperators/heureka/internal/database/mariadb" "github.com/cloudoperators/heureka/internal/server" @@ -120,7 +121,11 @@ func getMvTestTableMigrationVersion() string { func (dbmt *DbMigrationTest) tableExists(tableName string) bool { db := dbmt.dbConnect() - defer db.Close() + defer func() { + if err := db.Close(); err != nil { + logrus.Warnf("error during closing statement: %s", err) + } + }() var exists bool query := ` @@ -136,13 +141,17 @@ func (dbmt *DbMigrationTest) tableExists(tableName string) bool { var name string _ = rows.Scan(&name) } + Expect(err).To(BeNil()) return exists } func (dbmt *DbMigrationTest) countRows(tableName string) int { db := dbmt.dbConnect() - defer db.Close() + defer func() { + err := db.Close() + Expect(err).To(BeNil()) + }() query := fmt.Sprintf("SELECT COUNT(*) FROM `%s`", tableName) var count int @@ -165,7 +174,7 @@ func (dbmt *DbMigrationTest) setup() { } func (dbmt *DbMigrationTest) teardown() { - dbm.TestTearDown(dbmt.db) + _ = dbm.TestTearDown(dbmt.db) mariadb.MigrationFs = dbmt.heurekaMigration } diff --git a/internal/e2e/e2e_suite_test.go b/internal/e2e/e2e_suite_test.go index b826777b3..5c3afee01 100644 --- a/internal/e2e/e2e_suite_test.go +++ b/internal/e2e/e2e_suite_test.go @@ -7,19 +7,13 @@ import ( "fmt" "testing" - "github.com/cloudoperators/heureka/internal/database/mariadb" "github.com/cloudoperators/heureka/internal/database/mariadb/test" - util2 "github.com/cloudoperators/heureka/internal/util" "github.com/cloudoperators/heureka/pkg/util" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -var ( - dbConfig util2.Config - dbm *test.DatabaseManager - db *mariadb.SqlDatabase -) +var dbm *test.DatabaseManager func TestE2E(t *testing.T) { // Set the environment variables @@ -27,7 +21,8 @@ func TestE2E(t *testing.T) { if err != nil { panic(err) } - util.SetEnvVars(fmt.Sprintf("%s/%s", projectDir, ".test.env")) + + _ = util.SetEnvVars(fmt.Sprintf("%s/%s", projectDir, ".test.env")) RegisterFailHandler(Fail) RunSpecs(t, "e2e Suite") diff --git a/internal/e2e/evidence_query_test.go b/internal/e2e/evidence_query_test.go index 8136ac721..0261c1a01 100644 --- a/internal/e2e/evidence_query_test.go +++ b/internal/e2e/evidence_query_test.go @@ -26,6 +26,10 @@ import ( "github.com/sirupsen/logrus" ) +const ( + testDescription = "New Description" +) + var _ = Describe("Getting Evidences via API", Label("e2e", "Evidences"), func() { var seeder *test.DatabaseSeeder var s *server.Server @@ -45,7 +49,7 @@ var _ = Describe("Getting Evidences via API", Label("e2e", "Evidences"), func() AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -53,7 +57,7 @@ var _ = Describe("Getting Evidences via API", Label("e2e", "Evidences"), func() // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/evidence/minimal.graphql") Expect(err).To(BeNil()) @@ -90,7 +94,7 @@ var _ = Describe("Getting Evidences via API", Label("e2e", "Evidences"), func() // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/evidence/minimal.graphql") Expect(err).To(BeNil()) @@ -123,7 +127,7 @@ var _ = Describe("Getting Evidences via API", Label("e2e", "Evidences"), func() // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/evidence/directRelations.graphql") Expect(err).To(BeNil()) @@ -212,7 +216,7 @@ var _ = Describe("Creating Evidence via API", Label("e2e", "Evidences"), func() AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -229,7 +233,7 @@ var _ = Describe("Creating Evidence via API", Label("e2e", "Evidences"), func() // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/evidence/create.graphql") Expect(err).To(BeNil()) @@ -286,7 +290,7 @@ var _ = Describe("Updating evidence via API", Label("e2e", "Evidences"), func() AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -301,7 +305,7 @@ var _ = Describe("Updating evidence via API", Label("e2e", "Evidences"), func() // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/evidence/update.graphql") Expect(err).To(BeNil()) @@ -309,7 +313,7 @@ var _ = Describe("Updating evidence via API", Label("e2e", "Evidences"), func() req := graphql.NewRequest(str) evidence := seedCollection.EvidenceRows[0].AsEvidence() - evidence.Description = "New Description" + evidence.Description = testDescription req.Var("id", fmt.Sprintf("%d", evidence.Id)) req.Var("input", map[string]string{ @@ -356,7 +360,7 @@ var _ = Describe("Deleting Evidence via API", Label("e2e", "Evidences"), func() AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -371,7 +375,7 @@ var _ = Describe("Deleting Evidence via API", Label("e2e", "Evidences"), func() // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/evidence/delete.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/image_query_test.go b/internal/e2e/image_query_test.go index 4e507a9f5..8daa883fc 100644 --- a/internal/e2e/image_query_test.go +++ b/internal/e2e/image_query_test.go @@ -130,7 +130,7 @@ func newImageTest() *imageTest { func (it *imageTest) teardown() { e2e_common.ServerTeardown(it.server) - dbm.TestTearDown(it.db) + _ = dbm.TestTearDown(it.db) } func (it *imageTest) seed10Entries() { @@ -138,7 +138,7 @@ func (it *imageTest) seed10Entries() { for i := 0; i < 10; i++ { issue := test.NewFakeIssue() issue.Type.String = entity.IssueTypeVulnerability.String() - it.seeder.InsertFakeIssue(issue) + _, _ = it.seeder.InsertFakeIssue(issue) } it.components = it.seeder.SeedComponents(5) it.services = it.seeder.SeedServices(5) diff --git a/internal/e2e/image_version_query_test.go b/internal/e2e/image_version_query_test.go index 2712a5dbd..c30894307 100644 --- a/internal/e2e/image_version_query_test.go +++ b/internal/e2e/image_version_query_test.go @@ -39,7 +39,7 @@ var _ = Describe("Getting ImageVersions via API", Label("e2e", "ImageVersions"), AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) loadTestData := func() ([]mariadb.IssueVariantRow, []mariadb.ComponentVersionIssueRow, error) { @@ -95,7 +95,7 @@ var _ = Describe("Getting ImageVersions via API", Label("e2e", "ImageVersions"), _, err = seeder.InsertFakeIssueMatch(im) Expect(err).To(BeNil()) } - seeder.RefreshCountIssueRatings() + _ = seeder.RefreshCountIssueRatings() }) It("can query image versions", func() { diff --git a/internal/e2e/issue_counts_query_test.go b/internal/e2e/issue_counts_query_test.go index 62572a115..ebd1e2f31 100644 --- a/internal/e2e/issue_counts_query_test.go +++ b/internal/e2e/issue_counts_query_test.go @@ -42,7 +42,7 @@ var _ = Describe("Getting IssueCounts via API", Label("e2e", "IssueCounts"), fun AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has entries", func() { @@ -61,7 +61,7 @@ var _ = Describe("Getting IssueCounts via API", Label("e2e", "IssueCounts"), fun // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueCounts/query.graphql") Expect(err).To(BeNil()) @@ -99,7 +99,7 @@ var _ = Describe("Getting IssueCounts via API", Label("e2e", "IssueCounts"), fun // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/withIssueCounts.graphql") Expect(err).To(BeNil()) @@ -133,7 +133,7 @@ var _ = Describe("Getting IssueCounts via API", Label("e2e", "IssueCounts"), fun // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueCounts/query.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/issue_match_query_test.go b/internal/e2e/issue_match_query_test.go index 10f8e4805..670d04783 100644 --- a/internal/e2e/issue_match_query_test.go +++ b/internal/e2e/issue_match_query_test.go @@ -45,7 +45,7 @@ var _ = Describe("Getting IssueMatches via API", Label("e2e", "IssueMatches"), f AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -53,7 +53,7 @@ var _ = Describe("Getting IssueMatches via API", Label("e2e", "IssueMatches"), f // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueMatch/minimal.graphql") Expect(err).To(BeNil()) @@ -90,7 +90,7 @@ var _ = Describe("Getting IssueMatches via API", Label("e2e", "IssueMatches"), f // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueMatch/minimal.graphql") Expect(err).To(BeNil()) @@ -123,7 +123,7 @@ var _ = Describe("Getting IssueMatches via API", Label("e2e", "IssueMatches"), f // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueMatch/directRelations.graphql") Expect(err).To(BeNil()) @@ -203,7 +203,7 @@ var _ = Describe("Getting IssueMatches via API", Label("e2e", "IssueMatches"), f // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueMatch/withOrder.graphql") Expect(err).To(BeNil()) @@ -231,7 +231,7 @@ var _ = Describe("Getting IssueMatches via API", Label("e2e", "IssueMatches"), f }) By("- returns the expected content in order", func() { - var prev string = "" + prev := "" for _, im := range respData.IssueMatches.Edges { Expect(*im.Node.Issue.PrimaryName >= prev).Should(BeTrue()) prev = *im.Node.Issue.PrimaryName @@ -243,7 +243,7 @@ var _ = Describe("Getting IssueMatches via API", Label("e2e", "IssueMatches"), f // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueMatch/withOrder.graphql") Expect(err).To(BeNil()) @@ -272,8 +272,8 @@ var _ = Describe("Getting IssueMatches via API", Label("e2e", "IssueMatches"), f }) By("- returns the expected content in order", func() { - var prevPn string = "" - var prevTrd time.Time = time.Now() + prevPn := "" + prevTrd := time.Now() for _, im := range respData.IssueMatches.Edges { if *im.Node.Issue.PrimaryName == prevPn { trd, err := time.Parse("2006-01-02T15:04:05Z", *im.Node.TargetRemediationDate) @@ -313,7 +313,7 @@ var _ = Describe("Creating IssueMatch via API", Label("e2e", "IssueMatches"), fu AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) // use only 1 entry to make sure that all relations are resolved correctly @@ -333,7 +333,7 @@ var _ = Describe("Creating IssueMatch via API", Label("e2e", "IssueMatches"), fu // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueMatch/create.graphql") Expect(err).To(BeNil()) @@ -389,7 +389,7 @@ var _ = Describe("Updating issueMatch via API", Label("e2e", "IssueMatches"), fu AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -404,7 +404,7 @@ var _ = Describe("Updating issueMatch via API", Label("e2e", "IssueMatches"), fu // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueMatch/update.graphql") Expect(err).To(BeNil()) @@ -455,7 +455,7 @@ var _ = Describe("Deleting IssueMatch via API", Label("e2e", "IssueMatches"), fu AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -470,7 +470,7 @@ var _ = Describe("Deleting IssueMatch via API", Label("e2e", "IssueMatches"), fu // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueMatch/delete.graphql") Expect(err).To(BeNil()) @@ -516,7 +516,7 @@ var _ = Describe("Modifying Evidence of IssueMatch via API", Label("e2e", "Issue AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -531,7 +531,7 @@ var _ = Describe("Modifying Evidence of IssueMatch via API", Label("e2e", "Issue // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueMatch/addEvidence.graphql") Expect(err).To(BeNil()) @@ -576,7 +576,7 @@ var _ = Describe("Modifying Evidence of IssueMatch via API", Label("e2e", "Issue // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueMatch/removeEvidence.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/issue_query_test.go b/internal/e2e/issue_query_test.go index a031841ad..6709b5a43 100644 --- a/internal/e2e/issue_query_test.go +++ b/internal/e2e/issue_query_test.go @@ -45,7 +45,7 @@ var _ = Describe("Getting Issues via API", Label("e2e", "Issues"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -53,7 +53,7 @@ var _ = Describe("Getting Issues via API", Label("e2e", "Issues"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/minimal.graphql") Expect(err).To(BeNil()) @@ -90,7 +90,7 @@ var _ = Describe("Getting Issues via API", Label("e2e", "Issues"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/minimal.graphql") Expect(err).To(BeNil()) @@ -123,7 +123,7 @@ var _ = Describe("Getting Issues via API", Label("e2e", "Issues"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/directRelations.graphql") Expect(err).To(BeNil()) @@ -174,8 +174,8 @@ var _ = Describe("Getting Issues via API", Label("e2e", "Issues"), func() { for _, im := range issue.Node.IssueMatches.Edges { _, issueMatchFound := lo.Find(seedCollection.IssueMatchRows, func(row mariadb.IssueMatchRow) bool { return fmt.Sprintf("%d", row.Id.Int64) == im.Node.ID && // ID Matches - //@todo check and verify the date format comparison - //row.TargetRemediationDate.Time.String() == *vm.Node.TargetRemediationDate && // target remediation date matches + // @todo check and verify the date format comparison + // row.TargetRemediationDate.Time.String() == *vm.Node.TargetRemediationDate && // target remediation date matches fmt.Sprintf("%d", row.IssueId.Int64) == issue.Node.ID && // issue match belongs to the respective issue fmt.Sprintf("%d", row.ComponentInstanceId.Int64) == im.Node.ComponentInstance.ID // correct component instance attached to issue match }) @@ -203,7 +203,7 @@ var _ = Describe("Getting Issues via API", Label("e2e", "Issues"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/withObjectMetadata.graphql") Expect(err).To(BeNil()) @@ -247,7 +247,7 @@ var _ = Describe("Getting Issues via API", Label("e2e", "Issues"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/withOrder.graphql") Expect(err).To(BeNil()) @@ -275,7 +275,7 @@ var _ = Describe("Getting Issues via API", Label("e2e", "Issues"), func() { Expect(err).To(BeNil(), "Error while unmarshaling") By("- returns the expected content in order", func() { - var prev string = "" + prev := "" for _, i := range issues.Edges { Expect(*i.Node.PrimaryName >= prev).Should(BeTrue()) prev = *i.Node.PrimaryName @@ -330,7 +330,7 @@ var _ = Describe("Creating Issue via API", Label("e2e", "Issues"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -344,7 +344,7 @@ var _ = Describe("Creating Issue via API", Label("e2e", "Issues"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/create.graphql") Expect(err).To(BeNil()) @@ -394,7 +394,7 @@ var _ = Describe("Updating issue via API", Label("e2e", "Issues"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -409,7 +409,7 @@ var _ = Describe("Updating issue via API", Label("e2e", "Issues"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/update.graphql") Expect(err).To(BeNil()) @@ -459,7 +459,7 @@ var _ = Describe("Deleting Issue via API", Label("e2e", "Issues"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -474,7 +474,7 @@ var _ = Describe("Deleting Issue via API", Label("e2e", "Issues"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/delete.graphql") Expect(err).To(BeNil()) @@ -520,7 +520,7 @@ var _ = Describe("Modifying relationship of ComponentVersion of Issue via API", AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -535,7 +535,7 @@ var _ = Describe("Modifying relationship of ComponentVersion of Issue via API", // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/addComponentVersion.graphql") Expect(err).To(BeNil()) @@ -580,7 +580,7 @@ var _ = Describe("Modifying relationship of ComponentVersion of Issue via API", // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issue/removeComponentVersion.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/issue_repository_query_test.go b/internal/e2e/issue_repository_query_test.go index 365ddf7b2..f8472a3c7 100644 --- a/internal/e2e/issue_repository_query_test.go +++ b/internal/e2e/issue_repository_query_test.go @@ -44,7 +44,7 @@ var _ = Describe("Getting IssueRepositories via API", Label("e2e", "IssueReposit AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -52,7 +52,7 @@ var _ = Describe("Getting IssueRepositories via API", Label("e2e", "IssueReposit // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueRepository/minimal.graphql") Expect(err).To(BeNil()) @@ -89,7 +89,7 @@ var _ = Describe("Getting IssueRepositories via API", Label("e2e", "IssueReposit // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueRepository/minimal.graphql") Expect(err).To(BeNil()) @@ -122,7 +122,7 @@ var _ = Describe("Getting IssueRepositories via API", Label("e2e", "IssueReposit // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueRepository/directRelations.graphql") Expect(err).To(BeNil()) @@ -213,7 +213,7 @@ var _ = Describe("Creating IssueRepository via API", Label("e2e", "IssueReposito AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -227,7 +227,7 @@ var _ = Describe("Creating IssueRepository via API", Label("e2e", "IssueReposito // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueRepository/create.graphql") Expect(err).To(BeNil()) @@ -275,7 +275,7 @@ var _ = Describe("Updating issueRepository via API", Label("e2e", "IssueReposito AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -290,7 +290,7 @@ var _ = Describe("Updating issueRepository via API", Label("e2e", "IssueReposito // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueRepository/update.graphql") Expect(err).To(BeNil()) @@ -343,7 +343,7 @@ var _ = Describe("Deleting IssueRepository via API", Label("e2e", "IssueReposito AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -358,7 +358,7 @@ var _ = Describe("Deleting IssueRepository via API", Label("e2e", "IssueReposito // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueRepository/delete.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/issue_variant_query_test.go b/internal/e2e/issue_variant_query_test.go index 24d713ec8..0a2fab534 100644 --- a/internal/e2e/issue_variant_query_test.go +++ b/internal/e2e/issue_variant_query_test.go @@ -45,7 +45,7 @@ var _ = Describe("Getting IssueVariants via API", Label("e2e", "IssueVariants"), AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -53,7 +53,7 @@ var _ = Describe("Getting IssueVariants via API", Label("e2e", "IssueVariants"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueVariant/minimal.graphql") Expect(err).To(BeNil()) @@ -88,7 +88,7 @@ var _ = Describe("Getting IssueVariants via API", Label("e2e", "IssueVariants"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueVariant/minimal.graphql") Expect(err).To(BeNil()) @@ -121,7 +121,7 @@ var _ = Describe("Getting IssueVariants via API", Label("e2e", "IssueVariants"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueVariant/directRelations.graphql") Expect(err).To(BeNil()) @@ -209,7 +209,7 @@ var _ = Describe("Creating IssueVariant via API", Label("e2e", "IssueVariants"), AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -226,7 +226,7 @@ var _ = Describe("Creating IssueVariant via API", Label("e2e", "IssueVariants"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueVariant/create.graphql") Expect(err).To(BeNil()) @@ -263,7 +263,7 @@ var _ = Describe("Creating IssueVariant via API", Label("e2e", "IssueVariants"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueVariant/createWithRating.graphql") Expect(err).To(BeNil()) @@ -321,7 +321,7 @@ var _ = Describe("Updating issueVariant via API", Label("e2e", "IssueVariants"), AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -336,7 +336,7 @@ var _ = Describe("Updating issueVariant via API", Label("e2e", "IssueVariants"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueVariant/update.graphql") Expect(err).To(BeNil()) @@ -372,7 +372,7 @@ var _ = Describe("Updating issueVariant via API", Label("e2e", "IssueVariants"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueVariant/update.graphql") Expect(err).To(BeNil()) @@ -406,7 +406,7 @@ var _ = Describe("Updating issueVariant via API", Label("e2e", "IssueVariants"), Expect(string(*respData.IssueVariant.Severity.Value)).To(Equal(issueVariant.Severity.Value)) if respData.IssueVariant.Severity.Cvss != nil && respData.IssueVariant.Severity.Cvss.Vector != nil { - Expect(string(*respData.IssueVariant.Severity.Cvss.Vector)).To(BeEmpty()) + Expect(*respData.IssueVariant.Severity.Cvss.Vector).To(BeEmpty()) } }) }) @@ -432,7 +432,7 @@ var _ = Describe("Deleting IssueVariant via API", Label("e2e", "IssueVariants"), AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -447,7 +447,7 @@ var _ = Describe("Deleting IssueVariant via API", Label("e2e", "IssueVariants"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/issueVariant/delete.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/metadata_test.go b/internal/e2e/metadata_test.go index adda593f9..61c53aa45 100644 --- a/internal/e2e/metadata_test.go +++ b/internal/e2e/metadata_test.go @@ -100,7 +100,7 @@ var _ = Describe("Creating, updating and state filtering of entity via API", Lab AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("New issue is created via API", func() { diff --git a/internal/e2e/oidc_auth_test.go b/internal/e2e/oidc_auth_test.go index 5a40aae1e..a4424fe34 100644 --- a/internal/e2e/oidc_auth_test.go +++ b/internal/e2e/oidc_auth_test.go @@ -47,7 +47,7 @@ var _ = Describe("Getting access via API", Label("e2e", "OidcAuthorization"), fu AfterEach(func() { e2e_common.ServerTeardown(s) oidcProvider.Stop() - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("trying to access query resource with valid oidc token", func() { diff --git a/internal/e2e/patch_query_test.go b/internal/e2e/patch_query_test.go index faf507c81..15b6b1289 100644 --- a/internal/e2e/patch_query_test.go +++ b/internal/e2e/patch_query_test.go @@ -39,7 +39,7 @@ var _ = Describe("Getting Patches via API", Label("e2e", "Patches"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { diff --git a/internal/e2e/remediation_query_test.go b/internal/e2e/remediation_query_test.go index 5e5200d77..f142808e7 100644 --- a/internal/e2e/remediation_query_test.go +++ b/internal/e2e/remediation_query_test.go @@ -42,7 +42,7 @@ var _ = Describe("Getting Remediations via API", Label("e2e", "Remediations"), f AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -130,7 +130,7 @@ var _ = Describe("Creating Remediation via API", Label("e2e", "Remediations"), f AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -194,7 +194,7 @@ var _ = Describe("Updating remediation via API", Label("e2e", "Remediations"), f AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -305,7 +305,7 @@ var _ = Describe("Deleting Remediation via API", Label("e2e", "Remediations"), f AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { diff --git a/internal/e2e/scanner_run_query_test.go b/internal/e2e/scanner_run_query_test.go index 7c45646eb..67278bbfd 100644 --- a/internal/e2e/scanner_run_query_test.go +++ b/internal/e2e/scanner_run_query_test.go @@ -37,7 +37,7 @@ var _ = Describe("Creating ScannerRun via API", Label("e2e", "ScannerRun"), func AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -49,7 +49,7 @@ var _ = Describe("Creating ScannerRun via API", Label("e2e", "ScannerRun"), func // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/scannerRun/create.graphql") Expect(err).To(BeNil()) @@ -83,7 +83,7 @@ var _ = Describe("Creating ScannerRun via API", Label("e2e", "ScannerRun"), func // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/scannerRun/create.graphql") Expect(err).To(BeNil()) @@ -139,7 +139,7 @@ var _ = Describe("Creating ScannerRun via API", Label("e2e", "ScannerRun"), func // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/scannerRun/create.graphql") Expect(err).To(BeNil()) @@ -206,7 +206,7 @@ var _ = Describe("Querying ScannerRun via API", Label("e2e", "ScannerRun"), func AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { diff --git a/internal/e2e/service_filter_query_test.go b/internal/e2e/service_filter_query_test.go index 149dcb8b3..374215824 100644 --- a/internal/e2e/service_filter_query_test.go +++ b/internal/e2e/service_filter_query_test.go @@ -43,7 +43,7 @@ var _ = Describe("Getting ServiceFilterValues via API", Label("e2e", "ServiceFil AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -51,7 +51,7 @@ var _ = Describe("Getting ServiceFilterValues via API", Label("e2e", "ServiceFil // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/serviceFilter/serviceCcrns.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/service_query_test.go b/internal/e2e/service_query_test.go index 15dd85235..2e0649054 100644 --- a/internal/e2e/service_query_test.go +++ b/internal/e2e/service_query_test.go @@ -48,7 +48,7 @@ var _ = Describe("Getting Services via API", Label("e2e", "Services"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) seeder.CloseDbConnection() - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -56,7 +56,7 @@ var _ = Describe("Getting Services via API", Label("e2e", "Services"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/minimal.graphql") Expect(err).To(BeNil()) @@ -91,7 +91,7 @@ var _ = Describe("Getting Services via API", Label("e2e", "Services"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/minimal.graphql") Expect(err).To(BeNil()) @@ -121,7 +121,7 @@ var _ = Describe("Getting Services via API", Label("e2e", "Services"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/withObjectMetadata.graphql") Expect(err).To(BeNil()) @@ -162,7 +162,7 @@ var _ = Describe("Getting Services via API", Label("e2e", "Services"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/directRelations.graphql") Expect(err).To(BeNil()) @@ -290,7 +290,7 @@ var _ = Describe("Getting Services via API", Label("e2e", "Services"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/withOrder.graphql") Expect(err).To(BeNil()) @@ -318,7 +318,7 @@ var _ = Describe("Getting Services via API", Label("e2e", "Services"), func() { }) By("- returns the expected content in order", func() { - var prev string = "" + prev := "" for _, im := range respData.Services.Edges { Expect(c.CompareString(*im.Node.Ccrn, prev)).Should(BeNumerically(">=", 0)) prev = *im.Node.Ccrn @@ -436,7 +436,7 @@ var _ = Describe("Creating Service via API", Label("e2e", "Services"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) seeder.CloseDbConnection() - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -450,7 +450,7 @@ var _ = Describe("Creating Service via API", Label("e2e", "Services"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/create.graphql") Expect(err).To(BeNil()) @@ -497,7 +497,7 @@ var _ = Describe("Updating service via API", Label("e2e", "Services"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) seeder.CloseDbConnection() - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -512,7 +512,7 @@ var _ = Describe("Updating service via API", Label("e2e", "Services"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/update.graphql") Expect(err).To(BeNil()) @@ -563,7 +563,7 @@ var _ = Describe("Deleting Service via API", Label("e2e", "Services"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) seeder.CloseDbConnection() - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -578,7 +578,7 @@ var _ = Describe("Deleting Service via API", Label("e2e", "Services"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/delete.graphql") Expect(err).To(BeNil()) @@ -625,7 +625,7 @@ var _ = Describe("Modifying Owner of Service via API", Label("e2e", "Services"), AfterEach(func() { e2e_common.ServerTeardown(s) seeder.CloseDbConnection() - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -640,7 +640,7 @@ var _ = Describe("Modifying Owner of Service via API", Label("e2e", "Services"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/addOwner.graphql") Expect(err).To(BeNil()) @@ -683,7 +683,7 @@ var _ = Describe("Modifying Owner of Service via API", Label("e2e", "Services"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/removeOwner.graphql") Expect(err).To(BeNil()) @@ -741,7 +741,7 @@ var _ = Describe("Modifying IssueRepository of Service via API", Label("e2e", "S AfterEach(func() { e2e_common.ServerTeardown(s) seeder.CloseDbConnection() - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -757,7 +757,7 @@ var _ = Describe("Modifying IssueRepository of Service via API", Label("e2e", "S // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/addIssueRepository.graphql") Expect(err).To(BeNil()) @@ -802,7 +802,7 @@ var _ = Describe("Modifying IssueRepository of Service via API", Label("e2e", "S // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/service/removeIssueRepository.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/support_group_query_test.go b/internal/e2e/support_group_query_test.go index b408ec6d8..118d5df4c 100644 --- a/internal/e2e/support_group_query_test.go +++ b/internal/e2e/support_group_query_test.go @@ -48,7 +48,7 @@ var _ = Describe("Getting SupportGroups via API", Label("e2e", "SupportGroups"), AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -56,7 +56,7 @@ var _ = Describe("Getting SupportGroups via API", Label("e2e", "SupportGroups"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/supportGroup/minimal.graphql") Expect(err).To(BeNil()) @@ -94,7 +94,7 @@ var _ = Describe("Getting SupportGroups via API", Label("e2e", "SupportGroups"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/supportGroup/minimal.graphql") Expect(err).To(BeNil()) @@ -134,7 +134,7 @@ var _ = Describe("Getting SupportGroups via API", Label("e2e", "SupportGroups"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/supportGroup/directRelations.graphql") Expect(err).To(BeNil()) @@ -221,7 +221,7 @@ var _ = Describe("Getting SupportGroups via API", Label("e2e", "SupportGroups"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/supportGroup/withOrder.graphql") Expect(err).To(BeNil()) @@ -249,7 +249,7 @@ var _ = Describe("Getting SupportGroups via API", Label("e2e", "SupportGroups"), }) By("- returns the expected content in order", func() { - var prev string = "" + prev := "" for _, im := range respData.SupportGroups.Edges { Expect(c.CompareString(*im.Node.Ccrn, prev)).Should(BeNumerically(">=", 0)) prev = *im.Node.Ccrn @@ -280,7 +280,7 @@ var _ = Describe("Creating SupportGroup via API", Label("e2e", "SupportGroups"), AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -294,7 +294,7 @@ var _ = Describe("Creating SupportGroup via API", Label("e2e", "SupportGroups"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/supportGroup/create.graphql") Expect(err).To(BeNil()) @@ -340,7 +340,7 @@ var _ = Describe("Updating SupportGroup via API", Label("e2e", "SupportGroups"), AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -355,7 +355,7 @@ var _ = Describe("Updating SupportGroup via API", Label("e2e", "SupportGroups"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/supportGroup/update.graphql") Expect(err).To(BeNil()) @@ -405,7 +405,7 @@ var _ = Describe("Deleting SupportGroup via API", Label("e2e", "SupportGroups"), AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -420,7 +420,7 @@ var _ = Describe("Deleting SupportGroup via API", Label("e2e", "SupportGroups"), // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/supportGroup/delete.graphql") Expect(err).To(BeNil()) @@ -466,7 +466,7 @@ var _ = Describe("Modifying Services of SupportGroup via API", Label("e2e", "Sup AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -481,7 +481,7 @@ var _ = Describe("Modifying Services of SupportGroup via API", Label("e2e", "Sup // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/supportGroup/addService.graphql") Expect(err).To(BeNil()) @@ -526,7 +526,7 @@ var _ = Describe("Modifying Services of SupportGroup via API", Label("e2e", "Sup // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/supportGroup/removeService.graphql") Expect(err).To(BeNil()) @@ -583,7 +583,7 @@ var _ = Describe("Modifying Users of SupportGroup via API", Label("e2e", "Suppor AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -598,7 +598,7 @@ var _ = Describe("Modifying Users of SupportGroup via API", Label("e2e", "Suppor // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/supportGroup/addUser.graphql") Expect(err).To(BeNil()) @@ -645,7 +645,7 @@ var _ = Describe("Modifying Users of SupportGroup via API", Label("e2e", "Suppor // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/supportGroup/removeUser.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/token_auth_test.go b/internal/e2e/token_auth_test.go index e72ab07f2..63fce315a 100644 --- a/internal/e2e/token_auth_test.go +++ b/internal/e2e/token_auth_test.go @@ -36,7 +36,7 @@ var _ = Describe("Getting access via API", Label("e2e", "TokenAuthorization"), f AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("trying to access query resource with valid token", func() { diff --git a/internal/e2e/user_query_test.go b/internal/e2e/user_query_test.go index c38d4a975..48d825500 100644 --- a/internal/e2e/user_query_test.go +++ b/internal/e2e/user_query_test.go @@ -45,7 +45,7 @@ var _ = Describe("Getting Users via API", Label("e2e", "Users"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database is empty", func() { @@ -53,7 +53,7 @@ var _ = Describe("Getting Users via API", Label("e2e", "Users"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/user/minimal.graphql") Expect(err).To(BeNil()) @@ -89,7 +89,7 @@ var _ = Describe("Getting Users via API", Label("e2e", "Users"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/user/minimal.graphql") Expect(err).To(BeNil()) @@ -122,7 +122,7 @@ var _ = Describe("Getting Users via API", Label("e2e", "Users"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/user/directRelations.graphql") Expect(err).To(BeNil()) @@ -214,7 +214,7 @@ var _ = Describe("Creating User via API", Label("e2e", "Users"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -254,7 +254,7 @@ var _ = Describe("Updating User via API", Label("e2e", "Users"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -297,7 +297,7 @@ var _ = Describe("Deleting User via API", Label("e2e", "Users"), func() { AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { @@ -312,7 +312,7 @@ var _ = Describe("Deleting User via API", Label("e2e", "Users"), func() { // create a queryCollection (safe to share across requests) client := graphql.NewClient(fmt.Sprintf("http://localhost:%s/query", cfg.Port)) - //@todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? + // @todo may need to make this more fault proof?! What if the test is executed from the root dir? does it still work? b, err := os.ReadFile("../api/graphql/graph/queryCollection/user/delete.graphql") Expect(err).To(BeNil()) diff --git a/internal/e2e/vulnerability_filter_query_test.go b/internal/e2e/vulnerability_filter_query_test.go index 7dc2ca5b3..cf27a8c53 100644 --- a/internal/e2e/vulnerability_filter_query_test.go +++ b/internal/e2e/vulnerability_filter_query_test.go @@ -43,7 +43,7 @@ var _ = Describe("Getting VulnerabilityFilterValues via API", Label("e2e", "Vuln AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) When("the database has 10 entries", func() { diff --git a/internal/e2e/vulnerability_query_test.go b/internal/e2e/vulnerability_query_test.go index d0f2033d3..50a5dce34 100644 --- a/internal/e2e/vulnerability_query_test.go +++ b/internal/e2e/vulnerability_query_test.go @@ -42,7 +42,7 @@ var _ = Describe("Getting Vulnerabilities via API", Label("e2e", "Vulnerabilitie AfterEach(func() { e2e_common.ServerTeardown(s) - dbm.TestTearDown(db) + _ = dbm.TestTearDown(db) }) loadTestData := func() ([]mariadb.ComponentInstanceRow, []mariadb.IssueVariantRow, []mariadb.ComponentVersionIssueRow, []mariadb.IssueMatchRow, error) { @@ -74,7 +74,7 @@ var _ = Describe("Getting Vulnerabilities via API", Label("e2e", "Vulnerabilitie for i := 0; i < 10; i++ { issue := test.NewFakeIssue() issue.Type.String = entity.IssueTypeVulnerability.String() - seeder.InsertFakeIssue(issue) + _, _ = seeder.InsertFakeIssue(issue) } components := seeder.SeedComponents(1) seeder.SeedComponentVersions(10, components) @@ -130,7 +130,7 @@ var _ = Describe("Getting Vulnerabilities via API", Label("e2e", "Vulnerabilitie Expect(err).To(BeNil(), "Error while unmarshaling") Expect(respData.Vulnerabilities.TotalCount).To(Equal(10)) Expect(len(respData.Vulnerabilities.Edges)).To(Equal(5)) - var prevSeverity int = 100 + prevSeverity := 100 for _, vulnerability := range respData.Vulnerabilities.Edges { for _, service := range vulnerability.Node.Services.Edges { Expect(service.Node.Ccrn).ToNot(BeNil(), "service has a ccrn set") diff --git a/internal/entity/common.go b/internal/entity/common.go index b6ede6c15..d129f9866 100644 --- a/internal/entity/common.go +++ b/internal/entity/common.go @@ -128,8 +128,8 @@ type PageInfo struct { IsValidPage *bool `json:"is_valid_page,omitempty"` PageNumber *int `json:"page_number,omitempty"` NextPageAfter *string `json:"next_page_after,omitempty"` - StartCursor *string `json:"deprecated,omitempty"` //@todo remove as deprecated - EndCursor *string `json:"end_cursor,omitempty"` //@todo remove as deprecated + StartCursor *string `json:"deprecated,omitempty"` // @todo remove as deprecated + EndCursor *string `json:"end_cursor,omitempty"` // @todo remove as deprecated Pages []Page `json:"pages,omitempty"` } diff --git a/internal/entity/issue_repository.go b/internal/entity/issue_repository.go index 5097b1104..99cf43f8f 100644 --- a/internal/entity/issue_repository.go +++ b/internal/entity/issue_repository.go @@ -36,6 +36,9 @@ func NewIssueRepositoryFilter() *IssueRepositoryFilter { type IssueRepositoryAggregations struct{} +// nolint due to embedding structures with the same fields +// +//nolint:govet type IssueRepository struct { BaseIssueRepository IssueRepositoryService diff --git a/internal/entity/service.go b/internal/entity/service.go index 3136a7987..b84064fda 100644 --- a/internal/entity/service.go +++ b/internal/entity/service.go @@ -21,6 +21,9 @@ type ServiceAggregations struct { IssueMatches int64 } +// nolint due to embedding structures with the same fields +// +//nolint:govet type ServiceWithAggregations struct { Service ServiceAggregations @@ -44,6 +47,9 @@ type ServiceFilter struct { State []StateFilterType `json:"state"` } +// nolint due to embedding structures with the same fields +// +//nolint:govet type Service struct { BaseService IssueRepositoryService diff --git a/internal/entity/test/component_instance.go b/internal/entity/test/component_instance.go index 348e3bd60..02d0ae88e 100644 --- a/internal/entity/test/component_instance.go +++ b/internal/entity/test/component_instance.go @@ -27,19 +27,20 @@ func NewFakeComponentInstanceEntity() entity.ComponentInstance { "my_ip": gofakeit.IPv4Address(), } return entity.ComponentInstance{ - Id: int64(gofakeit.Number(1, 10000000)), - CCRN: test.GenerateFakeCcrn(cluster, namespace), - Region: region, - Cluster: cluster, - Namespace: namespace, - Domain: domain, - Project: project, - Pod: pod, - Container: container, - Type: entity.NewComponentInstanceType(t), - ParentId: int64(gofakeit.Number(1, 10000000)), - Context: &context, - Count: int16(gofakeit.Number(1, 100)), + Id: int64(gofakeit.Number(1, 10000000)), + CCRN: test.GenerateFakeCcrn(cluster, namespace), + Region: region, + Cluster: cluster, + Namespace: namespace, + Domain: domain, + Project: project, + Pod: pod, + Container: container, + Type: entity.NewComponentInstanceType(t), + ParentId: int64(gofakeit.Number(1, 10000000)), + Context: &context, + // nolint due to int16 won't overflow + Count: int16(gofakeit.Number(1, 100)), //nolint: gosec ComponentVersion: nil, ComponentVersionId: int64(gofakeit.Number(1, 10000000)), Service: nil, diff --git a/internal/entity/user.go b/internal/entity/user.go index 2d7ba81e5..681b81b84 100644 --- a/internal/entity/user.go +++ b/internal/entity/user.go @@ -42,22 +42,24 @@ type UserResult struct { } func GetUserTypeFromString(uts string) UserType { - if uts == "user" { + switch uts { + case "user": return HumanUserType - } else if uts == "technical" { + case "technical": return TechnicalUserType - } else if uts == "mail_list" { + case "mail_list": return MailingListUserType } return InvalidUserType } func GetUserTypeString(ut UserType) string { - if ut == HumanUserType { + switch ut { + case HumanUserType: return "user" - } else if ut == TechnicalUserType { + case TechnicalUserType: return "technical" - } else if ut == MailingListUserType { // Handle the new user type + case MailingListUserType: // Handle the new user type return "mail_list" } return "" diff --git a/internal/errors/helpers.go b/internal/errors/helpers.go index 648ed7aa1..8917883c2 100644 --- a/internal/errors/helpers.go +++ b/internal/errors/helpers.go @@ -25,13 +25,14 @@ func E(args ...interface{}) *Error { case Op: e.Op = string(a) case string: + switch { // If no entity is set, treat string as entity - if e.Entity == "" { + case e.Entity == "": e.Entity = a - } else if e.ID == "" { + case e.ID == "": // If entity is set but ID is not, treat string as ID e.ID = a - } else if e.Message == "" { + case e.Message == "": // If both entity and ID are set, treat as message e.Message = a } diff --git a/internal/openfga/authz.go b/internal/openfga/authz.go index 8692abfa3..d98e95db5 100644 --- a/internal/openfga/authz.go +++ b/internal/openfga/authz.go @@ -55,7 +55,9 @@ func NewAuthz(l *logrus.Logger, cfg *util.Config) Authorization { storeId = store.Id } // update the storeId of the current instance - fgaClient.SetStoreId(storeId) + if err := fgaClient.SetStoreId(storeId); err != nil { + l.Error("failed to update current storeID: ", err) + } // Check if the model already exists, otherwise create it modelId, err := CheckModel(fgaClient, storeId) @@ -81,7 +83,9 @@ func NewAuthz(l *logrus.Logger, cfg *util.Config) Authorization { modelId = modelResponse.AuthorizationModelId } // update the modelId of the current instance - fgaClient.SetAuthorizationModelId(modelId) + if err := fgaClient.SetAuthorizationModelId(modelId); err != nil { + l.Error("failed to update modelId for current instance: ", err) + } l.Info("Initializing authorization with OpenFGA") return &Authz{config: cfg, logger: l, client: fgaClient} @@ -89,6 +93,7 @@ func NewAuthz(l *logrus.Logger, cfg *util.Config) Authorization { // Reads the authorization model from a file, before creating the model in OpenFGA func getAuthModelRequestFromFile(filePath string) (*client.ClientWriteAuthorizationModelRequest, error) { + //nolint:gosec modelBytes, err := os.ReadFile(filePath) if err != nil { return nil, err @@ -141,7 +146,7 @@ func CheckModel(fgaClient *client.OpenFgaClient, storeId string) (string, error) func (a *Authz) CheckTuple(r RelationInput) (bool, error) { userString := string(r.UserType) + ":" + string(r.UserId) relationString := string(r.Relation) - objectString := string(r.ObjectType) + ":" + string(r.ObjectId) + objectString := string(r.ObjectType) + ":" + r.ObjectId req := client.ClientReadRequest{ User: &userString, @@ -162,7 +167,7 @@ func (a *Authz) CheckPermission(p PermissionInput) (bool, error) { req := client.ClientCheckRequest{ User: string(p.UserType) + ":" + string(p.UserId), Relation: string(p.Relation), - Object: string(p.ObjectType) + ":" + string(p.ObjectId), + Object: string(p.ObjectType) + ":" + p.ObjectId, } resp, err := a.client.Check(context.Background()).Body(req).Execute() if err != nil { @@ -182,7 +187,7 @@ func (a *Authz) AddRelation(r RelationInput) error { { User: string(r.UserType) + ":" + string(r.UserId), Relation: string(r.Relation), - Object: string(r.ObjectType) + ":" + string(r.ObjectId), + Object: string(r.ObjectType) + ":" + r.ObjectId, }, }, } @@ -209,7 +214,7 @@ func (a *Authz) RemoveRelation(r RelationInput) error { { User: string(r.UserType) + ":" + string(r.UserId), Relation: string(r.Relation), - Object: string(r.ObjectType) + ":" + string(r.ObjectId), + Object: string(r.ObjectType) + ":" + r.ObjectId, }, }, } diff --git a/internal/openfga/authz_test.go b/internal/openfga/authz_test.go index 8ce5e5393..5e06f5b79 100644 --- a/internal/openfga/authz_test.go +++ b/internal/openfga/authz_test.go @@ -22,6 +22,12 @@ const ( readerRel = "reader" writerRel = "writer" ownerRel = "owner" + + document1 = "document1" + document2 = "document2" + document3 = "document3" + + read = "read" ) var ( @@ -177,7 +183,7 @@ var _ = Describe("Authz", func() { Describe("ListAccessibleResources", func() { It("should return an empty slice and no error", func() { - p.ObjectId = "read" + p.ObjectId = read resources, err := authz.ListAccessibleResources(p) Expect(err).To(BeNil()) Expect(resources).To(BeEmpty()) @@ -189,7 +195,7 @@ var _ = Describe("Authz", func() { Expect(err).To(BeNil()) p.ObjectType = "invalid_type" - p.ObjectId = "read" + p.ObjectId = read p.Relation = ownerRel resources, err := authz.ListAccessibleResources(p) Expect(err).NotTo(BeNil()) @@ -202,11 +208,11 @@ var _ = Describe("Authz", func() { Expect(err).To(BeNil()) expectedResult := []openfga.AccessibleResource{ - {ObjectType: documentType, ObjectId: "document1"}, + {ObjectType: documentType, ObjectId: document1}, } p.Relation = ownerRel - p.ObjectId = "read" + p.ObjectId = read resources, err := authz.ListAccessibleResources(p) Expect(err).To(BeNil()) Expect(resources).To(Equal(expectedResult)) @@ -214,24 +220,24 @@ var _ = Describe("Authz", func() { It("should return a list with multiple resources after adding relations", func() { r.Relation = ownerRel - r.ObjectId = "document1" + r.ObjectId = document1 err := authz.AddRelation(r) Expect(err).To(BeNil()) - r.ObjectId = "document2" + r.ObjectId = document2 err = authz.AddRelation(r) Expect(err).To(BeNil()) - r.ObjectId = "document3" + r.ObjectId = document3 err = authz.AddRelation(r) Expect(err).To(BeNil()) expectedResult := []openfga.AccessibleResource{ - {ObjectType: documentType, ObjectId: "document1"}, - {ObjectType: documentType, ObjectId: "document2"}, - {ObjectType: documentType, ObjectId: "document3"}, + {ObjectType: documentType, ObjectId: document1}, + {ObjectType: documentType, ObjectId: document2}, + {ObjectType: documentType, ObjectId: document3}, } p.Relation = ownerRel - p.ObjectId = "read" + p.ObjectId = read resources, err := authz.ListAccessibleResources(p) Expect(err).To(BeNil()) Expect(resources).To(ConsistOf(expectedResult)) @@ -241,25 +247,25 @@ var _ = Describe("Authz", func() { r.Relation = ownerRel err := authz.AddRelation(r) Expect(err).To(BeNil()) - r.ObjectId = "document2" + r.ObjectId = document2 err = authz.AddRelation(r) Expect(err).To(BeNil()) - r.ObjectId = "document3" + r.ObjectId = document3 err = authz.AddRelation(r) Expect(err).To(BeNil()) - r.ObjectId = "document1" + r.ObjectId = document1 err = authz.RemoveRelation(r) Expect(err).To(BeNil()) - r.ObjectId = "document2" + r.ObjectId = document2 err = authz.RemoveRelation(r) Expect(err).To(BeNil()) - r.ObjectId = "document3" + r.ObjectId = document3 err = authz.RemoveRelation(r) Expect(err).To(BeNil()) p.Relation = ownerRel - p.ObjectId = "read" + p.ObjectId = read resources, err := authz.ListAccessibleResources(p) Expect(err).To(BeNil()) Expect(resources).To(BeEmpty()) diff --git a/internal/openfga/interface.go b/internal/openfga/interface.go index 412807765..f60ede0c8 100644 --- a/internal/openfga/interface.go +++ b/internal/openfga/interface.go @@ -4,7 +4,7 @@ package openfga import ( - "io/ioutil" + "io" "github.com/cloudoperators/heureka/internal/util" "github.com/sirupsen/logrus" @@ -63,7 +63,7 @@ func NewAuthorizationHandler(cfg *util.Config, enablelog bool) Authorization { func newLogger(enableLog bool) *logrus.Logger { l := logrus.New() if !enableLog { - l.SetOutput(ioutil.Discard) + l.SetOutput(io.Discard) } return l } diff --git a/internal/server/server.go b/internal/server/server.go index 12d48e41b..1799c51ee 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -6,7 +6,6 @@ package server import ( "context" "fmt" - "log" "net/http" "os" "os/signal" @@ -84,7 +83,7 @@ func NewServer(cfg util.Config) *Server { signal.Notify(s.sigs, syscall.SIGINT, syscall.SIGTERM) go func() { sig := <-s.sigs - logrus.Warn("Received signal: '%s'. Starting server shutdown.", sig) + logrus.Warn(fmt.Sprintf("Received signal: '%s'. Starting server shutdown.", sig)) cancel() }() @@ -176,6 +175,8 @@ func (s *Server) Start() { } func (s *Server) NonBlockingStart() { + // nolint due to unset values for timeouts + //nolint:gosec s.nonBlockingSrv = &http.Server{ Addr: fmt.Sprintf(":%s", s.config.Port), Handler: s.router.Handler(), @@ -190,10 +191,10 @@ func (s *Server) BlockingStop() { defer cancel() if err := s.nonBlockingSrv.Shutdown(ctx); err != nil { - log.Fatal("Server forced to shutdown: ", err) + panic(fmt.Errorf("server forced to shutdown: %w", err)) } if err := s.graphQLAPI.App.Shutdown(); err != nil { - log.Fatalf("Error while shuting down Heureka App: %s", err) + panic(fmt.Errorf("error while shuting down Heureka App: %s", err)) } done := make(chan struct{}) go func() { @@ -205,7 +206,7 @@ func (s *Server) BlockingStop() { case <-done: logrus.Info("All goroutines exited cleanly.") case <-ctx.Done(): - log.Fatalf("Timeout: some goroutines did not exit in time.") + panic(fmt.Errorf("timeout: some goroutines did not exit in time")) } } diff --git a/internal/util/config.go b/internal/util/config.go index d6bf8c040..878339f37 100644 --- a/internal/util/config.go +++ b/internal/util/config.go @@ -25,14 +25,14 @@ type Config struct { DBMaxIdleConnections int `envconfig:"DB_MAX_IDLE_CONNECTIONS" default:"10" json:"dBMaxIdleConnections"` DBMaxOpenConnections int `envconfig:"DB_MAX_OPEN_CONNECTIONS" default:"100" json:"dbMaxOpenConnections"` DBTrace bool `envconfig:"DB_TRACE" default:"false" json:"-"` - //VasApiAddress string `envconfig:"VAS_API_ADDRESS" required:"true" json:"vasApiAddress"` - //VasApiToken string `envconfig:"VAS_API_TOKEN" required:"true" json:"-"` - //NvdApiToken string `envconfig:"NVD_API_TOKEN" required:"true" json:"-"` - //OidcClientId string `envconfig:"OIDC_CLIENT_ID" required:"true" json:"-"` - //OidcUrl string `envconfig:"OIDC_URL" required:"true" json:"-"` - //Environment string `envconfig:"ENVIRONMENT" required:"true" json:"environment"` - //// https://pkg.go.dev/github.com/robfig/cron#hdr-Predefined_schedules - //DiscoverySchedule string `envconfig:"DISOVERY_SCHEDULE" default:"0 0 0 * * *" json:"discoverySchedule"` + // VasApiAddress string `envconfig:"VAS_API_ADDRESS" required:"true" json:"vasApiAddress"` + // VasApiToken string `envconfig:"VAS_API_TOKEN" required:"true" json:"-"` + // NvdApiToken string `envconfig:"NVD_API_TOKEN" required:"true" json:"-"` + // OidcClientId string `envconfig:"OIDC_CLIENT_ID" required:"true" json:"-"` + // OidcUrl string `envconfig:"OIDC_URL" required:"true" json:"-"` + // Environment string `envconfig:"ENVIRONMENT" required:"true" json:"environment"` + // https://pkg.go.dev/github.com/robfig/cron#hdr-Predefined_schedules + // DiscoverySchedule string `envconfig:"DISOVERY_SCHEDULE" default:"0 0 0 * * *" json:"discoverySchedule"` SeedMode bool `envconfig:"SEED_MODE" required:"false" default:"false" json:"seedMode"` AuthTokenSecret string `envconfig:"AUTH_TOKEN_SECRET" required:"false" json:"-"` AuthOidcClientId string `envconfig:"AUTH_OIDC_CLIENT_ID" required:"false" json:"-"` @@ -58,30 +58,30 @@ type Config struct { func (c *Config) ConfigToConsole() { data := [][]string{ {"Port:", c.Port}, - //{"Regions", fmt.Sprintf("%v", c.Regions)}, - //{"CloudAdmin Username", c.CloudAdminUsername}, - //{"CloudAdmin Password", strings.Repeat("*", 10)}, + // {"Regions", fmt.Sprintf("%v", c.Regions)}, + // {"CloudAdmin Username", c.CloudAdminUsername}, + // {"CloudAdmin Password", strings.Repeat("*", 10)}, {"Database Address", c.DBAddress}, {"Database Port", c.DBPort}, {"Database Name", c.DBName}, {"Database Username", c.DBUser}, {"Database Password", strings.Repeat("*", 10)}, - //{"VAS API Address", c.VasApiAddress}, - //{"Environment", c.Environment}, - //{"Postgres Password", strings.Repeat("*", 10)}, - //{"VAS API Token", strings.Repeat("*", 10)}, - //{"NVD API Token", strings.Repeat("*", 10)}, - //{"OIDC Client Id", strings.Repeat("*", 10)}, - //{"OIDC URL", c.OidcUrl}, - //{"Discovery Schedule", c.DiscoverySchedule}, + // {"VAS API Address", c.VasApiAddress}, + // {"Environment", c.Environment}, + // {"Postgres Password", strings.Repeat("*", 10)}, + // {"VAS API Token", strings.Repeat("*", 10)}, + // {"NVD API Token", strings.Repeat("*", 10)}, + // {"OIDC Client Id", strings.Repeat("*", 10)}, + // {"OIDC URL", c.OidcUrl}, + // {"Discovery Schedule", c.DiscoverySchedule}, } table := tablewriter.NewWriter(os.Stdout) table.Header([]string{"Variable", "Value"}) table.Configure(func(config *tablewriter.Config) { - config.Row.Formatting.Alignment = tw.AlignLeft + config.Row.Alignment.Global = tw.AlignLeft }) - table.Bulk(data) - table.Render() + _ = table.Bulk(data) + _ = table.Render() } const HeurekaFiglet = ` diff --git a/internal/util/slice.go b/internal/util/slice.go index 81b9ecde6..dcbe8e8ff 100644 --- a/internal/util/slice.go +++ b/internal/util/slice.go @@ -23,12 +23,12 @@ func FindMaxBy[E any, T constraints.Ordered](s []E, fn func(val E) (T, error)) ( v, err := fn(s[i]) if err != nil { - return nil, errors.New("Error in FindMaxBy Callback function") + return nil, errors.New("error in FindMaxBy Callback function") } m, err := fn(max) if err != nil { - return nil, errors.New("Error in FindMaxBy Callback function") + return nil, errors.New("error in FindMaxBy Callback function") } if v > m { max = s[i] diff --git a/pkg/log/config.go b/pkg/log/config.go index 27c7af4c1..b58f675c9 100644 --- a/pkg/log/config.go +++ b/pkg/log/config.go @@ -6,6 +6,7 @@ package log import ( "fmt" "io" + "log" "os" "github.com/kelseyhightower/envconfig" @@ -31,10 +32,10 @@ func (l *LogConfig) SetFormatter(v string) { case "json": l.Formatter = &logrus.JSONFormatter{ PrettyPrint: l.PrettyPrint, - //CallerPrettyfier: func(f *runtime.Frame) (string, string) { + // CallerPrettyfier: func(f *runtime.Frame) (string, string) { // _, filename := path.Split(f.File) // return f.Function, fmt.Sprintf("%s: %d", filename, f.Line) - //}, + // }, } case "text": @@ -65,7 +66,12 @@ func (l *LogConfig) SetWriter(v string) { logrus.Warn(fmt.Sprintf("Error while creating log io.Writer for file: %s, Using default: %s", v, "stdout")) l.Writer = os.Stdout } - defer f.Close() + defer func() { + if err := f.Close(); err != nil { + log.Printf("error during file closing: %s", err) + } + }() + l.Writer = f } } diff --git a/pkg/oidc/provider.go b/pkg/oidc/provider.go index f65bd1d1c..be7ec9825 100644 --- a/pkg/oidc/provider.go +++ b/pkg/oidc/provider.go @@ -10,7 +10,6 @@ import ( "encoding/base64" "fmt" "io" - "io/ioutil" "net/http" "regexp" "time" @@ -37,7 +36,7 @@ type Provider struct { func NewProvider(url string, enableLog bool) *Provider { l := logrus.New() if !enableLog { - l.SetOutput(ioutil.Discard) + l.SetOutput(io.Discard) } gin.DefaultWriter = l.Writer() oidcProvider := Provider{ @@ -55,6 +54,8 @@ func NewProvider(url string, enableLog bool) *Provider { func (p *Provider) Start() { p.ctx, p.cancel = context.WithCancel(context.Background()) + // nolint due to unset values for timeouts + //nolint:gosec p.server = &http.Server{Handler: p.router.Handler()} serverAddr := "'default'" @@ -74,6 +75,8 @@ func (p *Provider) Start() { } func (p *Provider) StartForeground() { + // nolint due to unset values for timeouts + //nolint:gosec p.server = &http.Server{Handler: p.router.Handler()} serverAddr := "'default'" diff --git a/pkg/util/filesystem.go b/pkg/util/filesystem.go index e63573985..325bad9d0 100644 --- a/pkg/util/filesystem.go +++ b/pkg/util/filesystem.go @@ -6,17 +6,24 @@ package util import ( "bufio" "fmt" + "log" "os" "path/filepath" "strings" ) func SetEnvVars(f string) error { + //nolint: gosec file, err := os.Open(f) if err != nil { return err } - defer file.Close() + defer func() { + if err := file.Close(); err != nil { + log.Printf("error during file closing: %s", err) + } + }() + // Create a map to store the environment variables envVars := make(map[string]string) // Read the file line by line @@ -42,7 +49,7 @@ func SetEnvVars(f string) error { } // Set the environment variables for key, value := range envVars { - os.Setenv(key, value) + _ = os.Setenv(key, value) } return err } @@ -51,7 +58,7 @@ func GetProjectRoot() (string, error) { // Get the current working directory cwd, err := os.Getwd() if err != nil { - return "", fmt.Errorf("Error:", err) + return "", fmt.Errorf("error: %w", err) } // Find the project root directory by traversing up the directory tree projectRoot := findProjectRoot(cwd) diff --git a/pkg/util/network.go b/pkg/util/network.go index 445c4babe..191712a80 100644 --- a/pkg/util/network.go +++ b/pkg/util/network.go @@ -14,12 +14,13 @@ func IsPortFree(port string) bool { if err != nil { return false } - ln.Close() + _ = ln.Close() return true } func GetRandomFreePort() string { + //nolint:gosec rndNumber := rand.Intn(9999) port := fmt.Sprintf("2%04d", rndNumber) if IsPortFree(port) { diff --git a/pkg/util/server.go b/pkg/util/server.go index efe924dc6..39bbceb65 100644 --- a/pkg/util/server.go +++ b/pkg/util/server.go @@ -11,7 +11,8 @@ import ( "github.com/sirupsen/logrus" ) -// FirstListenThenServe is a utility function that ensures that first a listener is spin up then the http server is setup for serving asynchronously +// FirstListenThenServe is a utility function that ensures that first a listener is spin up +// then the http server is setup for serving asynchronously // this is requried to ensure in tests that the server is spinned up before jumping to tests. func FirstListenThenServe(srv *http.Server, log *logrus.Logger) { var waitGroup sync.WaitGroup