diff --git a/.golangci.yml b/.golangci.yml index d17394b935542..edb8fedcfeda8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -80,7 +80,7 @@ linters-settings: wrapcheck: ignoreSigRegexps: - utils\.Should - - errox\.New.* + - errox\..+\.CausedBy(f)? - retry\.MakeRetryable - policy\.NewErr.* diff --git a/central/apitoken/service/service_impl.go b/central/apitoken/service/service_impl.go index d22bb4c2ff7d8..4bb52a52f8001 100644 --- a/central/apitoken/service/service_impl.go +++ b/central/apitoken/service/service_impl.go @@ -101,7 +101,7 @@ func (s *serviceImpl) GenerateToken(ctx context.Context, req *v1.GenerateTokenRe return nil, err } if err := verifyNoPrivilegeEscalation(id.Roles(), roles); err != nil { - return nil, errox.NewErrNotAuthorized(err.Error()) + return nil, errox.NotAuthorized.CausedBy(err.Error()) } token, metadata, err := s.backend.IssueRoleToken(ctx, req.GetName(), utils.RoleNames(roles)) diff --git a/central/authprovider/service/service_impl.go b/central/authprovider/service/service_impl.go index 85c0bf9c6cd24..a4f82e47ba5c0 100644 --- a/central/authprovider/service/service_impl.go +++ b/central/authprovider/service/service_impl.go @@ -70,7 +70,7 @@ func (s *serviceImpl) AuthFuncOverride(ctx context.Context, fullMethodName strin // GetAuthProvider retrieves the authProvider based on the id passed func (s *serviceImpl) GetAuthProvider(_ context.Context, request *v1.GetAuthProviderRequest) (*storage.AuthProvider, error) { if request.GetId() == "" { - return nil, errox.NewErrInvalidArgs("auth provider id is required") + return nil, errox.InvalidArgs.CausedBy("auth provider id is empty") } authProvider := s.registry.GetProvider(request.GetId()) if authProvider == nil { @@ -158,37 +158,37 @@ func (s *serviceImpl) GetAuthProviders(_ context.Context, request *v1.GetAuthPro func (s *serviceImpl) PostAuthProvider(ctx context.Context, request *v1.PostAuthProviderRequest) (*storage.AuthProvider, error) { providerReq := request.GetProvider() if providerReq.GetName() == "" { - return nil, errox.NewErrInvalidArgs("no auth provider name specified") + return nil, errox.InvalidArgs.CausedBy("no auth provider name specified") } if providerReq.GetId() != "" { - return nil, errox.NewErrInvalidArgs("auth provider id must be empty") + return nil, errox.InvalidArgs.CausedBy("auth provider id is not empty") } if providerReq.GetLoginUrl() != "" { - return nil, errox.NewErrInvalidArgs("auth provider loginUrl field must be empty") + return nil, errox.InvalidArgs.CausedBy("auth provider loginUrl field is not empty") } provider, err := s.registry.CreateProvider(ctx, authproviders.WithStorageView(providerReq), authproviders.WithValidateCallback(datastore.Singleton())) if err != nil { - return nil, errors.Wrap(errox.NewErrInvalidArgs(err.Error()), "creating auth provider instance") + return nil, errors.Wrap(errox.InvalidArgs.CausedBy(err.Error()), "creating auth provider instance") } return provider.StorageView(), nil } func (s *serviceImpl) PutAuthProvider(ctx context.Context, request *storage.AuthProvider) (*storage.AuthProvider, error) { if request.GetId() == "" { - return nil, errox.NewErrInvalidArgs("auth provider id must not be empty") + return nil, errox.InvalidArgs.CausedBy("auth provider id is empty") } provider := s.registry.GetProvider(request.GetId()) if provider == nil { - return nil, errox.NewErrInvalidArgs(fmt.Sprintf("auth provider with id %q does not exist", request.GetId())) + return nil, errox.InvalidArgs.CausedBy(fmt.Sprintf("auth provider with id %q does not exist", request.GetId())) } // Attempt to merge configs. request.Config = provider.MergeConfigInto(request.GetConfig()) if err := s.registry.ValidateProvider(ctx, authproviders.WithStorageView(request)); err != nil { - return nil, errox.NewErrInvalidArgs(fmt.Sprintf("auth provider validation check failed: %v", err)) + return nil, errox.InvalidArgs.CausedBy(fmt.Sprintf("auth provider validation check failed: %v", err)) } // This will not log anyone out as the provider was not validated and thus no one has ever logged into it @@ -198,14 +198,14 @@ func (s *serviceImpl) PutAuthProvider(ctx context.Context, request *storage.Auth provider, err := s.registry.CreateProvider(ctx, authproviders.WithStorageView(request), authproviders.WithValidateCallback(datastore.Singleton())) if err != nil { - return nil, errors.Wrap(errox.NewErrInvalidArgs(err.Error()), "creating auth provider instance") + return nil, errors.Wrap(errox.InvalidArgs.CausedBy(err.Error()), "creating auth provider instance") } return provider.StorageView(), nil } func (s *serviceImpl) UpdateAuthProvider(ctx context.Context, request *v1.UpdateAuthProviderRequest) (*storage.AuthProvider, error) { if request.GetId() == "" { - return nil, errox.NewErrInvalidArgs("auth provider id must not be empty") + return nil, errox.InvalidArgs.CausedBy("auth provider id is empty") } var options []authproviders.ProviderOption @@ -217,7 +217,7 @@ func (s *serviceImpl) UpdateAuthProvider(ctx context.Context, request *v1.Update } provider, err := s.registry.UpdateProvider(ctx, request.GetId(), options...) if err != nil { - return nil, errors.Wrap(errox.NewErrInvalidArgs(err.Error()), "updating auth provider") + return nil, errors.Wrap(errox.InvalidArgs.CausedBy(err.Error()), "updating auth provider") } return provider.StorageView(), nil } @@ -225,7 +225,7 @@ func (s *serviceImpl) UpdateAuthProvider(ctx context.Context, request *v1.Update // DeleteAuthProvider deletes an auth provider from the system func (s *serviceImpl) DeleteAuthProvider(ctx context.Context, request *v1.ResourceByID) (*v1.Empty, error) { if request.GetId() == "" { - return nil, errox.NewErrInvalidArgs("auth provider id is required") + return nil, errox.InvalidArgs.CausedBy("auth provider id is empty") } // Get auth provider. diff --git a/central/cluster/datastore/datastore_impl.go b/central/cluster/datastore/datastore_impl.go index 1811e5e1f88b7..edb91fa19b2f8 100644 --- a/central/cluster/datastore/datastore_impl.go +++ b/central/cluster/datastore/datastore_impl.go @@ -929,7 +929,7 @@ func (ds *datastoreImpl) LookupOrCreateClusterFromConfig(ctx context.Context, cl func normalizeCluster(cluster *storage.Cluster) error { if cluster == nil { - return errox.NewErrInvariantViolation("cannot normalize nil cluster object") + return errox.InvariantViolation.CausedBy("cannot normalize nil cluster object") } cluster.CentralApiEndpoint = strings.TrimPrefix(cluster.GetCentralApiEndpoint(), "https://") @@ -947,7 +947,7 @@ func validateInput(cluster *storage.Cluster) error { // `cluster.* bool` flags remain untouched. func addDefaults(cluster *storage.Cluster) error { if cluster == nil { - return errox.NewErrInvariantViolation("cannot enrich nil cluster object") + return errox.InvariantViolation.CausedBy("cannot enrich nil cluster object") } // For backwards compatibility reasons, if Collection Method is not set then honor defaults for runtime support if cluster.GetCollectionMethod() == storage.CollectionMethod_UNSET_COLLECTION { diff --git a/central/compliance/standards/utils.go b/central/compliance/standards/utils.go index 00276b561ba31..9f5382acfb22c 100644 --- a/central/compliance/standards/utils.go +++ b/central/compliance/standards/utils.go @@ -34,5 +34,5 @@ func IsSupported(standardID string) bool { // UnSupportedStandardsErr builds error message for unsupported compliance standards and returns the error func UnSupportedStandardsErr(unsupported ...string) error { - return errox.NewErrInvalidArgs(fmt.Sprintf("unsupported standard(s): %+v. Supported standards are %+v", unsupported, GetSupportedStandards())) + return errox.InvalidArgs.CausedBy(fmt.Sprintf("unsupported standard(s): %+v. Supported standards are %+v", unsupported, GetSupportedStandards())) } diff --git a/central/detection/service/service_impl.go b/central/detection/service/service_impl.go index b1ceb943cfa2b..80a84b606f619 100644 --- a/central/detection/service/service_impl.go +++ b/central/detection/service/service_impl.go @@ -126,7 +126,7 @@ func (s *serviceImpl) DetectBuildTime(ctx context.Context, req *apiV1.BuildDetec } } if image.GetName() == nil { - return nil, errox.NewErrInvalidArgs("image or image_name must be specified") + return nil, errox.InvalidArgs.CausedBy("image or image_name must be specified") } // This is a workaround for those who post the full image, but don't fill in fullname if name := image.GetName(); name != nil && name.GetFullName() == "" { @@ -288,7 +288,7 @@ func getObjectsFromList(list *coreV1.List) ([]k8sRuntime.Object, []string, error // DetectDeployTimeFromYAML runs detection on a deployment. func (s *serviceImpl) DetectDeployTimeFromYAML(ctx context.Context, req *apiV1.DeployYAMLDetectionRequest) (*apiV1.DeployDetectionResponse, error) { if req.GetYaml() == "" { - return nil, errox.NewErrInvalidArgs("yaml field must be specified in detection request") + return nil, errox.InvalidArgs.CausedBy("yaml field must be specified in detection request") } resources, ignoredObjectRefs, err := getObjectsFromYAML(req.GetYaml()) @@ -347,7 +347,7 @@ func (s *serviceImpl) populateDeploymentWithClusterInfo(ctx context.Context, clu // DetectDeployTime runs detection on a deployment. func (s *serviceImpl) DetectDeployTime(ctx context.Context, req *apiV1.DeployDetectionRequest) (*apiV1.DeployDetectionResponse, error) { if req.GetDeployment() == nil { - return nil, errox.NewErrInvalidArgs("deployment must be passed to deploy time detection") + return nil, errox.InvalidArgs.CausedBy("deployment must be passed to deploy time detection") } if err := s.populateDeploymentWithClusterInfo(ctx, req.GetClusterId(), req.GetDeployment()); err != nil { return nil, err diff --git a/central/networkpolicies/service/service_impl.go b/central/networkpolicies/service/service_impl.go index bd9043e186dd9..9b4c39402b33e 100644 --- a/central/networkpolicies/service/service_impl.go +++ b/central/networkpolicies/service/service_impl.go @@ -1075,7 +1075,7 @@ func compileValidateYaml(simulationYaml string) ([]*storage.NetworkPolicy, error // Check that all resulting policies have namespaces. for _, policy := range policies { if policy.GetNamespace() == "" { - return nil, errox.NewErrInvalidArgs("yamls tested against must apply to a namespace") + return nil, errox.InvalidArgs.CausedBy("yamls tested against must apply to a namespace") } } diff --git a/central/policy/service/service_impl.go b/central/policy/service/service_impl.go index 1708bc3619845..867db58a71d9f 100644 --- a/central/policy/service/service_impl.go +++ b/central/policy/service/service_impl.go @@ -853,7 +853,7 @@ func (s *serviceImpl) PolicyFromSearch(ctx context.Context, request *v1.PolicyFr func (s *serviceImpl) parsePolicy(ctx context.Context, searchString string) (*storage.Policy, []search.FieldLabel, bool, error) { // Handle empty input query case. if len(searchString) == 0 { - return nil, nil, false, errox.NewErrInvalidArgs("can not generate a policy from an empty query") + return nil, nil, false, errox.InvalidArgs.CausedBy("can not generate a policy from an empty query") } // Have a filled query, parse it. fieldMap, err := getFieldMapFromQueryString(searchString) diff --git a/central/role/service/service_impl.go b/central/role/service/service_impl.go index 51e5804d0d124..6826ae8a69adc 100644 --- a/central/role/service/service_impl.go +++ b/central/role/service/service_impl.go @@ -113,7 +113,7 @@ func (s *serviceImpl) CreateRole(ctx context.Context, roleRequest *v1.CreateRole // Check role request correctness. if role.GetName() != "" && role.GetName() != roleRequest.GetName() { - return nil, errox.NewErrInvalidArgs("different role names in path and body") + return nil, errox.InvalidArgs.CausedBy("different role names in path and body") } role.Name = roleRequest.GetName() @@ -208,7 +208,7 @@ func (s *serviceImpl) ListPermissionSets(ctx context.Context, _ *v1.Empty) (*v1. func (s *serviceImpl) PostPermissionSet(ctx context.Context, permissionSet *storage.PermissionSet) (*storage.PermissionSet, error) { if permissionSet.GetId() != "" { - return nil, errox.NewErrInvalidArgs("setting id field is not allowed") + return nil, errox.InvalidArgs.CausedBy("setting id field is not allowed") } permissionSet.Id = rolePkg.GeneratePermissionSetID() @@ -274,7 +274,7 @@ func (s *serviceImpl) ListSimpleAccessScopes(ctx context.Context, _ *v1.Empty) ( func (s *serviceImpl) PostSimpleAccessScope(ctx context.Context, scope *storage.SimpleAccessScope) (*storage.SimpleAccessScope, error) { if scope.GetId() != "" { - return nil, errox.NewErrInvalidArgs("setting id field is not allowed") + return nil, errox.InvalidArgs.CausedBy("setting id field is not allowed") } scope.Id = rolePkg.GenerateAccessScopeID() diff --git a/central/sensor/service/service_impl.go b/central/sensor/service/service_impl.go index 4d30a4d036499..93dd218232c15 100644 --- a/central/sensor/service/service_impl.go +++ b/central/sensor/service/service_impl.go @@ -70,7 +70,7 @@ func (s *serviceImpl) Communicate(server central.SensorService_CommunicateServer svc := identity.Service() if svc == nil || svc.GetType() != storage.ServiceType_SENSOR_SERVICE { - return errox.NewErrNotAuthorized("only sensor may access this API") + return errox.NotAuthorized.CausedBy("only sensor may access this API") } sensorHello, sensorSupportsHello, err := receiveSensorHello(server) diff --git a/central/sensorupgrade/controlservice/service_impl.go b/central/sensorupgrade/controlservice/service_impl.go index 86c7409efce40..f02cede504ec2 100644 --- a/central/sensorupgrade/controlservice/service_impl.go +++ b/central/sensorupgrade/controlservice/service_impl.go @@ -36,12 +36,12 @@ func clusterIDFromCtx(ctx context.Context) (string, error) { svc := id.Service() if svc == nil || svc.GetType() != storage.ServiceType_SENSOR_SERVICE { - return "", errox.NewErrNotAuthorized("only sensor/upgrader may access this API") + return "", errox.NotAuthorized.CausedBy("only sensor/upgrader may access this API") } clusterID := svc.GetId() if clusterID == "" { - return "", errox.NewErrNotAuthorized("only sensors with a valid cluster ID may access this API") + return "", errox.NotAuthorized.CausedBy("only sensors with a valid cluster ID may access this API") } return clusterID, nil } diff --git a/central/signatureintegration/datastore/datastore_impl.go b/central/signatureintegration/datastore/datastore_impl.go index dc565d94c0e48..5fe94758d9b8c 100644 --- a/central/signatureintegration/datastore/datastore_impl.go +++ b/central/signatureintegration/datastore/datastore_impl.go @@ -67,7 +67,7 @@ func (d *datastoreImpl) AddSignatureIntegration(ctx context.Context, integration } integration.Id = GenerateSignatureIntegrationID() if err := ValidateSignatureIntegration(integration); err != nil { - return nil, errox.NewErrInvalidArgs(err.Error()) + return nil, errox.InvalidArgs.CausedBy(err.Error()) } // Protect against TOCTOU race condition. @@ -93,7 +93,7 @@ func (d *datastoreImpl) UpdateSignatureIntegration(ctx context.Context, integrat return false, err } if err := ValidateSignatureIntegration(integration); err != nil { - return false, errox.NewErrInvalidArgs(err.Error()) + return false, errox.InvalidArgs.CausedBy(err.Error()) } // Protect against TOCTOU race condition. diff --git a/pkg/auth/authproviders/provider_impl.go b/pkg/auth/authproviders/provider_impl.go index 922f691b84c38..169a7dcafe163 100644 --- a/pkg/auth/authproviders/provider_impl.go +++ b/pkg/auth/authproviders/provider_impl.go @@ -117,7 +117,7 @@ func (p *providerImpl) GetOrCreateBackend(ctx context.Context) (Backend, error) // Backend factories are not guaranteed to survive product upgrades or restarts. if p.backendFactory == nil { - return nil, errox.NewErrInvariantViolation( + return nil, errox.InvariantViolation.CausedBy( "the backend for this authentication provider cannot be instantiated;" + " this is probably because of a recent upgrade or a configuration change") } diff --git a/pkg/auth/authproviders/registry_httphandler.go b/pkg/auth/authproviders/registry_httphandler.go index 15c64ab996660..3f6eb48e4fcce 100644 --- a/pkg/auth/authproviders/registry_httphandler.go +++ b/pkg/auth/authproviders/registry_httphandler.go @@ -275,7 +275,7 @@ func (r *registryImpl) providersHTTPHandler(w http.ResponseWriter, req *http.Req userInfo := user.GetUserInfo() if userInfo == nil { - err := errox.NewErrNotAuthorized("failed to get user info") + err := errox.NotAuthorized.CausedBy("failed to get user info") r.error(w, err, typ, clientState, testMode) return } diff --git a/pkg/errox/errors.go b/pkg/errox/errors.go index 490786e0ffb3a..6270aa3c58aa4 100644 --- a/pkg/errox/errors.go +++ b/pkg/errox/errors.go @@ -52,23 +52,3 @@ func GenericNoValidRole() error { return NoValidRole.New("access for this user is not authorized: no valid role," + " please contact your system administrator") } - -// NewErrNotAuthorized wraps NotAuthorized into an explanation. -func NewErrNotAuthorized(explanation string) error { - return NotAuthorized.CausedBy(explanation) -} - -// NewErrNoCredentials wraps NoCredentials into an explanation. -func NewErrNoCredentials(explanation string) error { - return NoCredentials.CausedBy(explanation) -} - -// NewErrInvariantViolation wraps InvariantViolation into an explanation. -func NewErrInvariantViolation(explanation string) error { - return InvariantViolation.CausedBy(explanation) -} - -// NewErrInvalidArgs wraps InvalidArgs into an explanation. -func NewErrInvalidArgs(explanation string) error { - return InvalidArgs.CausedBy(explanation) -} diff --git a/pkg/gjson/row.go b/pkg/gjson/row.go index cceb1d7b4ea9a..3bda46fdac392 100644 --- a/pkg/gjson/row.go +++ b/pkg/gjson/row.go @@ -22,7 +22,7 @@ type RowMapper struct { func NewRowMapper(jsonObj interface{}, multiPathExpression string) (*RowMapper, error) { bytes, err := json.Marshal(jsonObj) if err != nil { - return nil, errox.NewErrInvariantViolation(err.Error()) + return nil, errox.InvariantViolation.CausedBy(err.Error()) } result, err := getResultFromBytes(bytes, multiPathExpression) @@ -85,7 +85,7 @@ func isJaggedArray(array [][]string) error { func getResultFromBytes(bytes []byte, jsonPathExpression string) (gjson.Result, error) { results := gjson.GetManyBytes(bytes, jsonPathExpression) if len(results) != 1 { - return gjson.Result{}, errox.NewErrInvariantViolation("expected gjson " + + return gjson.Result{}, errox.InvariantViolation.CausedBy("expected gjson " + "results to be exactly 1") } @@ -112,7 +112,7 @@ func getRowsFromColumns(columns [][]string) [][]string { // jaggedArrayError helper to create an errox.InvariantViolation with an explanation about a jagged array being found func jaggedArrayError(maxAmount, violatedAmount, arrayIndex int) error { - return errox.NewErrInvariantViolation(fmt.Sprintf("jagged array found: yielded values within "+ + return errox.InvariantViolation.CausedBy(fmt.Sprintf("jagged array found: yielded values within "+ "each array are not matching; expected each array to hold %d elements but found an array with %d elements "+ "at array index %d", maxAmount, violatedAmount, arrayIndex+1)) } diff --git a/pkg/grpc/authn/basic/manager.go b/pkg/grpc/authn/basic/manager.go index 7a8fe54e1180f..d3c9b04eee358 100644 --- a/pkg/grpc/authn/basic/manager.go +++ b/pkg/grpc/authn/basic/manager.go @@ -30,7 +30,7 @@ func (m *Manager) SetHashFile(hashFile *htpasswd.HashFile) { // IdentityForCreds returns an identity for the given credentials. func (m *Manager) IdentityForCreds(ctx context.Context, username, password string, authProvider authproviders.Provider) (Identity, error) { if !m.hashFile().Check(username, password) { - return nil, errox.NewErrNotAuthorized("invalid username and/or password") + return nil, errox.NotAuthorized.CausedBy("invalid username and/or password") } resolvedRoles, err := m.mapper.FromUserDescriptor(ctx, &permissions.UserDescriptor{ diff --git a/pkg/grpc/authn/interceptor.go b/pkg/grpc/authn/interceptor.go index 0a613558954da..b17eb7629d402 100644 --- a/pkg/grpc/authn/interceptor.go +++ b/pkg/grpc/authn/interceptor.go @@ -28,7 +28,7 @@ func (u contextUpdater) updateContext(ctx context.Context) (context.Context, err log.Warnf("Cannot extract identity: %v", err) } // Ignore id value if error is not nil. - return context.WithValue(ctx, identityErrorContextKey{}, errox.NewErrNoCredentials(err.Error())), nil + return context.WithValue(ctx, identityErrorContextKey{}, errox.NoCredentials.CausedBy(err.Error())), nil } if id != nil { // Only service identities can have no roles assigned. diff --git a/pkg/grpc/authz/and/and.go b/pkg/grpc/authz/and/and.go index 371deea682949..247b9e45e43c9 100644 --- a/pkg/grpc/authz/and/and.go +++ b/pkg/grpc/authz/and/and.go @@ -20,7 +20,7 @@ func (a *and) Authorized(ctx context.Context, fullMethodName string) error { } } if len(errors) != 0 { - return errox.NewErrNotAuthorized(errorhelpers.NewErrorListWithErrors("some authorizer could not authorize this request:", errors).String()) + return errox.NotAuthorized.CausedBy(errorhelpers.NewErrorListWithErrors("some authorizer could not authorize this request:", errors).String()) } return nil } diff --git a/pkg/grpc/authz/idcheck/service_type.go b/pkg/grpc/authz/idcheck/service_type.go index 96987c4585efa..4fa36091e0bdf 100644 --- a/pkg/grpc/authz/idcheck/service_type.go +++ b/pkg/grpc/authz/idcheck/service_type.go @@ -16,7 +16,7 @@ func (s serviceType) AuthorizeByIdentity(id authn.Identity) error { return errox.NoCredentials } if svc.GetType() != storage.ServiceType(s) { - return errox.NewErrNotAuthorized("service source type not allowed") + return errox.NotAuthorized.CausedBy("service source type not allowed") } return nil } diff --git a/pkg/grpc/authz/or/or.go b/pkg/grpc/authz/or/or.go index f418e5f7d7339..234a5d7f70d4f 100644 --- a/pkg/grpc/authz/or/or.go +++ b/pkg/grpc/authz/or/or.go @@ -22,7 +22,7 @@ func (o *or) Authorized(ctx context.Context, fullMethodName string) error { } errors = append(errors, err) } - return errox.NewErrNotAuthorized(errorhelpers.NewErrorListWithErrors("no authorizer could authorize this request:", errors).String()) + return errox.NotAuthorized.CausedBy(errorhelpers.NewErrorListWithErrors("no authorizer could authorize this request:", errors).String()) } // Or creates an Authorizer that succeeds if any of the provided Authorizers succeed. diff --git a/pkg/grpc/authz/user/role.go b/pkg/grpc/authz/user/role.go index e07b591768c26..ddca033e78173 100644 --- a/pkg/grpc/authz/user/role.go +++ b/pkg/grpc/authz/user/role.go @@ -39,5 +39,5 @@ func (p *roleChecker) checkRole(roleNames []string) error { } } - return errox.NewErrNotAuthorized(fmt.Sprintf("role %q is required", p.roleName)) + return errox.NotAuthorized.CausedBy(fmt.Sprintf("role %q is required", p.roleName)) } diff --git a/pkg/grpc/authz/user/user.go b/pkg/grpc/authz/user/user.go index e0fdfae214188..cc557fef4a507 100644 --- a/pkg/grpc/authz/user/user.go +++ b/pkg/grpc/authz/user/user.go @@ -70,7 +70,7 @@ func (p *permissionChecker) checkGlobalSACPermissions(ctx context.Context, rootS return err } if !allowed { - return errox.NewErrNotAuthorized("scoped access") + return errox.NotAuthorized.CausedBy("scoped access") } return nil } @@ -81,7 +81,7 @@ func (p *permissionChecker) checkPermissions(rolePerms map[string]storage.Access } for _, requiredPerm := range p.requiredPermissions { if !evaluateAgainstPermissions(rolePerms, requiredPerm) { - return errox.NewErrNotAuthorized(fmt.Sprintf("%q for %q", requiredPerm.Access, requiredPerm.Resource)) + return errox.NotAuthorized.CausedBy(fmt.Sprintf("%q for %q", requiredPerm.Access, requiredPerm.Resource)) } } return nil diff --git a/pkg/grpc/errors/interceptor_test.go b/pkg/grpc/errors/interceptor_test.go index ec811a5ccd3e7..8b51317b81444 100644 --- a/pkg/grpc/errors/interceptor_test.go +++ b/pkg/grpc/errors/interceptor_test.go @@ -221,7 +221,7 @@ func TestPanicOnInvariantViolationStreamInterceptor(t *testing.T) { }, "Error is ErrInvariantViolation -> panic": { handler: func(srv interface{}, stream grpc.ServerStream) error { - return errox.NewErrInvariantViolation("some explanation") + return errox.InvariantViolation.CausedBy("some explanation") }, err: nil, panics: true, diff --git a/pkg/printers/junit.go b/pkg/printers/junit.go index b3276df4085b7..cccecd0e1b3d9 100644 --- a/pkg/printers/junit.go +++ b/pkg/printers/junit.go @@ -143,12 +143,12 @@ func validateJUnitSuiteData(testCaseNames, failedTestCaseNames, failedTestCaseEr amountSkippedTestCases := len(skippedTestCaseNames) if amountTestCases < amountFailedTestCases+amountSkippedTestCases { - return errox.NewErrInvariantViolation(fmt.Sprintf("%d failed test cases are greater "+ + return errox.InvariantViolation.CausedBy(fmt.Sprintf("%d failed test cases are greater "+ "than %d overall test cases", amountTestCases, amountFailedTestCases)) } if len(failedTestCaseNames) != len(failedTestCaseErrorMessages) { - return errox.NewErrInvariantViolation(fmt.Sprintf("%d failed test cases and %d error "+ + return errox.InvariantViolation.CausedBy(fmt.Sprintf("%d failed test cases and %d error "+ "messages are not matching", amountFailedTestCases, amountFailedTestCaseErrorMessages)) } return nil @@ -191,7 +191,7 @@ func createFailedTestCaseMap(failedTestCases []string, failedTestCaseErrorMessag failedTestCaseMap := make(map[string]string, len(failedTestCases)) for i, name := range failedTestCases { if _, exists := failedTestCaseMap[name]; exists { - return nil, errox.NewErrInvariantViolation(fmt.Sprintf("duplicate failed test "+ + return nil, errox.InvariantViolation.CausedBy(fmt.Sprintf("duplicate failed test "+ "case %q found", name)) } failedTestCaseMap[name] = failedTestCaseErrorMessages[i] diff --git a/pkg/registries/ecr/ecr.go b/pkg/registries/ecr/ecr.go index 0079da7f772f7..48ee593278fe4 100644 --- a/pkg/registries/ecr/ecr.go +++ b/pkg/registries/ecr/ecr.go @@ -234,10 +234,10 @@ func createECRClient(conf *storage.ECRConfig) (*awsECR.ECR, error) { if conf.GetUseAssumeRole() { if endpoint != "" { - return nil, errox.NewErrInvalidArgs("AssumeRole and Endpoint cannot both be enabled") + return nil, errox.InvalidArgs.CausedBy("AssumeRole and Endpoint cannot both be enabled") } if conf.GetAssumeRoleId() == "" { - return nil, errox.NewErrInvalidArgs("AssumeRole ID is required to use AssumeRole") + return nil, errox.InvalidArgs.CausedBy("AssumeRole ID is required to use AssumeRole") } roleToAssumeArn := fmt.Sprintf("arn:aws:iam::%s:role/%s", conf.RegistryId, conf.AssumeRoleId) diff --git a/pkg/search/general_query_parser.go b/pkg/search/general_query_parser.go index b61c86160b12d..293272fc8709f 100644 --- a/pkg/search/general_query_parser.go +++ b/pkg/search/general_query_parser.go @@ -56,7 +56,7 @@ func getFieldMap(query string) map[FieldLabel][]string { func ParseFieldMap(query string) (map[FieldLabel][]string, error) { fieldMap := getFieldMap(query) if len(fieldMap) == 0 { - return nil, errox.NewErrInvalidArgs("after parsing, query is empty") + return nil, errox.InvalidArgs.CausedBy("after parsing, query is empty") } return fieldMap, nil } diff --git a/roxctl/common/flags/opt_bool.go b/roxctl/common/flags/opt_bool.go index 5df2e4f75ec5a..f4fbb247131b2 100644 --- a/roxctl/common/flags/opt_bool.go +++ b/roxctl/common/flags/opt_bool.go @@ -27,7 +27,7 @@ func (v optBool) Set(strVal string) error { } b, err := strconv.ParseBool(strVal) if err != nil { - return errox.NewErrInvalidArgs(err.Error()) + return errox.InvalidArgs.CausedBy(err.Error()) } *v.boolp = &b return nil diff --git a/roxctl/common/printer/junitprinter_factory.go b/roxctl/common/printer/junitprinter_factory.go index 2595207fd4b2c..7e507712fb596 100644 --- a/roxctl/common/printer/junitprinter_factory.go +++ b/roxctl/common/printer/junitprinter_factory.go @@ -114,7 +114,7 @@ func (j *JUnitPrinterFactory) CreatePrinter(format string) (ObjectPrinter, error func (j *JUnitPrinterFactory) validate() error { // ensure that the suite name is not empty if j.suiteName == "" { - return errox.NewErrInvalidArgs("empty JUnit test suite name given, " + + return errox.InvalidArgs.CausedBy("empty JUnit test suite name given, " + "please provide a meaningful name") } diff --git a/roxctl/common/printer/tabularprinter_factory.go b/roxctl/common/printer/tabularprinter_factory.go index 79c78c024f958..e57d2f8cf1afc 100644 --- a/roxctl/common/printer/tabularprinter_factory.go +++ b/roxctl/common/printer/tabularprinter_factory.go @@ -126,7 +126,7 @@ func (t *TabularPrinterFactory) CreatePrinter(format string) (ObjectPrinter, err // if it is not possible func (t *TabularPrinterFactory) validate() error { if t.NoHeader && t.HeaderAsComment { - return errox.NewErrInvalidArgs("cannot specify both --no-header as well as " + + return errox.InvalidArgs.CausedBy("cannot specify both --no-header as well as " + "--headers-as-comment flags. Choose only one of them") } headers := set.NewStringSet(t.Headers...) diff --git a/roxctl/completion/completion.go b/roxctl/completion/completion.go index 92336a6475361..46868355bda6a 100644 --- a/roxctl/completion/completion.go +++ b/roxctl/completion/completion.go @@ -10,7 +10,7 @@ import ( ) var ( - errInvalidArgs = errox.NewErrInvalidArgs("use one of the following: [bash|zsh|fish|powershell]") + errInvalidArgs = errox.InvalidArgs.CausedBy("use one of the following: [bash|zsh|fish|powershell]") ) const ( diff --git a/roxctl/deployment/check/check.go b/roxctl/deployment/check/check.go index bb562f7a32f7c..1c155ffc90d77 100644 --- a/roxctl/deployment/check/check.go +++ b/roxctl/deployment/check/check.go @@ -129,7 +129,7 @@ func (d *deploymentCheckCommand) Construct(args []string, cmd *cobra.Command, f func (d *deploymentCheckCommand) Validate() error { if _, err := os.Open(d.file); err != nil { - return errors.Wrap(errox.NewErrInvalidArgs(err.Error()), "validating command") + return errors.Wrap(errox.InvalidArgs.CausedBy(err.Error()), "validating command") } return nil diff --git a/roxctl/helm/derivelocalvalues/command.go b/roxctl/helm/derivelocalvalues/command.go index f1299a9634819..a289cb9ee3532 100644 --- a/roxctl/helm/derivelocalvalues/command.go +++ b/roxctl/helm/derivelocalvalues/command.go @@ -65,11 +65,11 @@ func (cfg *helmDeriveLocalValuesCommand) Construct(chartName string) { // provided values func (cfg *helmDeriveLocalValuesCommand) Validate() error { if cfg.output == "" && cfg.outputDir == "" { - return errox.NewErrInvalidArgs(noOutputFileExplanation) + return errox.InvalidArgs.CausedBy(noOutputFileExplanation) } if cfg.output != "" && cfg.outputDir != "" { - return errox.NewErrInvalidArgs(`specify either "--output" or "--output-dir" but not both`) + return errox.InvalidArgs.CausedBy(`specify either "--output" or "--output-dir" but not both`) } if cfg.output == "-" { diff --git a/roxctl/image/scan/scan.go b/roxctl/image/scan/scan.go index 152a77f694883..a81a60c17bf03 100644 --- a/roxctl/image/scan/scan.go +++ b/roxctl/image/scan/scan.go @@ -113,7 +113,7 @@ func (i *imageScanCommand) Construct(args []string, cmd *cobra.Command, f *print i.timeout = flags.Timeout(cmd) if err := imageUtils.IsValidImageString(i.image); err != nil { - return errox.NewErrInvalidArgs(err.Error()) + return errox.InvalidArgs.CausedBy(err.Error()) } // There is a case where cobra is not printing the deprecation warning to stderr, when a deprecated flag is not @@ -141,7 +141,7 @@ func (i *imageScanCommand) Construct(args []string, cmd *cobra.Command, f *print // provided values func (i *imageScanCommand) Validate() error { if i.image == "" { - return errox.NewErrInvalidArgs("no image name specified via the -i or --image flag") + return errox.InvalidArgs.CausedBy("no image name specified via the -i or --image flag") } // Only verify the legacy output format if no printer is constructed, thus the new output format is not used diff --git a/roxctl/pflag/autobool/autobool.go b/roxctl/pflag/autobool/autobool.go index 33847522e47dd..b1bd8ff5eb796 100644 --- a/roxctl/pflag/autobool/autobool.go +++ b/roxctl/pflag/autobool/autobool.go @@ -36,7 +36,7 @@ func (v Value) Set(s string) error { // Then check for booleans. b, err := strconv.ParseBool(s) if err != nil { - return errox.NewErrInvalidArgs(err.Error()) + return errox.InvalidArgs.CausedBy(err.Error()) } *v.bp = &b diff --git a/roxctl/scanner/generate/generate.go b/roxctl/scanner/generate/generate.go index 2a80ec695c6df..755f92d1efde8 100644 --- a/roxctl/scanner/generate/generate.go +++ b/roxctl/scanner/generate/generate.go @@ -48,7 +48,7 @@ func (cmd *scannerGenerateCommand) validate() error { } } - return errox.NewErrInvalidArgs(fmt.Sprintf( + return errox.InvalidArgs.CausedBy(fmt.Sprintf( "unsupported Istio version %q used for argument %q. Use one of the following: [%s]", cmd.apiParams.IstioVersion, "--"+istioSupportArg, strings.Join(istioutils.ListKnownIstioVersions(), "|"), ))