diff --git a/central/alert/service/service_impl.go b/central/alert/service/service_impl.go index 07f97a2fd5e93..ad2d0dd99c3bc 100644 --- a/central/alert/service/service_impl.go +++ b/central/alert/service/service_impl.go @@ -20,6 +20,7 @@ import ( "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/batcher" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -103,7 +104,7 @@ func (s *serviceImpl) GetAlert(ctx context.Context, request *v1.ResourceByID) (* return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "alert with id '%s' does not exist", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "alert with id '%s' does not exist", request.GetId()) } return alert, nil @@ -128,7 +129,7 @@ func (s *serviceImpl) CountAlerts(ctx context.Context, request *v1.RawQuery) (*v // Fill in Query. parsedQuery, err := search.ParseQuery(request.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } count, err := s.dataStore.Count(ctx, parsedQuery) @@ -179,7 +180,7 @@ func (s *serviceImpl) GetAlertsCounts(ctx context.Context, request *v1.GetAlerts return response, nil } - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "unknown group by: %v", request.GetGroupBy()) + return nil, errors.Wrapf(errox.InvalidArgs, "unknown group by: %v", request.GetGroupBy()) } // GetAlertTimeseries returns the timeseries format of the events based on the request parameters @@ -202,7 +203,7 @@ func (s *serviceImpl) ResolveAlert(ctx context.Context, req *v1.ResolveAlertRequ return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "alert with id '%s' does not exist", req.GetId()) + return nil, errors.Wrapf(errox.NotFound, "alert with id '%s' does not exist", req.GetId()) } if req.GetWhitelist() || req.GetAddToBaseline() { @@ -254,7 +255,7 @@ func (s *serviceImpl) ResolveAlerts(ctx context.Context, req *v1.ResolveAlertsRe query, err := search.ParseQuery(req.GetQuery()) if err != nil { log.Error(err) - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } runtimeQuery := search.NewQueryBuilder().AddStrings(search.LifecycleStage, storage.LifecycleStage_RUNTIME.String()).ProtoQuery() cq := search.ConjunctionQuery(query, runtimeQuery) @@ -337,10 +338,10 @@ func (s *serviceImpl) changeAlertState(ctx context.Context, alert *storage.Alert func (s *serviceImpl) SnoozeAlert(ctx context.Context, req *v1.SnoozeAlertRequest) (*v1.Empty, error) { if req.GetSnoozeTill() == nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "'snooze_till' cannot be nil") + return nil, errors.Wrap(errox.InvalidArgs, "'snooze_till' cannot be nil") } if protoconv.ConvertTimestampToTimeOrNow(req.GetSnoozeTill()).Before(time.Now()) { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, badSnoozeErrorMsg) + return nil, errors.Wrap(errox.InvalidArgs, badSnoozeErrorMsg) } alert, exists, err := s.dataStore.GetAlert(ctx, req.GetId()) if err != nil { @@ -348,7 +349,7 @@ func (s *serviceImpl) SnoozeAlert(ctx context.Context, req *v1.SnoozeAlertReques return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "alert with id '%s' does not exist", req.GetId()) + return nil, errors.Wrapf(errox.NotFound, "alert with id '%s' does not exist", req.GetId()) } alert.SnoozeTill = req.GetSnoozeTill() err = s.changeAlertState(ctx, alert, storage.ViolationState_SNOOZED) @@ -367,7 +368,7 @@ func (s *serviceImpl) DeleteAlerts(ctx context.Context, request *v1.DeleteAlerts query, err := search.ParseQuery(request.GetQuery().GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "error parsing query: %v", err) + return nil, errors.Wrapf(errox.InvalidArgs, "error parsing query: %v", err) } paginated.FillPagination(query, request.GetQuery().GetPagination(), math.MaxInt32) @@ -379,7 +380,7 @@ func (s *serviceImpl) DeleteAlerts(ctx context.Context, request *v1.DeleteAlerts } if matchFieldQuery.MatchFieldQuery.GetField() == search.ViolationState.String() { if matchFieldQuery.MatchFieldQuery.Value != storage.ViolationState_RESOLVED.String() { - err = errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid value for violation state: %q. Only resolved alerts can be deleted", matchFieldQuery.MatchFieldQuery.Value) + err = errors.Wrapf(errox.InvalidArgs, "invalid value for violation state: %q. Only resolved alerts can be deleted", matchFieldQuery.MatchFieldQuery.Value) return } specified = true @@ -389,7 +390,7 @@ func (s *serviceImpl) DeleteAlerts(ctx context.Context, request *v1.DeleteAlerts return nil, err } if !specified { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "please specify Violation State:%s in the query to confirm deletion", storage.ViolationState_RESOLVED.String()) + return nil, errors.Wrapf(errox.InvalidArgs, "please specify Violation State:%s in the query to confirm deletion", storage.ViolationState_RESOLVED.String()) } results, err := s.dataStore.Search(ctx, query) diff --git a/central/alert/service/service_test.go b/central/alert/service/service_test.go index 09ed5c5d6fe09..c79b95ab29932 100644 --- a/central/alert/service/service_test.go +++ b/central/alert/service/service_test.go @@ -15,7 +15,7 @@ import ( baselineMocks "github.com/stackrox/rox/central/processbaseline/datastore/mocks" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/search" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" @@ -106,7 +106,7 @@ func (s *getAlertTests) TestGetAlertWhenAlertIsMissing() { result, err := s.service.GetAlert(fakeContext, s.fakeResourceByIDRequest) - s.EqualError(err, errors.Wrapf(errorhelpers.ErrNotFound, "alert with id '%s' does not exist", alerttest.FakeAlertID).Error()) + s.EqualError(err, errors.Wrapf(errox.NotFound, "alert with id '%s' does not exist", alerttest.FakeAlertID).Error()) s.Equal((*storage.Alert)(nil), result) } @@ -852,7 +852,7 @@ func (s *getAlertsCountsTests) TestGetAlertsCountsWhenTheGroupIsUnknown() { Query: "", }, GroupBy: unknownGroupBy}) - s.EqualError(err, errors.Wrapf(errorhelpers.ErrInvalidArgs, "unknown group by: %v", unknownGroupBy).Error()) + s.EqualError(err, errors.Wrapf(errox.InvalidArgs, "unknown group by: %v", unknownGroupBy).Error()) s.Equal((*v1.GetAlertsCountsResponse)(nil), result) } @@ -1057,7 +1057,7 @@ func (s *patchAlertTests) TestSnoozeAlertWithSnoozeTillInThePast() { snoozeTill, err := types.TimestampProto(time.Now().Add(-1 * time.Hour)) s.NoError(err) _, err = s.service.SnoozeAlert(context.Background(), &v1.SnoozeAlertRequest{Id: alerttest.FakeAlertID, SnoozeTill: snoozeTill}) - s.EqualError(err, errors.Wrap(errorhelpers.ErrInvalidArgs, badSnoozeErrorMsg).Error()) + s.EqualError(err, errors.Wrap(errox.InvalidArgs, badSnoozeErrorMsg).Error()) } func (s *patchAlertTests) TestResolveAlert() { diff --git a/central/apitoken/service/service_impl.go b/central/apitoken/service/service_impl.go index 58e976db1ce37..d22bb4c2ff7d8 100644 --- a/central/apitoken/service/service_impl.go +++ b/central/apitoken/service/service_impl.go @@ -13,7 +13,6 @@ import ( "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/auth/permissions/utils" - "github.com/stackrox/rox/pkg/errorhelpers" "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authn" "github.com/stackrox/rox/pkg/grpc/authz" @@ -43,14 +42,14 @@ type serviceImpl struct { func (s *serviceImpl) GetAPIToken(ctx context.Context, req *v1.ResourceByID) (*storage.TokenMetadata, error) { if req.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "empty id passed") + return nil, errors.Wrap(errox.InvalidArgs, "empty id passed") } token, err := s.backend.GetTokenOrNil(ctx, req.GetId()) if err != nil { return nil, errors.Errorf("token retrieval failed: %s", err) } if token == nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "token with id '%s' does not exist", req.GetId()) + return nil, errors.Wrapf(errox.InvalidArgs, "token with id '%s' does not exist", req.GetId()) } return token, nil } @@ -78,12 +77,12 @@ func (s *serviceImpl) RevokeToken(ctx context.Context, req *v1.ResourceByID) (*v func (s *serviceImpl) GenerateToken(ctx context.Context, req *v1.GenerateTokenRequest) (*v1.GenerateTokenResponse, error) { if req.GetName() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "token name cannot be empty") + return nil, errors.Wrap(errox.InvalidArgs, "token name cannot be empty") } if req.GetRole() != "" { if len(req.GetRoles()) > 0 { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "must use either role or roles, but not both") + return nil, errors.Wrap(errox.InvalidArgs, "must use either role or roles, but not both") } req.Roles = []string{req.GetRole()} req.Role = "" @@ -94,7 +93,7 @@ func (s *serviceImpl) GenerateToken(ctx context.Context, req *v1.GenerateTokenRe return nil, errors.Wrap(err, "unable to fetch roles") } if len(missingIndices) > 0 { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "role(s) %s don't exist", strings.Join(sliceutils.StringSelect(req.GetRoles(), missingIndices...), ",")) + return nil, errors.Wrapf(errox.InvalidArgs, "role(s) %s don't exist", strings.Join(sliceutils.StringSelect(req.GetRoles(), missingIndices...), ",")) } id, err := authn.IdentityFromContext(ctx) diff --git a/central/authprovider/service/service_impl.go b/central/authprovider/service/service_impl.go index 743c6f7b0730d..85c0bf9c6cd24 100644 --- a/central/authprovider/service/service_impl.go +++ b/central/authprovider/service/service_impl.go @@ -16,7 +16,7 @@ import ( "github.com/stackrox/rox/pkg/auth/authproviders/basic" "github.com/stackrox/rox/pkg/auth/authproviders/idputil" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/allow" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" @@ -70,11 +70,11 @@ 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, errorhelpers.NewErrInvalidArgs("auth provider id is required") + return nil, errox.NewErrInvalidArgs("auth provider id is required") } authProvider := s.registry.GetProvider(request.GetId()) if authProvider == nil { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "auth provider %q not found", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "auth provider %q not found", request.GetId()) } return authProvider.StorageView(), 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, errorhelpers.NewErrInvalidArgs("no auth provider name specified") + return nil, errox.NewErrInvalidArgs("no auth provider name specified") } if providerReq.GetId() != "" { - return nil, errorhelpers.NewErrInvalidArgs("auth provider id must be empty") + return nil, errox.NewErrInvalidArgs("auth provider id must be empty") } if providerReq.GetLoginUrl() != "" { - return nil, errorhelpers.NewErrInvalidArgs("auth provider loginUrl field must be empty") + return nil, errox.NewErrInvalidArgs("auth provider loginUrl field must be empty") } provider, err := s.registry.CreateProvider(ctx, authproviders.WithStorageView(providerReq), authproviders.WithValidateCallback(datastore.Singleton())) if err != nil { - return nil, errors.Wrap(errorhelpers.NewErrInvalidArgs(err.Error()), "creating auth provider instance") + return nil, errors.Wrap(errox.NewErrInvalidArgs(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, errorhelpers.NewErrInvalidArgs("auth provider id must not be empty") + return nil, errox.NewErrInvalidArgs("auth provider id must not be empty") } provider := s.registry.GetProvider(request.GetId()) if provider == nil { - return nil, errorhelpers.NewErrInvalidArgs(fmt.Sprintf("auth provider with id %q does not exist", request.GetId())) + return nil, errox.NewErrInvalidArgs(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, errorhelpers.NewErrInvalidArgs(fmt.Sprintf("auth provider validation check failed: %v", err)) + return nil, errox.NewErrInvalidArgs(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(errorhelpers.NewErrInvalidArgs(err.Error()), "creating auth provider instance") + return nil, errors.Wrap(errox.NewErrInvalidArgs(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, errorhelpers.NewErrInvalidArgs("auth provider id must not be empty") + return nil, errox.NewErrInvalidArgs("auth provider id must not be 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(errorhelpers.NewErrInvalidArgs(err.Error()), "updating auth provider") + return nil, errors.Wrap(errox.NewErrInvalidArgs(err.Error()), "updating auth provider") } return provider.StorageView(), nil } @@ -225,13 +225,13 @@ 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, errorhelpers.NewErrInvalidArgs("auth provider id is required") + return nil, errox.NewErrInvalidArgs("auth provider id is required") } // Get auth provider. authProvider := s.registry.GetProvider(request.GetId()) if authProvider == nil { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "auth provider %q not found", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "auth provider %q not found", request.GetId()) } // Delete auth provider. if err := s.registry.DeleteProvider(ctx, request.GetId(), true); err != nil { diff --git a/central/certgen/sensor.go b/central/certgen/sensor.go index 98bd46bd506ff..d9c86f6d3e9df 100644 --- a/central/certgen/sensor.go +++ b/central/certgen/sensor.go @@ -10,7 +10,7 @@ import ( "github.com/stackrox/rox/central/clusters/zip" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/apiparams" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/httputil" "github.com/stackrox/rox/pkg/images/defaults" "github.com/stackrox/rox/pkg/renderer" @@ -26,7 +26,7 @@ func (s *serviceImpl) getSensorCerts(r *http.Request) ([]byte, *storage.Cluster, clusterID := params.ID if clusterID == "" { - return nil, nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "no cluster ID specified") + return nil, nil, errors.Wrap(errox.InvalidArgs, "no cluster ID specified") } cluster, _, err := s.clusters.GetCluster(r.Context(), clusterID) @@ -34,7 +34,7 @@ func (s *serviceImpl) getSensorCerts(r *http.Request) ([]byte, *storage.Cluster, return nil, nil, errors.Errorf("failed to retrieve cluster: %v", err) } if cluster == nil { - return nil, nil, errors.Wrapf(errorhelpers.ErrNotFound, "cluster with ID %q not found", clusterID) + return nil, nil, errors.Wrapf(errox.NotFound, "cluster with ID %q not found", clusterID) } certs, err := zip.GenerateCertsAndAddToZip(nil, cluster, s.serviceIdentities) diff --git a/central/cluster/datastore/datastore_impl.go b/central/cluster/datastore/datastore_impl.go index 974b375d509af..89816b8082680 100644 --- a/central/cluster/datastore/datastore_impl.go +++ b/central/cluster/datastore/datastore_impl.go @@ -35,6 +35,7 @@ import ( clusterValidation "github.com/stackrox/rox/pkg/cluster" "github.com/stackrox/rox/pkg/concurrency" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/images/defaults" "github.com/stackrox/rox/pkg/protoconv" "github.com/stackrox/rox/pkg/sac" @@ -926,7 +927,7 @@ func (ds *datastoreImpl) LookupOrCreateClusterFromConfig(ctx context.Context, cl func normalizeCluster(cluster *storage.Cluster) error { if cluster == nil { - return errorhelpers.NewErrInvariantViolation("cannot normalize nil cluster object") + return errox.NewErrInvariantViolation("cannot normalize nil cluster object") } cluster.CentralApiEndpoint = strings.TrimPrefix(cluster.GetCentralApiEndpoint(), "https://") @@ -944,7 +945,7 @@ func validateInput(cluster *storage.Cluster) error { // `cluster.* bool` flags remain untouched. func addDefaults(cluster *storage.Cluster) error { if cluster == nil { - return errorhelpers.NewErrInvariantViolation("cannot enrich nil cluster object") + return errox.NewErrInvariantViolation("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/cluster/service/service_impl.go b/central/cluster/service/service_impl.go index 16b1bf21be9a6..dbeca81d401f4 100644 --- a/central/cluster/service/service_impl.go +++ b/central/cluster/service/service_impl.go @@ -12,7 +12,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/or" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" @@ -63,7 +63,7 @@ func (s *serviceImpl) AuthFuncOverride(ctx context.Context, fullMethodName strin // PostCluster creates a new cluster. func (s *serviceImpl) PostCluster(ctx context.Context, request *storage.Cluster) (*v1.ClusterResponse, error) { if request.GetId() != "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Id field should be empty when posting a new cluster") + return nil, errors.Wrap(errox.InvalidArgs, "Id field should be empty when posting a new cluster") } id, err := s.datastore.AddCluster(ctx, request) if err != nil { @@ -76,7 +76,7 @@ func (s *serviceImpl) PostCluster(ctx context.Context, request *storage.Cluster) // PutCluster updates an existing cluster. func (s *serviceImpl) PutCluster(ctx context.Context, request *storage.Cluster) (*v1.ClusterResponse, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Id must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "Id must be provided") } err := s.datastore.UpdateCluster(ctx, request) if err != nil { @@ -88,7 +88,7 @@ func (s *serviceImpl) PutCluster(ctx context.Context, request *storage.Cluster) // GetCluster returns the specified cluster. func (s *serviceImpl) GetCluster(ctx context.Context, request *v1.ResourceByID) (*v1.ClusterResponse, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Id must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "Id must be provided") } return s.getCluster(ctx, request.GetId()) } @@ -99,7 +99,7 @@ func (s *serviceImpl) getCluster(ctx context.Context, id string) (*v1.ClusterRes return nil, errors.Errorf("Could not get cluster: %s", err) } if !ok { - return nil, errors.Wrap(errorhelpers.ErrNotFound, "Not found") + return nil, errors.Wrap(errox.NotFound, "Not found") } return &v1.ClusterResponse{ @@ -111,7 +111,7 @@ func (s *serviceImpl) getCluster(ctx context.Context, id string) (*v1.ClusterRes func (s *serviceImpl) GetClusters(ctx context.Context, req *v1.GetClustersRequest) (*v1.ClustersList, error) { q, err := search.ParseQuery(req.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid query %q: %v", req.GetQuery(), err) + return nil, errors.Wrapf(errox.InvalidArgs, "invalid query %q: %v", req.GetQuery(), err) } clusters, err := s.datastore.SearchRawClusters(ctx, q) @@ -126,7 +126,7 @@ func (s *serviceImpl) GetClusters(ctx context.Context, req *v1.GetClustersReques // DeleteCluster removes a cluster func (s *serviceImpl) DeleteCluster(ctx context.Context, request *v1.ResourceByID) (*v1.Empty, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Request must have a id") + return nil, errors.Wrap(errox.InvalidArgs, "Request must have a id") } if err := s.datastore.RemoveCluster(ctx, request.GetId(), nil); err != nil { return nil, err diff --git a/central/compliance/datastore/datastore_impl.go b/central/compliance/datastore/datastore_impl.go index 6f37aea6be0b5..bbeccc16b6a77 100644 --- a/central/compliance/datastore/datastore_impl.go +++ b/central/compliance/datastore/datastore_impl.go @@ -12,7 +12,7 @@ import ( "github.com/stackrox/rox/central/role/resources" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/logging" "github.com/stackrox/rox/pkg/sac" "github.com/stackrox/rox/pkg/sync" @@ -48,7 +48,7 @@ func (ds *datastoreImpl) GetSpecificRunResults(ctx context.Context, clusterID, s if ok, err := complianceSAC.ReadAllowed(ctx, sac.ClusterScopeKey(clusterID)); err != nil { return types.ResultsWithStatus{}, err } else if !ok { - return types.ResultsWithStatus{}, errorhelpers.ErrNotFound + return types.ResultsWithStatus{}, errox.NotFound } res, err := ds.storage.GetSpecificRunResults(clusterID, standardID, runID, flags) @@ -72,7 +72,7 @@ func (ds *datastoreImpl) GetLatestRunResults(ctx context.Context, clusterID, sta if ok, err := complianceSAC.ReadAllowed(ctx, sac.ClusterScopeKey(clusterID)); err != nil { return types.ResultsWithStatus{}, err } else if !ok { - return types.ResultsWithStatus{}, errorhelpers.ErrNotFound + return types.ResultsWithStatus{}, errox.NotFound } res, err := ds.storage.GetLatestRunResults(clusterID, standardID, flags) @@ -126,7 +126,7 @@ func (ds *datastoreImpl) IsComplianceRunSuccessfulOnCluster(ctx context.Context, if ok, err := complianceSAC.ReadAllowed(ctx, sac.ClusterScopeKey(clusterID)); err != nil { return false, err } else if !ok { - return false, errors.Wrapf(errorhelpers.ErrNotFound, "ClusterID %s", clusterID) + return false, errors.Wrapf(errox.NotFound, "ClusterID %s", clusterID) } results, err := ds.storage.GetLatestRunMetadataBatch(clusterID, standardIDs) if err != nil || len(results) == 0 { diff --git a/central/compliance/datastore/test/datastore_test.go b/central/compliance/datastore/test/datastore_test.go index ac64afabe3924..4506a2d95e764 100644 --- a/central/compliance/datastore/test/datastore_test.go +++ b/central/compliance/datastore/test/datastore_test.go @@ -13,7 +13,7 @@ import ( "github.com/stackrox/rox/central/compliance/datastore/types" "github.com/stackrox/rox/central/role/resources" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/sac" "github.com/stretchr/testify/suite" ) @@ -215,7 +215,7 @@ func (s *complianceDataStoreWithSACTestSuite) TestEnforceGetLatestRunResults() { _, err := s.dataStore.GetLatestRunResults(s.hasNoneCtx, clusterID, standardID, types.WithMessageStrings) // Check results match. - s.ErrorIs(err, errorhelpers.ErrNotFound) + s.ErrorIs(err, errox.NotFound) } func (s *complianceDataStoreWithSACTestSuite) TestEnforceStoreRunResults() { diff --git a/central/compliance/manager/manager_impl.go b/central/compliance/manager/manager_impl.go index ec397b53e45f4..8e84b0d1db5c3 100644 --- a/central/compliance/manager/manager_impl.go +++ b/central/compliance/manager/manager_impl.go @@ -24,6 +24,7 @@ import ( "github.com/stackrox/rox/pkg/bolthelper" "github.com/stackrox/rox/pkg/concurrency" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/logging" "github.com/stackrox/rox/pkg/sac" "github.com/stackrox/rox/pkg/search" @@ -518,7 +519,7 @@ func (m *manager) GetRecentRun(ctx context.Context, id string) (*v1.ComplianceRu if ok, err := complianceRunSAC.ReadAllowed(ctx, sac.ClusterScopeKey(run.ClusterId)); err != nil { return nil, err } else if !ok { - return nil, errorhelpers.ErrNotFound + return nil, errox.NotFound } return run, nil @@ -686,7 +687,7 @@ func (m *manager) GetRunStatuses(ctx context.Context, ids ...string) ([]*v1.Comp if ok, err := complianceRunSAC.ScopeChecker(ctx, storage.Access_READ_ACCESS).AllAllowed(ctx, clusterScopes.get()); err != nil { return nil, err } else if !ok { - return nil, errorhelpers.ErrNotFound + return nil, errox.NotFound } return runStatuses, nil diff --git a/central/compliance/manager/service/service_impl.go b/central/compliance/manager/service/service_impl.go index 99075587cc5bb..d6061d20f2f92 100644 --- a/central/compliance/manager/service/service_impl.go +++ b/central/compliance/manager/service/service_impl.go @@ -10,7 +10,7 @@ import ( "github.com/stackrox/rox/central/role/resources" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -70,7 +70,7 @@ func (s *service) GetRecentRuns(ctx context.Context, req *v1.GetRecentCompliance func (s *service) TriggerRuns(ctx context.Context, req *v1.TriggerComplianceRunsRequest) (*v1.TriggerComplianceRunsResponse, error) { expanded, err := s.manager.ExpandSelection(ctx, req.GetSelection().GetClusterId(), req.GetSelection().GetStandardId()) if err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "could not expand cluster/standard selection: %v", err) + return nil, errors.Wrapf(errox.InvalidArgs, "could not expand cluster/standard selection: %v", err) } runs, err := s.manager.TriggerRuns(ctx, expanded...) diff --git a/central/compliance/service/service_impl.go b/central/compliance/service/service_impl.go index 7172f8b2fb9f1..efa8172a9da5e 100644 --- a/central/compliance/service/service_impl.go +++ b/central/compliance/service/service_impl.go @@ -15,7 +15,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -96,7 +96,7 @@ func (s *serviceImpl) GetStandard(ctx context.Context, req *v1.ResourceByID) (*v return nil, err } if !exists { - return nil, errors.Wrap(errorhelpers.ErrNotFound, req.GetId()) + return nil, errors.Wrap(errox.NotFound, req.GetId()) } return &v1.GetComplianceStandardResponse{ Standard: standard, @@ -110,7 +110,7 @@ func (s *serviceImpl) GetComplianceControlResults(ctx context.Context, query *v1 if query.GetQuery() != "" { q, err = search.ParseQuery(query.GetQuery()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } } results, err := s.complianceDataStore.QueryControlResults(ctx, q) diff --git a/central/config/service/service.go b/central/config/service/service.go index 527f0299242b3..5b148b41787be 100644 --- a/central/config/service/service.go +++ b/central/config/service/service.go @@ -10,7 +10,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" pkgGRPC "github.com/stackrox/rox/pkg/grpc" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/allow" @@ -110,7 +110,7 @@ func (s *serviceImpl) GetConfig(ctx context.Context, _ *v1.Empty) (*storage.Conf // PutConfig updates Central's config func (s *serviceImpl) PutConfig(ctx context.Context, req *v1.PutConfigRequest) (*storage.Config, error) { if req.GetConfig() == nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "config must be specified") + return nil, errors.Wrap(errox.InvalidArgs, "config must be specified") } if err := s.datastore.UpsertConfig(ctx, req.GetConfig()); err != nil { return nil, err diff --git a/central/credentialexpiry/service/service_impl.go b/central/credentialexpiry/service/service_impl.go index e55c9aba5dbe9..1d0b026b842b6 100644 --- a/central/credentialexpiry/service/service_impl.go +++ b/central/credentialexpiry/service/service_impl.go @@ -13,6 +13,7 @@ import ( imageIntegrationStore "github.com/stackrox/rox/central/imageintegration/datastore" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -44,7 +45,7 @@ func (s *serviceImpl) GetCertExpiry(ctx context.Context, request *v1.GetCertExpi case v1.GetCertExpiry_SCANNER: return s.getScannerCertExpiry(ctx) } - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid component: %v", request.GetComponent()) + return nil, errors.Wrapf(errox.InvalidArgs, "invalid component: %v", request.GetComponent()) } func (s *serviceImpl) getCentralCertExpiry() (*v1.GetCertExpiry_Response, error) { @@ -123,7 +124,7 @@ func (s *serviceImpl) getScannerCertExpiry(ctx context.Context) (*v1.GetCertExpi } } if len(clairifyEndpoints) == 0 { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "StackRox Scanner is not integrated") + return nil, errors.Wrap(errox.InvalidArgs, "StackRox Scanner is not integrated") } errC := make(chan error, len(clairifyEndpoints)) expiryC := make(chan *types.Timestamp, len(clairifyEndpoints)) diff --git a/central/cve/service/service_impl.go b/central/cve/service/service_impl.go index 73404116b45b9..fab7a536c400e 100644 --- a/central/cve/service/service_impl.go +++ b/central/cve/service/service_impl.go @@ -14,7 +14,7 @@ import ( "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/concurrency" "github.com/stackrox/rox/pkg/dackbox/utils/queue" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/and" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" @@ -122,7 +122,7 @@ func (s *serviceImpl) validateCVEsExist(ctx context.Context, ids ...string) erro if len(result) < len(ids) { missingIds := set.NewStringSet(ids...).Difference(search.ResultsToIDSet(result)) - return errors.Wrapf(errorhelpers.ErrNotFound, "Following CVEs not found: %s", strings.Join(missingIds.AsSlice(), ", ")) + return errors.Wrapf(errox.NotFound, "Following CVEs not found: %s", strings.Join(missingIds.AsSlice(), ", ")) } return nil } diff --git a/central/debug/service/service.go b/central/debug/service/service.go index 1c089530a7eed..9262f9bfdead9 100644 --- a/central/debug/service/service.go +++ b/central/debug/service/service.go @@ -26,7 +26,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/buildinfo" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" grpcPkg "github.com/stackrox/rox/pkg/grpc" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" @@ -155,7 +155,7 @@ func (s *serviceImpl) GetLogLevel(ctx context.Context, req *v1.GetLogLevelReques logging.ForEachModule(forEachModule, req.GetModules()) if len(unknownModules) > 0 { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "Unknown module(s): %s", strings.Join(unknownModules, ", ")) + return nil, errors.Wrapf(errox.InvalidArgs, "Unknown module(s): %s", strings.Join(unknownModules, ", ")) } return resp, nil @@ -166,7 +166,7 @@ func (s *serviceImpl) SetLogLevel(ctx context.Context, req *v1.LogLevelRequest) levelStr := req.GetLevel() zapLevel, ok := logging.LevelForLabel(levelStr) if !ok { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "Unknown log level %s", levelStr) + return nil, errors.Wrapf(errox.InvalidArgs, "Unknown log level %s", levelStr) } // If this is a global request, then set the global level and return @@ -185,7 +185,7 @@ func (s *serviceImpl) SetLogLevel(ctx context.Context, req *v1.LogLevelRequest) }, req.GetModules()) if len(unknownModules) > 0 { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "Unknown module(s): %s", strings.Join(unknownModules, ", ")) + return nil, errors.Wrapf(errox.InvalidArgs, "Unknown module(s): %s", strings.Join(unknownModules, ", ")) } return &types.Empty{}, nil diff --git a/central/deployment/service/service_impl.go b/central/deployment/service/service_impl.go index 61ba3e1bedd1d..12743291bb360 100644 --- a/central/deployment/service/service_impl.go +++ b/central/deployment/service/service_impl.go @@ -17,7 +17,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -123,7 +123,7 @@ func (s *serviceImpl) GetDeployment(ctx context.Context, request *v1.ResourceByI return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "deployment with id '%s' does not exist", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "deployment with id '%s' does not exist", request.GetId()) } return deployment, nil } @@ -135,7 +135,7 @@ func (s *serviceImpl) GetDeploymentWithRisk(ctx context.Context, request *v1.Res return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "deployment with id '%s' does not exist", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "deployment with id '%s' does not exist", request.GetId()) } risk, _, err := s.risks.GetRiskForDeployment(ctx, deployment) @@ -154,7 +154,7 @@ func (s *serviceImpl) CountDeployments(ctx context.Context, request *v1.RawQuery // Fill in Query. parsedQuery, err := search.ParseQuery(request.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } numDeployments, err := s.datastore.Count(ctx, parsedQuery) @@ -169,7 +169,7 @@ func (s *serviceImpl) ListDeployments(ctx context.Context, request *v1.RawQuery) // Fill in Query. parsedQuery, err := search.ParseQuery(request.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } // Fill in pagination. diff --git a/central/development/service/service_impl.go b/central/development/service/service_impl.go index e3b02b488139c..aced1b03c367c 100644 --- a/central/development/service/service_impl.go +++ b/central/development/service/service_impl.go @@ -13,7 +13,7 @@ import ( "github.com/pkg/errors" "github.com/stackrox/rox/central/sensor/service/connection" "github.com/stackrox/rox/generated/internalapi/central" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz/allow" "github.com/stackrox/rox/pkg/httputil/proxy" "github.com/stackrox/rox/pkg/logging" @@ -54,7 +54,7 @@ func (s *serviceImpl) ReconciliationStatsByCluster(context.Context, *central.Emp func (s *serviceImpl) URLHasValidCert(ctx context.Context, req *central.URLHasValidCertRequest) (*central.URLHasValidCertResponse, error) { if !strings.HasPrefix(req.GetUrl(), "https://") { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "url %q must start with https", req.GetUrl()) + return nil, errors.Wrapf(errox.InvalidArgs, "url %q must start with https", req.GetUrl()) } _, err := s.client.Get(req.GetUrl()) if err == nil { diff --git a/central/externalbackups/service/service_impl.go b/central/externalbackups/service/service_impl.go index cc077827dbf72..a06528a2df7c5 100644 --- a/central/externalbackups/service/service_impl.go +++ b/central/externalbackups/service/service_impl.go @@ -13,6 +13,7 @@ import ( "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/endpoints" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -66,14 +67,14 @@ func (s *serviceImpl) AuthFuncOverride(ctx context.Context, fullMethodName strin // GetExternalBackup retrieves the external backup based on the id passed func (s *serviceImpl) GetExternalBackup(ctx context.Context, request *v1.ResourceByID) (*storage.ExternalBackup, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "id must be specified when requesting an external backup") + return nil, errors.Wrap(errox.InvalidArgs, "id must be specified when requesting an external backup") } backup, err := s.dataStore.GetBackup(ctx, request.GetId()) if err != nil { return nil, err } if backup == nil { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "No external backup with id %q found", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "No external backup with id %q found", request.GetId()) } secrets.ScrubSecretsFromStructWithReplacement(backup, secrets.ScrubReplacementStr) return backup, nil @@ -124,7 +125,7 @@ func (s *serviceImpl) TestExternalBackup(ctx context.Context, externalBackup *st // TestUpdatedExternalBackup tests that the provided config is valid func (s *serviceImpl) TestUpdatedExternalBackup(ctx context.Context, request *v1.UpdateExternalBackupRequest) (*v1.Empty, error) { if err := validateBackup(request.GetExternalBackup()); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if err := s.reconcileUpdateExternalBackupRequest(ctx, request); err != nil { return nil, err @@ -137,7 +138,7 @@ func (s *serviceImpl) TestUpdatedExternalBackup(ctx context.Context, request *v1 func (s *serviceImpl) TriggerExternalBackup(ctx context.Context, request *v1.ResourceByID) (*v1.Empty, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "id must be specified when triggering a backup") + return nil, errors.Wrap(errox.InvalidArgs, "id must be specified when triggering a backup") } if err := s.manager.Backup(ctx, request.GetId()); err != nil { log.Errorf("error trigger backup: %v", err) @@ -148,7 +149,7 @@ func (s *serviceImpl) TriggerExternalBackup(ctx context.Context, request *v1.Res func (s *serviceImpl) upsertExternalBackup(ctx context.Context, request *storage.ExternalBackup) error { if err := s.manager.Upsert(ctx, request); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } if err := s.dataStore.UpsertBackup(ctx, request); err != nil { s.manager.Remove(ctx, request.GetId()) @@ -165,13 +166,13 @@ func (s *serviceImpl) PutExternalBackup(ctx context.Context, externalBackup *sto // UpdateExternalBackup inserts a new external backup into the system func (s *serviceImpl) UpdateExternalBackup(ctx context.Context, request *v1.UpdateExternalBackupRequest) (*storage.ExternalBackup, error) { if request.GetExternalBackup().GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "id field must be provided when updating an external backup") + return nil, errors.Wrap(errox.InvalidArgs, "id field must be provided when updating an external backup") } if err := s.reconcileUpdateExternalBackupRequest(ctx, request); err != nil { return nil, err } if err := validateBackup(request.GetExternalBackup()); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if err := s.upsertExternalBackup(ctx, request.GetExternalBackup()); err != nil { return nil, err @@ -182,10 +183,10 @@ func (s *serviceImpl) UpdateExternalBackup(ctx context.Context, request *v1.Upda // PostExternalBackup adds a new external backup to the system func (s *serviceImpl) PostExternalBackup(ctx context.Context, request *storage.ExternalBackup) (*storage.ExternalBackup, error) { if request.GetId() != "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "id field must be empty when posting a new external backup") + return nil, errors.Wrap(errox.InvalidArgs, "id field must be empty when posting a new external backup") } if err := validateBackup(request); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } request.Id = uuid.NewV4().String() if err := s.upsertExternalBackup(ctx, request); err != nil { @@ -202,7 +203,7 @@ func (s *serviceImpl) PostExternalBackup(ctx context.Context, request *storage.E // DeleteExternalBackup deletes an external backup from the system func (s *serviceImpl) DeleteExternalBackup(ctx context.Context, request *v1.ResourceByID) (*v1.Empty, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Backup id is required for deletions") + return nil, errors.Wrap(errox.InvalidArgs, "Backup id is required for deletions") } if err := s.dataStore.RemoveBackup(ctx, request.GetId()); err != nil { return nil, err @@ -221,20 +222,20 @@ func (s *serviceImpl) reconcileUpdateExternalBackupRequest(ctx context.Context, return nil } if updateRequest.GetExternalBackup() == nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "request is missing external backup config") + return errors.Wrap(errox.InvalidArgs, "request is missing external backup config") } if updateRequest.GetExternalBackup().GetId() == "" { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "id required for stored credential reconciliation") + return errors.Wrap(errox.InvalidArgs, "id required for stored credential reconciliation") } existingBackupConfig, err := s.dataStore.GetBackup(ctx, updateRequest.GetExternalBackup().GetId()) if err != nil { return err } if existingBackupConfig == nil { - return errors.Wrapf(errorhelpers.ErrNotFound, "backup config %s not found", updateRequest.GetExternalBackup().GetId()) + return errors.Wrapf(errox.NotFound, "backup config %s not found", updateRequest.GetExternalBackup().GetId()) } if err := reconcileExternalBackupWithExisting(updateRequest.GetExternalBackup(), existingBackupConfig); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } return nil } diff --git a/central/globaldb/v2backuprestore/service/http_handlers.go b/central/globaldb/v2backuprestore/service/http_handlers.go index a628d60d457bf..9b6c843dd358f 100644 --- a/central/globaldb/v2backuprestore/service/http_handlers.go +++ b/central/globaldb/v2backuprestore/service/http_handlers.go @@ -11,7 +11,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/pkg/binenc" "github.com/stackrox/rox/pkg/concurrency" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/httputil" "github.com/stackrox/rox/pkg/ioutils" "github.com/stackrox/rox/pkg/uuid" @@ -36,24 +36,24 @@ func (s *service) handleRestore(req *http.Request) error { headerLenStr := queryValues.Get("headerLength") headerLen, err := strconv.Atoi(headerLenStr) if err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid header length %q: %v", headerLenStr, err) + return errors.Wrapf(errox.InvalidArgs, "invalid header length %q: %v", headerLenStr, err) } id := queryValues.Get("id") if id == "" { id = uuid.NewV4().String() } else if _, err := uuid.FromString(id); err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "ID must be unset or a valid UUID (got: %q)", id) + return errors.Wrapf(errox.InvalidArgs, "ID must be unset or a valid UUID (got: %q)", id) } headerBytes := make([]byte, headerLen) if _, err := io.ReadFull(req.Body, headerBytes); err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "could not read request header (%d bytes): %v", headerLen, err) + return errors.Wrapf(errox.InvalidArgs, "could not read request header (%d bytes): %v", headerLen, err) } var header v1.DBRestoreRequestHeader if err := proto.Unmarshal(headerBytes, &header); err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "could not parse restore request header: %v", err) + return errors.Wrapf(errox.InvalidArgs, "could not parse restore request header: %v", err) } // Make sure we perform a clean cut when reading from the stream. Returning from a handler while a concurrent call @@ -93,31 +93,31 @@ func (s *service) handleResumeRestore(req *http.Request) error { queryValues := req.URL.Query() processID := queryValues.Get("id") if processID == "" { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "need to specify a restore process ID for resuming") + return errors.Wrap(errox.InvalidArgs, "need to specify a restore process ID for resuming") } attemptID := queryValues.Get("attemptId") if _, err := uuid.FromString(attemptID); err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid attempt ID %q: %v", attemptID, err) + return errors.Wrapf(errox.InvalidArgs, "invalid attempt ID %q: %v", attemptID, err) } posStr := queryValues.Get("pos") pos, err := strconv.ParseInt(posStr, 10, 64) if err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid position specification %q: %v", posStr, err) + return errors.Wrapf(errox.InvalidArgs, "invalid position specification %q: %v", posStr, err) } crc32Str := queryValues.Get("crc32") crc32Val, err := strconv.ParseUint(crc32Str, 16, 32) if err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid CRC32 value %q: %v", crc32Str, err) + return errors.Wrapf(errox.InvalidArgs, "invalid CRC32 value %q: %v", crc32Str, err) } crc32 := uint32(crc32Val) activeProcess := s.mgr.GetActiveRestoreProcess() if activeProcess.Metadata().GetId() != processID { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "specified process ID %s does not match ID of currently active restore process", processID) + return errors.Wrapf(errox.InvalidArgs, "specified process ID %s does not match ID of currently active restore process", processID) } // Make sure we perform a clean cut when reading from the stream. Returning from a handler while a concurrent call diff --git a/central/group/service/service_impl.go b/central/group/service/service_impl.go index cd2fea9a5d8b7..6fa96c621eb3c 100644 --- a/central/group/service/service_impl.go +++ b/central/group/service/service_impl.go @@ -12,7 +12,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -92,7 +92,7 @@ func (s *serviceImpl) GetGroup(ctx context.Context, props *storage.GroupProperti return nil, err } if group == nil { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "group %q not found", proto.MarshalTextString(props)) + return nil, errors.Wrapf(errox.NotFound, "group %q not found", proto.MarshalTextString(props)) } return group, nil } @@ -100,7 +100,7 @@ func (s *serviceImpl) GetGroup(ctx context.Context, props *storage.GroupProperti func (s *serviceImpl) BatchUpdate(ctx context.Context, req *v1.GroupBatchUpdateRequest) (*v1.Empty, error) { for _, group := range req.GetRequiredGroups() { if err := validate(group); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } } @@ -113,7 +113,7 @@ func (s *serviceImpl) BatchUpdate(ctx context.Context, req *v1.GroupBatchUpdateR func (s *serviceImpl) CreateGroup(ctx context.Context, group *storage.Group) (*v1.Empty, error) { if err := validate(group); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } err := s.groups.Add(ctx, group) if err != nil { @@ -124,7 +124,7 @@ func (s *serviceImpl) CreateGroup(ctx context.Context, group *storage.Group) (*v func (s *serviceImpl) UpdateGroup(ctx context.Context, group *storage.Group) (*v1.Empty, error) { if err := validate(group); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } err := s.groups.Update(ctx, group) if err != nil { diff --git a/central/image/service/service_impl.go b/central/image/service/service_impl.go index 8c9e7d2c9ef71..ae24aa2a10e3d 100644 --- a/central/image/service/service_impl.go +++ b/central/image/service/service_impl.go @@ -20,7 +20,7 @@ import ( "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/concurrency" "github.com/stackrox/rox/pkg/env" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/expiringcache" "github.com/stackrox/rox/pkg/features" "github.com/stackrox/rox/pkg/grpc/authz" @@ -115,7 +115,7 @@ func (s *serviceImpl) AuthFuncOverride(ctx context.Context, fullMethodName strin // GetImage returns an image with given sha if it exists. func (s *serviceImpl) GetImage(ctx context.Context, request *v1.GetImageRequest) (*storage.Image, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "id must be specified") + return nil, errors.Wrap(errox.InvalidArgs, "id must be specified") } id := types.NewDigest(request.GetId()).Digest() @@ -125,7 +125,7 @@ func (s *serviceImpl) GetImage(ctx context.Context, request *v1.GetImageRequest) return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "image with id %q does not exist", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "image with id %q does not exist", request.GetId()) } if !request.GetIncludeSnoozed() { @@ -145,7 +145,7 @@ func (s *serviceImpl) CountImages(ctx context.Context, request *v1.RawQuery) (*v // Fill in Query. parsedQuery, err := search.ParseQuery(request.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } numImages, err := s.datastore.Count(ctx, parsedQuery) @@ -160,7 +160,7 @@ func (s *serviceImpl) ListImages(ctx context.Context, request *v1.RawQuery) (*v1 // Fill in Query. parsedQuery, err := search.ParseQuery(request.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } // Fill in pagination. @@ -410,7 +410,7 @@ func (s *serviceImpl) DeleteImages(ctx context.Context, request *v1.DeleteImages query, err := search.ParseQuery(request.GetQuery().GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "error parsing query: %v", err) + return nil, errors.Wrapf(errox.InvalidArgs, "error parsing query: %v", err) } paginated.FillPagination(query, request.GetQuery().GetPagination(), math.MaxInt32) diff --git a/central/imageintegration/service/service_impl.go b/central/imageintegration/service/service_impl.go index 05264d2875f42..11283e6228b7b 100644 --- a/central/imageintegration/service/service_impl.go +++ b/central/imageintegration/service/service_impl.go @@ -16,6 +16,7 @@ import ( "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/endpoints" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authn" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/or" @@ -78,14 +79,14 @@ func scrubImageIntegration(i *storage.ImageIntegration) { // GetImageIntegration returns the image integration given its ID. func (s *serviceImpl) GetImageIntegration(ctx context.Context, request *v1.ResourceByID) (*storage.ImageIntegration, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "image integration id must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "image integration id must be provided") } integration, exists, err := s.datastore.GetImageIntegration(ctx, request.GetId()) if err != nil { return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "image integration %s not found", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "image integration %s not found", request.GetId()) } scrubImageIntegration(integration) return integration, nil @@ -142,16 +143,16 @@ func (s *serviceImpl) PutImageIntegration(ctx context.Context, imageIntegration // PostImageIntegration creates an image integration. func (s *serviceImpl) PostImageIntegration(ctx context.Context, request *storage.ImageIntegration) (*storage.ImageIntegration, error) { if request.GetId() != "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "id field should be empty when posting a new image integration") + return nil, errors.Wrap(errox.InvalidArgs, "id field should be empty when posting a new image integration") } if err := s.validateTestAndNormalize(ctx, request); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } id, err := s.datastore.AddImageIntegration(ctx, request) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } request.Id = id @@ -167,7 +168,7 @@ func (s *serviceImpl) PostImageIntegration(ctx context.Context, request *storage // DeleteImageIntegration removes a image integration given its ID. func (s *serviceImpl) DeleteImageIntegration(ctx context.Context, request *v1.ResourceByID) (*v1.Empty, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "image integration id must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "image integration id must be provided") } if err := s.datastore.RemoveImageIntegration(ctx, request.GetId()); err != nil { return nil, err @@ -182,13 +183,13 @@ func (s *serviceImpl) DeleteImageIntegration(ctx context.Context, request *v1.Re // UpdateImageIntegration modifies a given image integration, with optional stored credential reconciliation. func (s *serviceImpl) UpdateImageIntegration(ctx context.Context, request *v1.UpdateImageIntegrationRequest) (*v1.Empty, error) { if err := s.validateIntegration(ctx, request.GetConfig()); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if err := s.reconcileUpdateImageIntegrationRequest(ctx, request); err != nil { return nil, err } if err := s.validateTestAndNormalize(ctx, request.GetConfig()); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if err := s.datastore.UpdateImageIntegration(ctx, request.GetConfig()); err != nil { return nil, err @@ -209,7 +210,7 @@ func (s *serviceImpl) TestImageIntegration(ctx context.Context, imageIntegration // TestUpdatedImageIntegration checks if the given image integration is correctly configured, with optional stored credential reconciliation. func (s *serviceImpl) TestUpdatedImageIntegration(ctx context.Context, request *v1.UpdateImageIntegrationRequest) (*v1.Empty, error) { if err := s.validateIntegration(ctx, request.GetConfig()); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if err := s.reconcileUpdateImageIntegrationRequest(ctx, request); err != nil { return nil, err @@ -224,21 +225,21 @@ func (s *serviceImpl) testImageIntegration(request *storage.ImageIntegration) er for _, category := range request.GetCategories() { if category == storage.ImageIntegrationCategory_REGISTRY { if err := s.testRegistryIntegration(request); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, errors.Wrap(err, "registry integration").Error()) + return errors.Wrap(errox.InvalidArgs, errors.Wrap(err, "registry integration").Error()) } } if category == storage.ImageIntegrationCategory_SCANNER { if err := s.testScannerIntegration(request); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, errors.Wrap(err, "image scanner integration").Error()) + return errors.Wrap(errox.InvalidArgs, errors.Wrap(err, "image scanner integration").Error()) } } if category == storage.ImageIntegrationCategory_NODE_SCANNER { nodeIntegration, err := imageIntegrationToNodeIntegration(request) if err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, errors.Wrap(err, "node scanner integration").Error()) + return errors.Wrap(errox.InvalidArgs, errors.Wrap(err, "node scanner integration").Error()) } if err := s.testNodeScannerIntegration(nodeIntegration); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, errors.Wrap(err, "node scanner integration").Error()) + return errors.Wrap(errox.InvalidArgs, errors.Wrap(err, "node scanner integration").Error()) } } } @@ -248,10 +249,10 @@ func (s *serviceImpl) testImageIntegration(request *storage.ImageIntegration) er func (s *serviceImpl) testRegistryIntegration(integration *storage.ImageIntegration) error { registry, err := s.registryFactory.CreateRegistry(integration) if err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } if err := registry.Test(); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } return nil } @@ -259,10 +260,10 @@ func (s *serviceImpl) testRegistryIntegration(integration *storage.ImageIntegrat func (s *serviceImpl) testScannerIntegration(integration *storage.ImageIntegration) error { scanner, err := s.scannerFactory.CreateScanner(integration) if err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } if err := scanner.GetScanner().Test(); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } return nil } @@ -270,10 +271,10 @@ func (s *serviceImpl) testScannerIntegration(integration *storage.ImageIntegrati func (s *serviceImpl) testNodeScannerIntegration(integration *storage.NodeIntegration) error { scanner, err := s.nodeEnricher.CreateNodeScanner(integration) if err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } if err := scanner.GetNodeScanner().TestNodeScanner(); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } return nil } @@ -311,20 +312,20 @@ func (s *serviceImpl) reconcileUpdateImageIntegrationRequest(ctx context.Context return nil } if updateRequest.GetConfig() == nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "request is missing image integration config") + return errors.Wrap(errox.InvalidArgs, "request is missing image integration config") } if updateRequest.GetConfig().GetId() == "" { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "id required for stored credential reconciliation") + return errors.Wrap(errox.InvalidArgs, "id required for stored credential reconciliation") } integration, exists, err := s.datastore.GetImageIntegration(ctx, updateRequest.GetConfig().GetId()) if err != nil { return err } if !exists { - return errors.Wrapf(errorhelpers.ErrNotFound, "image integration %s not found", updateRequest.GetConfig().GetId()) + return errors.Wrapf(errox.NotFound, "image integration %s not found", updateRequest.GetConfig().GetId()) } if err := s.reconcileImageIntegrationWithExisting(updateRequest.GetConfig(), integration); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } return nil } diff --git a/central/imageintegration/service/service_impl_test.go b/central/imageintegration/service/service_impl_test.go index ab2f7f1bbbecd..c3e0b8ddc1ccd 100644 --- a/central/imageintegration/service/service_impl_test.go +++ b/central/imageintegration/service/service_impl_test.go @@ -12,7 +12,7 @@ import ( loopMocks "github.com/stackrox/rox/central/reprocessor/mocks" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" nodeMocks "github.com/stackrox/rox/pkg/nodes/enricher/mocks" "github.com/stackrox/rox/pkg/sac" scannerMocks "github.com/stackrox/rox/pkg/scanners/mocks" @@ -176,7 +176,7 @@ func TestValidateIntegration(t *testing.T) { _, err := s.TestUpdatedImageIntegration(testCtx, request) assert.Error(t, err) - assert.EqualError(t, err, errors.Wrap(errorhelpers.ErrInvalidArgs, "the request doesn't have a valid integration config type").Error()) + assert.EqualError(t, err, errors.Wrap(errox.InvalidArgs, "the request doesn't have a valid integration config type").Error()) dockerConfig := &storage.DockerConfig{ Endpoint: "endpoint", diff --git a/central/license/service/service_impl.go b/central/license/service/service_impl.go index b250346a3037c..bf3d78ed9f11b 100644 --- a/central/license/service/service_impl.go +++ b/central/license/service/service_impl.go @@ -10,7 +10,7 @@ import ( "github.com/stackrox/rox/central/role/resources" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/allow" "github.com/stackrox/rox/pkg/grpc/authz/idcheck" @@ -106,7 +106,7 @@ var ( func (s *service) AddLicense(ctx context.Context, req *v1.AddLicenseRequest) (*v1.AddLicenseResponse, error) { if req.GetLicenseKey() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "must provide a non-empty license key") + return nil, errors.Wrap(errox.InvalidArgs, "must provide a non-empty license key") } licenseInfo, err := s.licenseMgr.AddLicenseKey(req.GetLicenseKey(), req.GetActivate()) diff --git a/central/metadata/service/service_impl.go b/central/metadata/service/service_impl.go index f50b27c7b7715..de7b8bb3200e7 100644 --- a/central/metadata/service/service_impl.go +++ b/central/metadata/service/service_impl.go @@ -13,7 +13,7 @@ import ( "github.com/stackrox/rox/pkg/buildinfo" "github.com/stackrox/rox/pkg/centralsensor" "github.com/stackrox/rox/pkg/cryptoutils" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authn" "github.com/stackrox/rox/pkg/grpc/authz/allow" "github.com/stackrox/rox/pkg/mtls" @@ -67,10 +67,10 @@ func (s *serviceImpl) TLSChallenge(ctx context.Context, req *v1.TLSChallengeRequ sensorChallenge := req.GetChallengeToken() sensorChallengeBytes, err := base64.URLEncoding.DecodeString(sensorChallenge) if err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "challenge token must be a valid base64 string: %s", err) + return nil, errors.Wrapf(errox.InvalidArgs, "challenge token must be a valid base64 string: %s", err) } if len(sensorChallengeBytes) != centralsensor.ChallengeTokenLength { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "base64 decoded challenge token must be %d bytes long, got %s", centralsensor.ChallengeTokenLength, sensorChallenge) + return nil, errors.Wrapf(errox.InvalidArgs, "base64 decoded challenge token must be %d bytes long, got %s", centralsensor.ChallengeTokenLength, sensorChallenge) } // Create central challenge token diff --git a/central/mitre/datastore/store.go b/central/mitre/datastore/store.go index cd87463765caa..643aec8ca4deb 100644 --- a/central/mitre/datastore/store.go +++ b/central/mitre/datastore/store.go @@ -5,7 +5,7 @@ import ( "github.com/pkg/errors" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/logging" "github.com/stackrox/rox/pkg/mitre" ) @@ -53,12 +53,12 @@ func (s *mitreAttackStoreImpl) GetAll() []*storage.MitreAttackVector { func (s *mitreAttackStoreImpl) Get(id string) (*storage.MitreAttackVector, error) { if id == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "MITRE ATT&CK tactic ID must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "MITRE ATT&CK tactic ID must be provided") } v := s.mitreAttackVectors[id] if v == nil { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "MITRE ATT&CK vector for tactic %q not found. Please check the tactic ID and retry.", id) + return nil, errors.Wrapf(errox.NotFound, "MITRE ATT&CK vector for tactic %q not found. Please check the tactic ID and retry.", id) } return v, nil } diff --git a/central/namespace/service/service_impl.go b/central/namespace/service/service_impl.go index fadb15333bc79..77f229c0d9569 100644 --- a/central/namespace/service/service_impl.go +++ b/central/namespace/service/service_impl.go @@ -14,7 +14,7 @@ import ( secretDataStore "github.com/stackrox/rox/central/secret/datastore" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -51,7 +51,7 @@ func (s *serviceImpl) GetNamespaces(ctx context.Context, req *v1.GetNamespaceReq rawQuery := req.GetQuery() parsedQuery, err := search.ParseQuery(rawQuery.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } // Fill in pagination. MaxInt32 preserves previous functionality paginated.FillPagination(parsedQuery, rawQuery.GetPagination(), math.MaxInt32) @@ -67,14 +67,14 @@ func (s *serviceImpl) GetNamespaces(ctx context.Context, req *v1.GetNamespaceReq func (s *serviceImpl) GetNamespace(ctx context.Context, req *v1.ResourceByID) (*v1.Namespace, error) { if req.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "ID cannot be empty") + return nil, errors.Wrap(errox.InvalidArgs, "ID cannot be empty") } resolvedNS, found, err := namespace.ResolveByID(ctx, req.GetId(), s.datastore, s.deployments, s.secrets, s.networkPolicies) if err != nil { return nil, errors.Errorf("Failed to retrieve namespace: %v", err) } if !found { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "Namespace '%s' not found", req.GetId()) + return nil, errors.Wrapf(errox.InvalidArgs, "Namespace '%s' not found", req.GetId()) } return resolvedNS, nil } diff --git a/central/networkbaseline/manager/manager_impl.go b/central/networkbaseline/manager/manager_impl.go index d0b8dc8fb37bc..300fb51b34eab 100644 --- a/central/networkbaseline/manager/manager_impl.go +++ b/central/networkbaseline/manager/manager_impl.go @@ -15,6 +15,7 @@ import ( "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/env" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/labels" "github.com/stackrox/rox/pkg/logging" "github.com/stackrox/rox/pkg/networkgraph" @@ -327,7 +328,7 @@ func (m *manager) validatePeers(peers []*v1.NetworkBaselinePeerStatus) error { if len(invalidPeerTypes) > 0 { errorList.AddStringf("invalid types for peers: %v", invalidPeerTypes) } - return errors.Wrap(errorhelpers.ErrInvalidArgs, errorList.String()) + return errors.Wrap(errox.InvalidArgs, errorList.String()) } return nil } @@ -339,7 +340,7 @@ func (m *manager) ProcessBaselineStatusUpdate(ctx context.Context, modifyRequest baseline, found := m.baselinesByDeploymentID[deploymentID] if !found { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "no baseline found for deployment id %q", deploymentID) + return errors.Wrapf(errox.InvalidArgs, "no baseline found for deployment id %q", deploymentID) } if err := m.validatePeers(modifyRequest.GetPeers()); err != nil { return err @@ -507,7 +508,7 @@ type clusterNamespacePair struct { func (m *manager) processBaselineLockUpdate(ctx context.Context, deploymentID string, lockBaseline bool) error { baseline, found := m.baselinesByDeploymentID[deploymentID] if !found { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "no baseline with given deployment ID found") + return errors.Wrap(errox.InvalidArgs, "no baseline with given deployment ID found") } // Permission check before modifying in-memory data structures if ok, err := networkBaselineSAC.WriteAllowed(ctx, sac.ClusterScopeKey(baseline.ClusterID), sac.NamespaceScopeKey(baseline.Namespace)); err != nil { diff --git a/central/networkbaseline/service/service_impl.go b/central/networkbaseline/service/service_impl.go index 1e2dbda6654ca..84485beb02460 100644 --- a/central/networkbaseline/service/service_impl.go +++ b/central/networkbaseline/service/service_impl.go @@ -11,7 +11,6 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" @@ -77,14 +76,14 @@ func (s *serviceImpl) GetNetworkBaseline( request *v1.ResourceByID, ) (*storage.NetworkBaseline, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Network baseline id must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "Network baseline id must be provided") } baseline, found, err := s.datastore.GetNetworkBaseline(ctx, request.GetId()) if err != nil { return nil, err } if !found { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "network baseline with id %q does not exist", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "network baseline with id %q does not exist", request.GetId()) } return baseline, nil diff --git a/central/networkgraph/entity/datastore/datastore_impl.go b/central/networkgraph/entity/datastore/datastore_impl.go index fd68a87999986..3c232ea35a70a 100644 --- a/central/networkgraph/entity/datastore/datastore_impl.go +++ b/central/networkgraph/entity/datastore/datastore_impl.go @@ -11,6 +11,7 @@ import ( "github.com/stackrox/rox/central/sensor/service/connection" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/logging" "github.com/stackrox/rox/pkg/networkgraph" "github.com/stackrox/rox/pkg/networkgraph/externalsrcs" @@ -127,7 +128,7 @@ func (ds *dataStoreImpl) GetEntity(ctx context.Context, id string) (*storage.Net func (ds *dataStoreImpl) GetAllEntitiesForCluster(ctx context.Context, clusterID string) ([]*storage.NetworkEntity, error) { if clusterID == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "cannot get network entities. Cluster ID not specified") + return nil, errors.Wrap(errox.InvalidArgs, "cannot get network entities. Cluster ID not specified") } graphConfig, err := ds.graphConfig.GetNetworkGraphConfig(graphConfigReadCtx) @@ -277,7 +278,7 @@ func (ds *dataStoreImpl) create(ctx context.Context, entity *storage.NetworkEnti return errors.Wrapf(err, "could not determine if network entity %s already exists in DB. SKIPPING", entity.GetInfo().GetExternalSource().GetName()) } else if found { - return errors.Wrapf(errorhelpers.ErrAlreadyExists, + return errors.Wrapf(errox.AlreadyExists, "network %s of entity %s (CIDR=%s) conflicts with network of stored entity %s (CIDR=%s)", network, entity.GetInfo().GetExternalSource().GetName(), entity.GetInfo().GetExternalSource().GetCidr(), @@ -362,7 +363,7 @@ func (ds *dataStoreImpl) DeleteExternalNetworkEntity(ctx context.Context, id str func (ds *dataStoreImpl) DeleteExternalNetworkEntitiesForCluster(ctx context.Context, clusterID string) error { if clusterID == "" { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "external network entities cannot be deleted. Cluster ID not specified") + return errors.Wrap(errox.InvalidArgs, "external network entities cannot be deleted. Cluster ID not specified") } if ok, err := networkGraphSAC.WriteAllowed(ctx, sac.ClusterScopeKey(clusterID)); err != nil { @@ -464,15 +465,15 @@ func validateExternalNetworkEntity(entity *storage.NetworkEntity) error { } if entity.GetInfo().GetType() != storage.NetworkEntityInfo_EXTERNAL_SOURCE { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "only external network graph sources can be created") + return errors.Wrap(errox.InvalidArgs, "only external network graph sources can be created") } if entity.GetInfo().GetExternalSource() == nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "network entity must be specified") + return errors.Wrap(errox.InvalidArgs, "network entity must be specified") } if _, err := networkgraph.ValidateCIDR(entity.GetInfo().GetExternalSource().GetCidr()); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } if entity.GetInfo().GetExternalSource().GetName() == "" { @@ -484,16 +485,16 @@ func validateExternalNetworkEntity(entity *storage.NetworkEntity) error { func parseAndValidateID(id string) (sac.ResourceID, error) { if id == "" { - return sac.ResourceID{}, errors.Wrap(errorhelpers.ErrInvalidArgs, "network entity ID must be specified") + return sac.ResourceID{}, errors.Wrap(errox.InvalidArgs, "network entity ID must be specified") } decodedID, err := sac.ParseResourceID(id) if err != nil { - return sac.ResourceID{}, errors.Wrapf(errorhelpers.ErrInvalidArgs, "failed to parse network entity id %s", id) + return sac.ResourceID{}, errors.Wrapf(errox.InvalidArgs, "failed to parse network entity id %s", id) } if !decodedID.IsValid() || decodedID.NamespaceScoped() { - return sac.ResourceID{}, errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid network entity id %s. Must be cluster-scoped or global-scoped", id) + return sac.ResourceID{}, errors.Wrapf(errox.InvalidArgs, "invalid network entity id %s. Must be cluster-scoped or global-scoped", id) } return decodedID, nil } diff --git a/central/networkgraph/service/service_impl.go b/central/networkgraph/service/service_impl.go index dbae9e8d68313..ae4e58872cc72 100644 --- a/central/networkgraph/service/service_impl.go +++ b/central/networkgraph/service/service_impl.go @@ -19,7 +19,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -89,13 +89,13 @@ func (s *serviceImpl) AuthFuncOverride(ctx context.Context, fullMethodName strin func (s *serviceImpl) GetExternalNetworkEntities(ctx context.Context, request *v1.GetExternalNetworkEntitiesRequest) (*v1.GetExternalNetworkEntitiesResponse, error) { query, err := search.ParseQuery(request.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } query, _ = search.FilterQueryWithMap(query, mappings.OptionsMap) pred, err := netEntityPredFactory.GeneratePredicate(query) if err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "failed to parse query %q: %v", query.String(), err.Error()) + return nil, errors.Wrapf(errox.InvalidArgs, "failed to parse query %q: %v", query.String(), err.Error()) } ret, err := s.entities.GetAllMatchingEntities(ctx, func(entity *storage.NetworkEntity) bool { @@ -118,7 +118,7 @@ func (s *serviceImpl) CreateExternalNetworkEntity(ctx context.Context, request * // An error here implies one of the arguments is invalid. id, err := externalsrcs.NewClusterScopedID(request.GetClusterId(), request.GetEntity().GetCidr()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if err := s.validateCluster(request.GetClusterId()); err != nil { @@ -160,7 +160,7 @@ func (s *serviceImpl) DeleteExternalNetworkEntity(ctx context.Context, request * func (s *serviceImpl) PatchExternalNetworkEntity(ctx context.Context, request *v1.PatchNetworkEntityRequest) (*storage.NetworkEntity, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "network entity ID must be specified") + return nil, errors.Wrap(errox.InvalidArgs, "network entity ID must be specified") } id := request.GetId() @@ -187,7 +187,7 @@ func (s *serviceImpl) getEntityAndValidateMutable(ctx context.Context, id string return nil, err } if !found { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "network entity %s not found", id) + return nil, errors.Wrapf(errox.NotFound, "network entity %s not found", id) } if entity.GetInfo().GetExternalSource().GetDefault() { return nil, status.Error(codes.PermissionDenied, "StackRox-generated network entities are immutable") @@ -207,7 +207,7 @@ func (s *serviceImpl) GetNetworkGraphConfig(ctx context.Context, _ *v1.Empty) (* // PutNetworkGraphConfig updates Central's network graph config func (s *serviceImpl) PutNetworkGraphConfig(ctx context.Context, req *v1.PutNetworkGraphConfigRequest) (*storage.NetworkGraphConfig, error) { if req.GetConfig() == nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "network graph config must be specified") + return nil, errors.Wrap(errox.InvalidArgs, "network graph config must be specified") } if err := s.graphConfig.UpdateNetworkGraphConfig(ctx, req.GetConfig()); err != nil { @@ -222,7 +222,7 @@ func (s *serviceImpl) getFlowStore(ctx context.Context, clusterID string) (netwo return nil, errors.Errorf("could not obtain flows for cluster %s: %v", clusterID, err) } if flowStore == nil { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "no flows found for cluster %s", clusterID) + return nil, errors.Wrapf(errox.NotFound, "no flows found for cluster %s", clusterID) } return flowStore, nil } @@ -237,7 +237,7 @@ func (s *serviceImpl) validateCluster(clusterID string) error { if exists, err := s.clusters.Exists(clusterReadCtx, clusterID); err != nil { return err } else if !exists { - return errors.Wrapf(errorhelpers.ErrNotFound, "cluster %s not found. It may have been deleted", clusterID) + return errors.Wrapf(errox.NotFound, "cluster %s not found. It may have been deleted", clusterID) } return nil } @@ -248,7 +248,7 @@ func (s *serviceImpl) GetNetworkGraph(ctx context.Context, request *v1.NetworkGr func (s *serviceImpl) getNetworkGraph(ctx context.Context, request *v1.NetworkGraphRequest, withListenPorts bool) (*v1.NetworkGraph, error) { if request.GetClusterId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "cluster ID must be specified") + return nil, errors.Wrap(errox.InvalidArgs, "cluster ID must be specified") } requestClone := request.Clone() diff --git a/central/networkpolicies/service/service_impl.go b/central/networkpolicies/service/service_impl.go index a200112d07cdb..bd9043e186dd9 100644 --- a/central/networkpolicies/service/service_impl.go +++ b/central/networkpolicies/service/service_impl.go @@ -132,7 +132,7 @@ func (s *serviceImpl) GetNetworkPolicy(ctx context.Context, request *v1.Resource return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "network policy with id '%s' does not exist", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "network policy with id '%s' does not exist", request.GetId()) } populateYAML(networkPolicy) return networkPolicy, nil @@ -303,13 +303,13 @@ func (s *serviceImpl) SimulateNetworkGraph(ctx context.Context, request *v1.Simu func (s *serviceImpl) SendNetworkPolicyYAML(ctx context.Context, request *v1.SendNetworkPolicyYamlRequest) (*v1.Empty, error) { if request.GetClusterId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Cluster ID must be specified") + return nil, errors.Wrap(errox.InvalidArgs, "Cluster ID must be specified") } if len(request.GetNotifierIds()) == 0 { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Notifier IDs must be specified") + return nil, errors.Wrap(errox.InvalidArgs, "Notifier IDs must be specified") } if request.GetModification().GetApplyYaml() == "" && len(request.GetModification().GetToDelete()) == 0 { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Modification must have contents") + return nil, errors.Wrap(errox.InvalidArgs, "Modification must have contents") } clusterName, exists, err := s.clusterStore.GetClusterName(ctx, request.GetClusterId()) @@ -317,7 +317,7 @@ func (s *serviceImpl) SendNetworkPolicyYAML(ctx context.Context, request *v1.Sen return nil, errors.Errorf("failed to retrieve cluster: %s", err.Error()) } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "Cluster '%s' not found", request.GetClusterId()) + return nil, errors.Wrapf(errox.NotFound, "Cluster '%s' not found", request.GetClusterId()) } errorList := errorhelpers.NewErrorList("unable to use all requested notifiers") @@ -363,7 +363,7 @@ func (s *serviceImpl) GenerateNetworkPolicies(ctx context.Context, req *v1.Gener } if req.GetClusterId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Cluster ID must be specified") + return nil, errors.Wrap(errox.InvalidArgs, "Cluster ID must be specified") } generated, toDelete, err := s.policyGenerator.Generate(ctx, req) @@ -392,7 +392,7 @@ func (s *serviceImpl) GetUndoModification(ctx context.Context, req *v1.GetUndoMo return nil, errors.Errorf("could not query undo store: %v", err) } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "no undo record stored for cluster %q", req.GetClusterId()) + return nil, errors.Wrapf(errox.NotFound, "no undo record stored for cluster %q", req.GetClusterId()) } return &v1.GetUndoModificationResponse{ UndoRecord: undoRecord, @@ -421,7 +421,7 @@ func (s *serviceImpl) GetBaselineGeneratedNetworkPolicyForDeployment(ctx context // Currently we don't look at request.GetDeleteExisting. We try to delete the existing baseline generated // policy no matter what if request.GetDeploymentId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Cluster ID must be specified") + return nil, errors.Wrap(errox.InvalidArgs, "Cluster ID must be specified") } generated, toDelete, err := s.policyGenerator.GenerateFromBaselineForDeployment(ctx, request) @@ -479,7 +479,7 @@ func (s *serviceImpl) getRelevantClusterObjectsForDeployment(ctx context.Context if err != nil { return nil, nil, nil, err } else if !found { - return nil, nil, nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "specified deployment not found") + return nil, nil, nil, errors.Wrap(errox.InvalidArgs, "specified deployment not found") } networkTree, err := s.getNetworkTree(deployment.GetClusterId()) @@ -621,7 +621,7 @@ func (s *serviceImpl) applyModificationAndGetUndoRecord( modification *storage.NetworkPolicyModification, ) (*storage.NetworkPolicyApplicationUndoRecord, error) { if strings.TrimSpace(modification.GetApplyYaml()) == "" && len(modification.GetToDelete()) == 0 { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Modification must have contents") + return nil, errors.Wrap(errox.InvalidArgs, "Modification must have contents") } // Check that: @@ -673,7 +673,7 @@ func (s *serviceImpl) ApplyNetworkPolicyYamlForDeployment(ctx context.Context, r if err != nil { return nil, err } else if !found { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "requested deployment %q not found", request.GetDeploymentId()) + return nil, errors.Wrapf(errox.NotFound, "requested deployment %q not found", request.GetDeploymentId()) } undoRecord, err := s.applyModificationAndGetUndoRecord(ctx, deployment.GetClusterId(), request.GetModification()) @@ -702,14 +702,14 @@ func (s *serviceImpl) GetUndoModificationForDeployment(ctx context.Context, requ if err != nil { return nil, err } else if !found { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "deployment with ID %q not found", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "deployment with ID %q not found", request.GetId()) } undoRecord, found, err := s.networkPolicies.GetUndoDeploymentRecord(ctx, request.GetId()) if err != nil { return nil, err } else if !found { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "no undo record stored for deployment %q", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "no undo record stored for deployment %q", request.GetId()) } return &v1.GetUndoModificationForDeploymentResponse{ UndoRecord: undoRecord.GetUndoRecord(), @@ -1126,14 +1126,14 @@ func validateNoPolicyDiff(applyPolicy *storage.NetworkPolicy, currPolicy *storag func (s *serviceImpl) clusterExists(ctx context.Context, clusterID string) error { if clusterID == "" { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "cluster ID must be specified") + return errors.Wrap(errox.InvalidArgs, "cluster ID must be specified") } exists, err := s.clusterStore.Exists(ctx, clusterID) if err != nil { return err } if !exists { - return errors.Wrapf(errorhelpers.ErrNotFound, "cluster with ID %q doesn't exist", clusterID) + return errors.Wrapf(errox.NotFound, "cluster with ID %q doesn't exist", clusterID) } return nil } diff --git a/central/node/service/service_impl.go b/central/node/service/service_impl.go index e1fd5db552b22..1ca750f6a26b8 100644 --- a/central/node/service/service_impl.go +++ b/central/node/service/service_impl.go @@ -10,7 +10,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" pkgGRPC "github.com/stackrox/rox/pkg/grpc" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" @@ -78,7 +78,7 @@ func (s *nodeServiceImpl) GetNode(ctx context.Context, req *v1.GetNodeRequest) ( } if node == nil { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "node %q in cluster %q does not exist", req.GetNodeId(), req.GetClusterId()) + return nil, errors.Wrapf(errox.NotFound, "node %q in cluster %q does not exist", req.GetNodeId(), req.GetClusterId()) } return node, nil diff --git a/central/notifier/service/service_impl.go b/central/notifier/service/service_impl.go index e6c31c354b259..1242ad8d9cbc3 100644 --- a/central/notifier/service/service_impl.go +++ b/central/notifier/service/service_impl.go @@ -17,6 +17,7 @@ import ( "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/endpoints" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -74,14 +75,14 @@ func (s *serviceImpl) AuthFuncOverride(ctx context.Context, fullMethodName strin // GetNotifier retrieves all registries that matches the request filters func (s *serviceImpl) GetNotifier(ctx context.Context, request *v1.ResourceByID) (*storage.Notifier, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "notifier id must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "notifier id must be provided") } notifier, exists, err := s.storage.GetNotifier(ctx, request.GetId()) if err != nil { return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "notifier %v not found", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "notifier %v not found", request.GetId()) } secrets.ScrubSecretsFromStructWithReplacement(notifier, secrets.ScrubReplacementStr) return notifier, nil @@ -127,14 +128,14 @@ func (s *serviceImpl) PutNotifier(ctx context.Context, notifier *storage.Notifie // UpdateNotifier updates a notifier configuration func (s *serviceImpl) UpdateNotifier(ctx context.Context, request *v1.UpdateNotifierRequest) (*v1.Empty, error) { if err := validateNotifier(request.GetNotifier()); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if err := s.reconcileUpdateNotifierRequest(ctx, request); err != nil { return nil, err } notifierCreator, ok := notifiers.Registry[request.GetNotifier().GetType()] if !ok { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "notifier type %v is not a valid notifier type", request.GetNotifier().GetType()) + return nil, errors.Wrapf(errox.InvalidArgs, "notifier type %v is not a valid notifier type", request.GetNotifier().GetType()) } upgradeNotifierConfig(request.GetNotifier()) notifier, err := notifierCreator(request.GetNotifier()) @@ -151,15 +152,15 @@ func (s *serviceImpl) UpdateNotifier(ctx context.Context, request *v1.UpdateNoti // PostNotifier inserts a new registry into the system if it doesn't already exist func (s *serviceImpl) PostNotifier(ctx context.Context, request *storage.Notifier) (*storage.Notifier, error) { if err := validateNotifier(request); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if request.GetId() != "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "id field should be empty when posting a new notifier") + return nil, errors.Wrap(errox.InvalidArgs, "id field should be empty when posting a new notifier") } upgradeNotifierConfig(request) notifier, err := notifiers.CreateNotifier(request) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } id, err := s.storage.AddNotifier(ctx, request) if err != nil { @@ -182,14 +183,14 @@ func (s *serviceImpl) TestNotifier(ctx context.Context, notifier *storage.Notifi // TestUpdatedNotifier tests to see if the config is setup properly func (s *serviceImpl) TestUpdatedNotifier(ctx context.Context, request *v1.UpdateNotifierRequest) (*v1.Empty, error) { if err := validateNotifier(request.GetNotifier()); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if err := s.reconcileUpdateNotifierRequest(ctx, request); err != nil { return nil, err } notifier, err := notifiers.CreateNotifier(request.GetNotifier()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } defer func() { if err := notifier.Close(ctx); err != nil { @@ -198,7 +199,7 @@ func (s *serviceImpl) TestUpdatedNotifier(ctx context.Context, request *v1.Updat }() if err := notifier.Test(ctx); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } return &v1.Empty{}, nil } @@ -206,7 +207,7 @@ func (s *serviceImpl) TestUpdatedNotifier(ctx context.Context, request *v1.Updat // DeleteNotifier deletes a notifier from the system func (s *serviceImpl) DeleteNotifier(ctx context.Context, request *v1.DeleteNotifierRequest) (*v1.Empty, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "notifier id must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "notifier id must be provided") } n, err := s.GetNotifier(ctx, &v1.ResourceByID{Id: request.GetId()}) @@ -256,20 +257,20 @@ func (s *serviceImpl) reconcileUpdateNotifierRequest(ctx context.Context, update return nil } if updateRequest.GetNotifier() == nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "request is missing notifier config") + return errors.Wrap(errox.InvalidArgs, "request is missing notifier config") } if updateRequest.GetNotifier().GetId() == "" { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "id required for stored credential reconciliation") + return errors.Wrap(errox.InvalidArgs, "id required for stored credential reconciliation") } existingNotifierConfig, exists, err := s.storage.GetNotifier(ctx, updateRequest.GetNotifier().GetId()) if err != nil { return err } if !exists { - return errors.Wrapf(errorhelpers.ErrNotFound, "notifier integration %s not found", updateRequest.GetNotifier().GetId()) + return errors.Wrapf(errox.NotFound, "notifier integration %s not found", updateRequest.GetNotifier().GetId()) } if err := reconcileNotifierConfigWithExisting(updateRequest.GetNotifier(), existingNotifierConfig); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } return nil } diff --git a/central/notifier/service/service_impl_test.go b/central/notifier/service/service_impl_test.go index e5ef5431f54ce..cba1c196ce8e8 100644 --- a/central/notifier/service/service_impl_test.go +++ b/central/notifier/service/service_impl_test.go @@ -11,7 +11,7 @@ import ( _ "github.com/stackrox/rox/central/notifiers/all" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" reporterMocks "github.com/stackrox/rox/pkg/integrationhealth/mocks" "github.com/stackrox/rox/pkg/sac" "github.com/stackrox/rox/pkg/secrets" @@ -97,7 +97,7 @@ func (s *notifierServiceTestSuite) TestUpdateNotifier() { updateReq := createUpdateNotifierRequest() updateReq.GetNotifier().GetGeneric().Password = "updatePassword" _, err = s.getSvc().UpdateNotifier(s.ctx, updateReq) - s.EqualError(err, errors.Wrap(errorhelpers.ErrInvalidArgs, "non-zero or unmasked credential field 'Notifier.Notifier_Generic.Generic.Password'").Error()) + s.EqualError(err, errors.Wrap(errox.InvalidArgs, "non-zero or unmasked credential field 'Notifier.Notifier_Generic.Generic.Password'").Error()) updateReq.UpdatePassword = true _, err = s.getSvc().UpdateNotifier(s.ctx, updateReq) @@ -112,7 +112,7 @@ func (s *notifierServiceTestSuite) TestUpdateNotifier() { secrets.ScrubSecretsFromStructWithReplacement(updateDependentReq, secrets.ScrubReplacementStr) updateDependentReq.UpdatePassword = false _, err = s.getSvc().UpdateNotifier(s.ctx, updateDependentReq) - s.EqualError(err, errors.Wrap(errorhelpers.ErrInvalidArgs, "credentials required to update field 'Notifier.Notifier_Generic.Generic.Endpoint'").Error()) + s.EqualError(err, errors.Wrap(errox.InvalidArgs, "credentials required to update field 'Notifier.Notifier_Generic.Generic.Endpoint'").Error()) updateBasic := createUpdateNotifierRequest() updateBasic.GetNotifier().GetGeneric().AuditLoggingEnabled = true diff --git a/central/pod/service/service_impl.go b/central/pod/service/service_impl.go index b3fb19b0c9b6d..ac4ad2bbb7160 100644 --- a/central/pod/service/service_impl.go +++ b/central/pod/service/service_impl.go @@ -9,7 +9,7 @@ import ( "github.com/stackrox/rox/central/role/resources" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -55,7 +55,7 @@ func (s *serviceImpl) GetPods(ctx context.Context, request *v1.RawQuery) (*v1.Po // Fill in Query. parsedQuery, err := search.ParseQuery(request.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } // Fill in pagination. diff --git a/central/policy/service/service_impl.go b/central/policy/service/service_impl.go index 2987f7c795713..57a141a29217c 100644 --- a/central/policy/service/service_impl.go +++ b/central/policy/service/service_impl.go @@ -136,14 +136,14 @@ func (s *serviceImpl) GetPolicy(ctx context.Context, request *v1.ResourceByID) ( func (s *serviceImpl) getPolicy(ctx context.Context, id string) (*storage.Policy, error) { if id == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Policy ID must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "Policy ID must be provided") } policy, exists, err := s.policies.GetPolicy(ctx, id) if err != nil { return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "policy with ID '%s' does not exist", id) + return nil, errors.Wrapf(errox.NotFound, "policy with ID '%s' does not exist", id) } if len(policy.GetCategories()) == 0 { policy.Categories = []string{uncategorizedCategory} @@ -182,7 +182,7 @@ func (s *serviceImpl) ListPolicies(ctx context.Context, request *v1.RawQuery) (* } else { parsedQuery, err := search.ParseQuery(request.GetQuery()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } policies, err := s.policies.SearchRawPolicies(ctx, parsedQuery) if err != nil { @@ -196,11 +196,11 @@ func (s *serviceImpl) ListPolicies(ctx context.Context, request *v1.RawQuery) (* func (s *serviceImpl) convertAndValidate(ctx context.Context, p *storage.Policy, options ...booleanpolicy.ValidateOption) error { if err := policyversion.EnsureConvertedToLatest(p); err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "Could not ensure policy format: %v", err.Error()) + return errors.Wrapf(errox.InvalidArgs, "Could not ensure policy format: %v", err.Error()) } if err := s.validator.validate(ctx, p, options...); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } return nil } @@ -234,7 +234,7 @@ func (s *serviceImpl) addOrUpdatePolicy(ctx context.Context, request *storage.Po func ensureIDEmpty(p *storage.Policy) error { if p.GetId() != "" { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Id field should be empty when posting a new policy") + return errors.Wrap(errox.InvalidArgs, "Id field should be empty when posting a new policy") } return nil } @@ -297,7 +297,7 @@ func (s *serviceImpl) PatchPolicy(ctx context.Context, request *v1.PatchPolicyRe return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "Policy with id '%s' not found", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "Policy with id '%s' not found", request.GetId()) } if request.SetDisabled != nil { policy.Disabled = request.GetDisabled() @@ -309,7 +309,7 @@ func (s *serviceImpl) PatchPolicy(ctx context.Context, request *v1.PatchPolicyRe // DeletePolicy deletes an policy from the system. func (s *serviceImpl) DeletePolicy(ctx context.Context, request *v1.ResourceByID) (*v1.Empty, error) { if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "A policy id must be specified to delete a Policy") + return nil, errors.Wrap(errox.InvalidArgs, "A policy id must be specified to delete a Policy") } if err := s.policies.RemovePolicy(ctx, request.GetId()); err != nil { @@ -387,7 +387,7 @@ func (s *serviceImpl) QueryDryRunJobStatus(ctx context.Context, jobid *v1.JobId) func (s *serviceImpl) CancelDryRunJob(ctx context.Context, jobid *v1.JobId) (*v1.Empty, error) { metadata, _, _, err := s.dryRunPolicyJobManager.GetTaskStatusAndMetadata(jobid.JobId) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if err := checkIdentityFromMetadata(ctx, metadata); err != nil { @@ -395,7 +395,7 @@ func (s *serviceImpl) CancelDryRunJob(ctx context.Context, jobid *v1.JobId) (*v1 } if err := s.dryRunPolicyJobManager.CancelTask(jobid.JobId); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } return &v1.Empty{}, nil @@ -412,7 +412,7 @@ func (s *serviceImpl) predicateBasedDryRunPolicy(ctx context.Context, cancelCtx compiledPolicy, err := detection.CompilePolicy(request) if err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid policy: %v", err) + return nil, errors.Wrapf(errox.InvalidArgs, "invalid policy: %v", err) } deploymentIds, err := s.deployments.GetDeploymentIDs(ctx) @@ -550,7 +550,7 @@ func (s *serviceImpl) DeletePolicyCategory(ctx context.Context, request *v1.Dele } if !categorySet.Contains(request.GetCategory()) { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "Policy Category %s does not exist", request.GetCategory()) + return nil, errors.Wrapf(errox.NotFound, "Policy Category %s does not exist", request.GetCategory()) } if err := s.policies.DeletePolicyCategory(ctx, request); err != nil { @@ -601,7 +601,7 @@ func (s *serviceImpl) removeActivePolicy(id string) error { func (s *serviceImpl) EnableDisablePolicyNotification(ctx context.Context, request *v1.EnableDisablePolicyNotificationRequest) (*v1.Empty, error) { if request.GetPolicyId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Policy ID must be specified") + return nil, errors.Wrap(errox.InvalidArgs, "Policy ID must be specified") } var err error if request.GetDisable() { @@ -618,7 +618,7 @@ func (s *serviceImpl) EnableDisablePolicyNotification(ctx context.Context, reque func (s *serviceImpl) enablePolicyNotification(ctx context.Context, policyID string, notifierIDs []string) error { if len(notifierIDs) == 0 { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Notifier IDs must be specified") + return errors.Wrap(errox.InvalidArgs, "Notifier IDs must be specified") } policy, exists, err := s.policies.GetPolicy(ctx, policyID) @@ -626,7 +626,7 @@ func (s *serviceImpl) enablePolicyNotification(ctx context.Context, policyID str return errors.Errorf("failed to retrieve policy: %v", err) } if !exists { - return errors.Wrapf(errorhelpers.ErrNotFound, "Policy %q not found", policyID) + return errors.Wrapf(errox.NotFound, "Policy %q not found", policyID) } notifierSet := set.NewStringSet(policy.Notifiers...) errorList := errorhelpers.NewErrorList("unable to use all requested notifiers") @@ -675,7 +675,7 @@ func (s *serviceImpl) disablePolicyNotification(ctx context.Context, policyID st return errors.Errorf("failed to retrieve policy: %v", err) } if !exists { - return errors.Wrapf(errorhelpers.ErrNotFound, "Policy %q not found", policyID) + return errors.Wrapf(errox.NotFound, "Policy %q not found", policyID) } notifierSet := set.NewStringSet(policy.Notifiers...) if notifierSet.Cardinality() == 0 { @@ -714,7 +714,7 @@ func checkIdentityFromMetadata(ctx context.Context, metadata map[string]interfac return err } if identityUID != id.UID() { - return errorhelpers.ErrNotAuthorized + return errox.NotAuthorized } return nil diff --git a/central/policy/store/store_impl.go b/central/policy/store/store_impl.go index 357263d98e813..3e6535891114e 100644 --- a/central/policy/store/store_impl.go +++ b/central/policy/store/store_impl.go @@ -14,6 +14,7 @@ import ( "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/dberrors" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" ops "github.com/stackrox/rox/pkg/metrics" "github.com/stackrox/rox/pkg/protoconv" "github.com/stackrox/rox/pkg/secondarykey" @@ -236,7 +237,7 @@ func (s *storeImpl) UpdatePolicy(policy *storage.Policy) error { // If the update is changing the name, check if the name has already been taken val, ok := secondarykey.GetCurrentUniqueKey(tx, policyBucket, policy.GetId()) if !ok { - return errorhelpers.ErrNotFound + return errox.NotFound } if val != policy.GetName() { if err := secondarykey.UpdateUniqueKey(tx, policyBucket, policy.GetId(), policy.GetName()); err != nil { diff --git a/central/processbaseline/service/service_impl.go b/central/processbaseline/service/service_impl.go index 93308e7082913..6b96ab1fe393f 100644 --- a/central/processbaseline/service/service_impl.go +++ b/central/processbaseline/service/service_impl.go @@ -13,7 +13,7 @@ import ( "github.com/stackrox/rox/generated/internalapi/central" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -84,14 +84,14 @@ func validateKeyNotEmpty(key *storage.ProcessBaselineKey) error { func (s *serviceImpl) GetProcessBaseline(ctx context.Context, request *v1.GetProcessBaselineRequest) (*storage.ProcessBaseline, error) { if err := validateKeyNotEmpty(request.GetKey()); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } baseline, exists, err := s.dataStore.GetProcessBaseline(ctx, request.GetKey()) if err != nil { return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "No process baseline with key %+v found", request.GetKey()) + return nil, errors.Wrapf(errox.NotFound, "No process baseline with key %+v found", request.GetKey()) } return baseline, nil } @@ -167,12 +167,12 @@ func (s *serviceImpl) LockProcessBaselines(ctx context.Context, request *v1.Lock func (s *serviceImpl) DeleteProcessBaselines(ctx context.Context, request *v1.DeleteProcessBaselinesRequest) (*v1.DeleteProcessBaselinesResponse, error) { if request.GetQuery() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "query string must be nonempty") + return nil, errors.Wrap(errox.InvalidArgs, "query string must be nonempty") } q, err := search.ParseQuery(request.GetQuery()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } results, err := s.dataStore.Search(ctx, q) diff --git a/central/processindicator/service/service_impl.go b/central/processindicator/service/service_impl.go index 94c2cea5a90db..d3b255e8e93e5 100644 --- a/central/processindicator/service/service_impl.go +++ b/central/processindicator/service/service_impl.go @@ -14,7 +14,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -67,7 +67,7 @@ func (s *serviceImpl) GetProcessesByDeployment(ctx context.Context, req *v1.GetP return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "deployment with id '%s' does not exist", req.GetDeploymentId()) + return nil, errors.Wrapf(errox.NotFound, "deployment with id '%s' does not exist", req.GetDeploymentId()) } indicators, err := s.processIndicators.SearchRawProcessIndicators(ctx, search.NewQueryBuilder(). @@ -111,7 +111,7 @@ func (s *serviceImpl) getElementSet(ctx context.Context, deploymentID string, co return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "deployment with id '%s' does not exist", deploymentID) + return nil, errors.Wrapf(errox.NotFound, "deployment with id '%s' does not exist", deploymentID) } key := &storage.ProcessBaselineKey{ diff --git a/central/rbac/service/list_subjects.go b/central/rbac/service/list_subjects.go index e3f8329803ed0..fe07a13e96e60 100644 --- a/central/rbac/service/list_subjects.go +++ b/central/rbac/service/list_subjects.go @@ -9,7 +9,7 @@ import ( "github.com/stackrox/rox/central/rbac/service/mapping" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/k8srbac" "github.com/stackrox/rox/pkg/search" "github.com/stackrox/rox/pkg/search/predicate" @@ -64,7 +64,7 @@ func getFilteredSubjectsByRoleBinding(rawQuery *v1.RawQuery, bindings []*storage var parsed *v1.Query parsed, err := search.ParseQuery(subjectQuery.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } return GetFilteredSubjects(parsed, subjectsToFilter) } diff --git a/central/rbac/service/service_impl.go b/central/rbac/service/service_impl.go index 343c70852cb88..07916a8f58d07 100644 --- a/central/rbac/service/service_impl.go +++ b/central/rbac/service/service_impl.go @@ -11,7 +11,7 @@ import ( "github.com/stackrox/rox/central/role/resources" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -64,7 +64,7 @@ func (s *serviceImpl) GetRole(ctx context.Context, request *v1.ResourceByID) (*v return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "k8s role with id '%q' does not exist", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "k8s role with id '%q' does not exist", request.GetId()) } return &v1.GetRoleResponse{Role: role}, nil @@ -76,7 +76,7 @@ func (s *serviceImpl) ListRoles(ctx context.Context, rawQuery *v1.RawQuery) (*v1 // roles that can get pods are returned, not roles that can get anything, and can do any operation on Pods. q, err := search.ParseQuery(rawQuery.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } roles, err := s.roles.SearchRawRoles(ctx, q) @@ -94,7 +94,7 @@ func (s *serviceImpl) GetRoleBinding(ctx context.Context, request *v1.ResourceBy return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "k8s role binding with id '%q' does not exist", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "k8s role binding with id '%q' does not exist", request.GetId()) } return &v1.GetRoleBindingResponse{Binding: binding}, nil @@ -104,7 +104,7 @@ func (s *serviceImpl) GetRoleBinding(ctx context.Context, request *v1.ResourceBy func (s *serviceImpl) ListRoleBindings(ctx context.Context, rawQuery *v1.RawQuery) (*v1.ListRoleBindingsResponse, error) { q, err := search.ParseQuery(rawQuery.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } bindings, err := s.bindings.SearchRawRoleBindings(ctx, q) if err != nil { diff --git a/central/reportconfigurations/service/service_impl.go b/central/reportconfigurations/service/service_impl.go index b9da056142ef1..a8c0b12813bbc 100644 --- a/central/reportconfigurations/service/service_impl.go +++ b/central/reportconfigurations/service/service_impl.go @@ -14,7 +14,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -56,7 +56,7 @@ func (s *serviceImpl) GetReportConfigurations(ctx context.Context, query *v1.Raw // Fill in Query. parsedQuery, err := search.ParseQuery(query.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } // Fill in pagination. @@ -75,7 +75,7 @@ func (s *serviceImpl) GetReportConfiguration(ctx context.Context, id *v1.Resourc return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "report configuration with id '%s' does not exist", id) + return nil, errors.Wrapf(errox.NotFound, "report configuration with id '%s' does not exist", id) } return &v1.GetReportConfigurationResponse{ ReportConfig: reportConfig, @@ -118,7 +118,7 @@ func (s *serviceImpl) UpdateReportConfiguration(ctx context.Context, request *v1 func (s *serviceImpl) DeleteReportConfiguration(ctx context.Context, id *v1.ResourceByID) (*v1.Empty, error) { if id.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Report configuration id is required for deletion") + return nil, errors.Wrap(errox.InvalidArgs, "Report configuration id is required for deletion") } if err := s.reportConfigStore.RemoveReportConfiguration(ctx, id.GetId()); err != nil { return &v1.Empty{}, err @@ -129,7 +129,7 @@ func (s *serviceImpl) DeleteReportConfiguration(ctx context.Context, id *v1.Reso func (s *serviceImpl) CountReportConfigurations(ctx context.Context, request *v1.RawQuery) (*v1.CountReportConfigurationsResponse, error) { parsedQuery, err := search.ParseQuery(request.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } numReportConfigs, err := s.reportConfigStore.Count(ctx, parsedQuery) @@ -153,11 +153,11 @@ func (*serviceImpl) AuthFuncOverride(ctx context.Context, fullMethodName string) func (s *serviceImpl) validateReportConfiguration(ctx context.Context, config *storage.ReportConfiguration) error { if config.GetName() == "" { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Report configuration name empty") + return errors.Wrap(errox.InvalidArgs, "Report configuration name empty") } if config.GetSchedule() == nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Report configuration must have a schedule") + return errors.Wrap(errox.InvalidArgs, "Report configuration must have a schedule") } schedule := config.GetSchedule() @@ -165,53 +165,53 @@ func (s *serviceImpl) validateReportConfiguration(ctx context.Context, config *s switch schedule.GetIntervalType() { case storage.Schedule_UNSET: case storage.Schedule_DAILY: - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Report configuration must have a valid schedule type") + return errors.Wrap(errox.InvalidArgs, "Report configuration must have a valid schedule type") case storage.Schedule_WEEKLY: if schedule.GetDaysOfWeek() == nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Report configuration must specify days of week for the schedule") + return errors.Wrap(errox.InvalidArgs, "Report configuration must specify days of week for the schedule") } for _, day := range schedule.GetDaysOfWeek().GetDays() { if day < 0 || day > 6 { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Invalid schedule: Days of the week can be Sunday (0) - Saturday(6)") + return errors.Wrap(errox.InvalidArgs, "Invalid schedule: Days of the week can be Sunday (0) - Saturday(6)") } } case storage.Schedule_MONTHLY: if schedule.GetDaysOfMonth() == nil || schedule.GetDaysOfMonth().GetDays() == nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Report configuration must specify days of the month for the schedule") + return errors.Wrap(errox.InvalidArgs, "Report configuration must specify days of the month for the schedule") } for _, day := range schedule.GetDaysOfMonth().GetDays() { if day != 1 && day != 15 { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Reports can be sent out only 1st or 15th of the month") + return errors.Wrap(errox.InvalidArgs, "Reports can be sent out only 1st or 15th of the month") } } } if config.GetEmailConfig() == nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Report configuration must specify an email notifier configuration") + return errors.Wrap(errox.InvalidArgs, "Report configuration must specify an email notifier configuration") } if config.GetEmailConfig().GetNotifierId() == "" { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Report configuration must specify a valid email notifier") + return errors.Wrap(errox.InvalidArgs, "Report configuration must specify a valid email notifier") } if len(config.GetEmailConfig().GetMailingLists()) == 0 { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "Report configuration must specify one more recipients to send the report to") + return errors.Wrap(errox.InvalidArgs, "Report configuration must specify one more recipients to send the report to") } for _, addr := range config.GetEmailConfig().GetMailingLists() { if _, err := mail.ParseAddress(addr); err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "Invalid mailing list address: %s", addr) + return errors.Wrapf(errox.InvalidArgs, "Invalid mailing list address: %s", addr) } } _, found, err := s.accessScopeStore.GetAccessScope(ctx, config.GetScopeId()) if !found || err != nil { - return errors.Wrapf(errorhelpers.ErrNotFound, "Access scope %s not found. Error: %s", config.GetScopeId(), err) + return errors.Wrapf(errox.NotFound, "Access scope %s not found. Error: %s", config.GetScopeId(), err) } _, found, err = s.notifierStore.GetNotifier(ctx, config.GetEmailConfig().GetNotifierId()) if err != nil { - return errors.Wrapf(errorhelpers.ErrNotFound, "Failed to fetch notifier %s with error %s", config.GetEmailConfig().GetNotifierId(), err) + return errors.Wrapf(errox.NotFound, "Failed to fetch notifier %s with error %s", config.GetEmailConfig().GetNotifierId(), err) } if !found { - return errors.Wrapf(errorhelpers.ErrNotFound, "Notifier %s not found", config.GetEmailConfig().GetNotifierId()) + return errors.Wrapf(errox.NotFound, "Notifier %s not found", config.GetEmailConfig().GetNotifierId()) } return nil diff --git a/central/role/datastore/datastore_impl.go b/central/role/datastore/datastore_impl.go index d59e4466674d2..861b3e6e43a63 100644 --- a/central/role/datastore/datastore_impl.go +++ b/central/role/datastore/datastore_impl.go @@ -9,7 +9,7 @@ import ( rocksDBStore "github.com/stackrox/rox/central/role/store" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/logging" "github.com/stackrox/rox/pkg/sac" "github.com/stackrox/rox/pkg/sync" @@ -63,7 +63,7 @@ func (ds *dataStoreImpl) AddRole(ctx context.Context, role *storage.Role) error return err } if err := rolePkg.ValidateRole(role); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } if err := verifyNotDefaultRole(role.GetName()); err != nil { return err @@ -89,7 +89,7 @@ func (ds *dataStoreImpl) UpdateRole(ctx context.Context, role *storage.Role) err return err } if err := rolePkg.ValidateRole(role); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } if err := verifyNotDefaultRole(role.GetName()); err != nil { return err @@ -159,7 +159,7 @@ func (ds *dataStoreImpl) AddPermissionSet(ctx context.Context, permissionSet *st return err } if err := rolePkg.ValidatePermissionSet(permissionSet); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } if err := verifyNotDefaultPermissionSet(permissionSet.GetName()); err != nil { return err @@ -187,7 +187,7 @@ func (ds *dataStoreImpl) UpdatePermissionSet(ctx context.Context, permissionSet return err } if err := rolePkg.ValidatePermissionSet(permissionSet); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } if err := verifyNotDefaultPermissionSet(permissionSet.GetName()); err != nil { return err @@ -223,7 +223,7 @@ func (ds *dataStoreImpl) RemovePermissionSet(ctx context.Context, id string) err return err } if !found { - return errors.Wrapf(errorhelpers.ErrNotFound, "id = %s", id) + return errors.Wrapf(errox.NotFound, "id = %s", id) } if err := verifyNotDefaultPermissionSet(permissionSet.GetName()); err != nil { return err @@ -236,7 +236,7 @@ func (ds *dataStoreImpl) RemovePermissionSet(ctx context.Context, id string) err } for _, role := range roles { if role.GetPermissionSetId() == id { - return errors.Wrapf(errorhelpers.ErrReferencedByAnotherObject, "cannot delete permission set in use by role %q", role.GetName()) + return errors.Wrapf(errox.ReferencedByAnotherObject, "cannot delete permission set in use by role %q", role.GetName()) } } @@ -282,7 +282,7 @@ func (ds *dataStoreImpl) AddAccessScope(ctx context.Context, scope *storage.Simp return err } if err := rolePkg.ValidateSimpleAccessScope(scope); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } if err := verifyNotDefaultAccessScope(scope); err != nil { return err @@ -310,7 +310,7 @@ func (ds *dataStoreImpl) UpdateAccessScope(ctx context.Context, scope *storage.S return err } if err := rolePkg.ValidateSimpleAccessScope(scope); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } if err := verifyNotDefaultAccessScope(scope); err != nil { return err @@ -347,7 +347,7 @@ func (ds *dataStoreImpl) RemoveAccessScope(ctx context.Context, id string) error return err } if !found { - return errors.Wrapf(errorhelpers.ErrNotFound, "id = %s", id) + return errors.Wrapf(errox.NotFound, "id = %s", id) } if err := verifyNotDefaultAccessScope(accessScope); err != nil { return err @@ -360,7 +360,7 @@ func (ds *dataStoreImpl) RemoveAccessScope(ctx context.Context, id string) error } for _, role := range roles { if role.GetAccessScopeId() == id { - return errors.Wrapf(errorhelpers.ErrReferencedByAnotherObject, "cannot delete access scope in use by role %q", role.GetName()) + return errors.Wrapf(errox.ReferencedByAnotherObject, "cannot delete access scope in use by role %q", role.GetName()) } } @@ -414,23 +414,23 @@ func (ds *dataStoreImpl) GetAndResolveRole(ctx context.Context, name string) (pe func (ds *dataStoreImpl) verifyRoleReferencesExist(ctx context.Context, role *storage.Role) error { // Verify storage constraints. if err := ds.verifyPermissionSetIDExists(ctx, role.GetPermissionSetId()); err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "referenced permission set %s does not exist", role.GetPermissionSetId()) + return errors.Wrapf(errox.InvalidArgs, "referenced permission set %s does not exist", role.GetPermissionSetId()) } if err := ds.verifyAccessScopeIDExists(ctx, role.GetAccessScopeId()); err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "referenced access scope %s does not exist", role.GetAccessScopeId()) + return errors.Wrapf(errox.InvalidArgs, "referenced access scope %s does not exist", role.GetAccessScopeId()) } return nil } -// Returns errorhelpers.ErrInvalidArgs if the given role is a default one. +// Returns errox.InvalidArgs if the given role is a default one. func verifyNotDefaultRole(name string) error { if rolePkg.IsDefaultRoleName(name) { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "default role %q cannot be modified or deleted", name) + return errors.Wrapf(errox.InvalidArgs, "default role %q cannot be modified or deleted", name) } return nil } -// Returns errorhelpers.ErrNotFound if there is no permission set with the supplied ID. +// Returns errox.NotFound if there is no permission set with the supplied ID. func (ds *dataStoreImpl) verifyPermissionSetIDExists(ctx context.Context, id string) error { _, found, err := ds.permissionSetStorage.Get(ctx, id) @@ -438,12 +438,12 @@ func (ds *dataStoreImpl) verifyPermissionSetIDExists(ctx context.Context, id str return err } if !found { - return errors.Wrapf(errorhelpers.ErrNotFound, "id = %s", id) + return errors.Wrapf(errox.NotFound, "id = %s", id) } return nil } -// Returns errorhelpers.ErrAlreadyExists if there is a permission set with the same ID. +// Returns errox.AlreadyExists if there is a permission set with the same ID. func (ds *dataStoreImpl) verifyPermissionSetIDDoesNotExist(ctx context.Context, id string) error { _, found, err := ds.permissionSetStorage.Get(ctx, id) @@ -451,21 +451,21 @@ func (ds *dataStoreImpl) verifyPermissionSetIDDoesNotExist(ctx context.Context, return err } if found { - return errors.Wrapf(errorhelpers.ErrAlreadyExists, "id = %s", id) + return errors.Wrapf(errox.AlreadyExists, "id = %s", id) } return nil } -// Returns errorhelpers.ErrInvalidArgs if the given permission set is a default +// Returns errox.InvalidArgs if the given permission set is a default // one. Note that IsDefaultRoleName() is reused due to the name sameness. func verifyNotDefaultPermissionSet(name string) error { if rolePkg.IsDefaultRoleName(name) { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "default permission set %q cannot be modified or deleted", name) + return errors.Wrapf(errox.InvalidArgs, "default permission set %q cannot be modified or deleted", name) } return nil } -// Returns errorhelpers.ErrNotFound if there is no access scope with the supplied ID. +// Returns errox.NotFound if there is no access scope with the supplied ID. func (ds *dataStoreImpl) verifyAccessScopeIDExists(ctx context.Context, id string) error { _, found, err := ds.accessScopeStorage.Get(ctx, id) @@ -473,12 +473,12 @@ func (ds *dataStoreImpl) verifyAccessScopeIDExists(ctx context.Context, id strin return err } if !found { - return errors.Wrapf(errorhelpers.ErrNotFound, "id = %s", id) + return errors.Wrapf(errox.NotFound, "id = %s", id) } return nil } -// Returns errorhelpers.ErrAlreadyExists if there is an access scope with the same ID. +// Returns errox.AlreadyExists if there is an access scope with the same ID. func (ds *dataStoreImpl) verifyAccessScopeIDDoesNotExist(ctx context.Context, id string) error { _, found, err := ds.accessScopeStorage.Get(ctx, id) @@ -486,12 +486,12 @@ func (ds *dataStoreImpl) verifyAccessScopeIDDoesNotExist(ctx context.Context, id return err } if found { - return errors.Wrapf(errorhelpers.ErrAlreadyExists, "id = %s", id) + return errors.Wrapf(errox.AlreadyExists, "id = %s", id) } return nil } -// Returns errorhelpers.ErrAlreadyExists if there is a role with the same name. +// Returns errox.AlreadyExists if there is a role with the same name. func (ds *dataStoreImpl) verifyRoleNameDoesNotExist(ctx context.Context, name string) error { _, found, err := ds.roleStorage.Get(ctx, name) @@ -499,12 +499,12 @@ func (ds *dataStoreImpl) verifyRoleNameDoesNotExist(ctx context.Context, name st return err } if found { - return errors.Wrapf(errorhelpers.ErrAlreadyExists, "name = %q", name) + return errors.Wrapf(errox.AlreadyExists, "name = %q", name) } return nil } -// Returns errorhelpers.ErrNotFound if there is no role with the supplied name. +// Returns errox.NotFound if there is no role with the supplied name. func (ds *dataStoreImpl) verifyRoleNameExists(ctx context.Context, name string) error { _, found, err := ds.roleStorage.Get(ctx, name) @@ -512,15 +512,15 @@ func (ds *dataStoreImpl) verifyRoleNameExists(ctx context.Context, name string) return err } if !found { - return errors.Wrapf(errorhelpers.ErrNotFound, "name = %q", name) + return errors.Wrapf(errox.NotFound, "name = %q", name) } return nil } -// Returns errorhelpers.ErrInvalidArgs if the given scope is a default one. +// Returns errox.InvalidArgs if the given scope is a default one. func verifyNotDefaultAccessScope(scope *storage.SimpleAccessScope) error { if rolePkg.IsDefaultAccessScope(scope.GetId()) { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "default access scope %q cannot be modified or deleted", scope.GetName()) + return errors.Wrapf(errox.InvalidArgs, "default access scope %q cannot be modified or deleted", scope.GetName()) } return nil } @@ -537,7 +537,7 @@ func (ds *dataStoreImpl) getRolePermissionSetOrError(ctx context.Context, role * return nil, err } else if !found || permissionSet == nil { log.Errorf("Failed to fetch permission set %s for the existing role %q", role.GetPermissionSetId(), role.GetName()) - return nil, errors.Wrapf(errorhelpers.ErrInvariantViolation, "permission set %s for role %q is missing", role.GetPermissionSetId(), role.GetName()) + return nil, errors.Wrapf(errox.InvariantViolation, "permission set %s for role %q is missing", role.GetPermissionSetId(), role.GetName()) } return permissionSet, nil } @@ -550,7 +550,7 @@ func (ds *dataStoreImpl) getRoleAccessScopeOrError(ctx context.Context, role *st return nil, err } else if !found || accessScope == nil { log.Errorf("Failed to fetch access scope %s for the existing role %q", role.GetAccessScopeId(), role.GetName()) - return nil, errors.Wrapf(errorhelpers.ErrInvariantViolation, "access scope %s for role %q is missing", role.GetAccessScopeId(), role.GetName()) + return nil, errors.Wrapf(errox.InvariantViolation, "access scope %s for role %q is missing", role.GetAccessScopeId(), role.GetName()) } return accessScope, nil } diff --git a/central/role/datastore/datastore_test.go b/central/role/datastore/datastore_test.go index 8415efae95e65..d5bafb5463a37 100644 --- a/central/role/datastore/datastore_test.go +++ b/central/role/datastore/datastore_test.go @@ -11,7 +11,7 @@ import ( simpleAccessScopeStore "github.com/stackrox/rox/central/role/store/simpleaccessscope/rocksdb" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/bolthelper" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/rocksdb" "github.com/stackrox/rox/pkg/sac" "github.com/stackrox/rox/pkg/testutils" @@ -208,19 +208,19 @@ func (s *roleDataStoreTestSuite) TestRoleWriteOperations() { updatedAdminRole := getValidRole(role.Admin, s.existingPermissionSet.GetId(), s.existingScope.GetId()) err := s.dataStore.AddRole(s.hasWriteCtx, badRole) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs, "invalid role for Add*() yields an error") + s.ErrorIs(err, errox.InvalidArgs, "invalid role for Add*() yields an error") err = s.dataStore.AddRole(s.hasWriteCtx, cloneRole) - s.ErrorIs(err, errorhelpers.ErrAlreadyExists, "adding role with an existing name yields an error") + s.ErrorIs(err, errox.AlreadyExists, "adding role with an existing name yields an error") err = s.dataStore.UpdateRole(s.hasWriteCtx, goodRole) - s.ErrorIs(err, errorhelpers.ErrNotFound, "updating non-existing role yields an error") + s.ErrorIs(err, errox.NotFound, "updating non-existing role yields an error") err = s.dataStore.UpdateRole(s.hasWriteCtx, updatedAdminRole) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs, "updating a default role yields an error") + s.ErrorIs(err, errox.InvalidArgs, "updating a default role yields an error") err = s.dataStore.RemoveRole(s.hasWriteCtx, goodRole.GetName()) - s.ErrorIs(err, errorhelpers.ErrNotFound, "removing non-existing role yields an error") + s.ErrorIs(err, errox.NotFound, "removing non-existing role yields an error") err = s.dataStore.AddRole(s.hasWriteCtx, goodRole) s.NoError(err) @@ -229,7 +229,7 @@ func (s *roleDataStoreTestSuite) TestRoleWriteOperations() { s.Len(roles, 2, "added roles should be visible in the subsequent Get*()") err = s.dataStore.UpdateRole(s.hasWriteCtx, badRole) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs, "invalid role for Update*() yields an error") + s.ErrorIs(err, errox.InvalidArgs, "invalid role for Update*() yields an error") err = s.dataStore.UpdateRole(s.hasWriteCtx, goodRole) s.NoError(err) @@ -337,22 +337,22 @@ func (s *roleDataStoreTestSuite) TestPermissionSetWriteOperations() { updatedAdminPermissionSet := getValidPermissionSet(role.EnsureValidAccessScopeID("admin"), role.Admin) err := s.dataStore.AddPermissionSet(s.hasWriteCtx, badPermissionSet) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs, "invalid permission set for Add*() yields an error") + s.ErrorIs(err, errox.InvalidArgs, "invalid permission set for Add*() yields an error") err = s.dataStore.AddPermissionSet(s.hasWriteCtx, clonePermissionSet) - s.ErrorIs(err, errorhelpers.ErrAlreadyExists, "adding permission set with an existing ID yields an error") + s.ErrorIs(err, errox.AlreadyExists, "adding permission set with an existing ID yields an error") err = s.dataStore.AddPermissionSet(s.hasWriteCtx, mimicPermissionSet) - s.ErrorIs(err, errorhelpers.ErrAlreadyExists, "adding permission set with an existing name yields an error") + s.ErrorIs(err, errox.AlreadyExists, "adding permission set with an existing name yields an error") err = s.dataStore.UpdatePermissionSet(s.hasWriteCtx, goodPermissionSet) - s.ErrorIs(err, errorhelpers.ErrNotFound, "updating non-existing permission set yields an error") + s.ErrorIs(err, errox.NotFound, "updating non-existing permission set yields an error") err = s.dataStore.UpdatePermissionSet(s.hasWriteCtx, updatedAdminPermissionSet) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs, "updating a default permission set yields an error") + s.ErrorIs(err, errox.InvalidArgs, "updating a default permission set yields an error") err = s.dataStore.RemovePermissionSet(s.hasWriteCtx, goodPermissionSet.GetId()) - s.ErrorIs(err, errorhelpers.ErrNotFound, "removing non-existing permission set yields an error") + s.ErrorIs(err, errox.NotFound, "removing non-existing permission set yields an error") err = s.dataStore.AddPermissionSet(s.hasWriteCtx, goodPermissionSet) s.NoError(err) @@ -361,10 +361,10 @@ func (s *roleDataStoreTestSuite) TestPermissionSetWriteOperations() { s.Len(permissionSets, 2, "added permission set should be visible in the subsequent Get*()") err = s.dataStore.UpdatePermissionSet(s.hasWriteCtx, badPermissionSet) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs, "invalid permission set for Update*() yields an error") + s.ErrorIs(err, errox.InvalidArgs, "invalid permission set for Update*() yields an error") err = s.dataStore.UpdatePermissionSet(s.hasWriteCtx, mimicPermissionSet) - s.ErrorIs(err, errorhelpers.ErrAlreadyExists, "introducing a name collision with Update*() yields an error") + s.ErrorIs(err, errox.AlreadyExists, "introducing a name collision with Update*() yields an error") err = s.dataStore.UpdatePermissionSet(s.hasWriteCtx, goodPermissionSet) s.NoError(err) @@ -477,22 +477,22 @@ func (s *roleDataStoreTestSuite) TestAccessScopeWriteOperations() { role.AccessScopeExcludeAll.GetName()) err := s.dataStore.AddAccessScope(s.hasWriteCtx, badScope) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs, "invalid scope for Add*() yields an error") + s.ErrorIs(err, errox.InvalidArgs, "invalid scope for Add*() yields an error") err = s.dataStore.AddAccessScope(s.hasWriteCtx, cloneScope) - s.ErrorIs(err, errorhelpers.ErrAlreadyExists, "adding scope with an existing ID yields an error") + s.ErrorIs(err, errox.AlreadyExists, "adding scope with an existing ID yields an error") err = s.dataStore.AddAccessScope(s.hasWriteCtx, mimicScope) - s.ErrorIs(err, errorhelpers.ErrAlreadyExists, "adding scope with an existing name yields an error") + s.ErrorIs(err, errox.AlreadyExists, "adding scope with an existing name yields an error") err = s.dataStore.UpdateAccessScope(s.hasWriteCtx, goodScope) - s.ErrorIs(err, errorhelpers.ErrNotFound, "updating non-existing scope yields an error") + s.ErrorIs(err, errox.NotFound, "updating non-existing scope yields an error") err = s.dataStore.UpdateAccessScope(s.hasWriteCtx, updatedDefaultScope) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs, "updating a default scope yields an error") + s.ErrorIs(err, errox.InvalidArgs, "updating a default scope yields an error") err = s.dataStore.RemoveAccessScope(s.hasWriteCtx, goodScope.GetId()) - s.ErrorIs(err, errorhelpers.ErrNotFound, "removing non-existing scope yields an error") + s.ErrorIs(err, errox.NotFound, "removing non-existing scope yields an error") err = s.dataStore.AddAccessScope(s.hasWriteCtx, goodScope) s.NoError(err) @@ -501,10 +501,10 @@ func (s *roleDataStoreTestSuite) TestAccessScopeWriteOperations() { s.Len(scopes, 2, "added scope should be visible in the subsequent Get*()") err = s.dataStore.UpdateAccessScope(s.hasWriteCtx, badScope) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs, "invalid scope for Update*() yields an error") + s.ErrorIs(err, errox.InvalidArgs, "invalid scope for Update*() yields an error") err = s.dataStore.UpdateAccessScope(s.hasWriteCtx, mimicScope) - s.ErrorIs(err, errorhelpers.ErrAlreadyExists, "introducing a name collision with Update*() yields an error") + s.ErrorIs(err, errox.AlreadyExists, "introducing a name collision with Update*() yields an error") err = s.dataStore.UpdateAccessScope(s.hasWriteCtx, goodScope) s.NoError(err) @@ -530,21 +530,21 @@ func (s *roleDataStoreTestSuite) TestForeignKeyConstraints() { role := getValidRole("new valid role", permissionSet.GetId(), scope.GetId()) err = s.dataStore.AddRole(s.hasWriteCtx, role) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs, "Cannot create a Role without its PermissionSet and AccessScope existing") + s.ErrorIs(err, errox.InvalidArgs, "Cannot create a Role without its PermissionSet and AccessScope existing") s.NoError(s.dataStore.AddPermissionSet(s.hasWriteCtx, permissionSet)) err = s.dataStore.AddRole(s.hasWriteCtx, role) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs, "Cannot create a Role without its AccessScope existing") + s.ErrorIs(err, errox.InvalidArgs, "Cannot create a Role without its AccessScope existing") s.NoError(s.dataStore.AddAccessScope(s.hasWriteCtx, scope)) s.NoError(s.dataStore.AddRole(s.hasWriteCtx, role)) err = s.dataStore.RemovePermissionSet(s.hasWriteCtx, permissionSet.GetId()) - s.ErrorIs(err, errorhelpers.ErrReferencedByAnotherObject, "cannot delete a PermissionSet referred to by a Role") + s.ErrorIs(err, errox.ReferencedByAnotherObject, "cannot delete a PermissionSet referred to by a Role") err = s.dataStore.RemoveAccessScope(s.hasWriteCtx, scope.GetId()) - s.ErrorIs(err, errorhelpers.ErrReferencedByAnotherObject, "cannot delete an Access Scope referred to by a Role") + s.ErrorIs(err, errox.ReferencedByAnotherObject, "cannot delete an Access Scope referred to by a Role") s.NoError(s.dataStore.RemoveRole(s.hasWriteCtx, role.GetName())) s.NoError(s.dataStore.RemovePermissionSet(s.hasWriteCtx, permissionSet.GetId())) @@ -563,7 +563,7 @@ func (s *roleDataStoreTestSuite) TestGetAndResolveRole() { s.Nil(resolvedRole) err = s.dataStore.AddRole(s.hasWriteCtx, noScopeRole) - s.ErrorIs(err, errorhelpers.ErrInvalidArgs) + s.ErrorIs(err, errox.InvalidArgs) resolvedRole, err = s.dataStore.GetAndResolveRole(s.hasReadCtx, s.existingRole.GetName()) s.NoError(err) diff --git a/central/role/service/service_impl.go b/central/role/service/service_impl.go index 4959512d692fe..51e5804d0d124 100644 --- a/central/role/service/service_impl.go +++ b/central/role/service/service_impl.go @@ -14,7 +14,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authn" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/allow" @@ -99,7 +99,7 @@ func (s *serviceImpl) GetRole(ctx context.Context, id *v1.ResourceByID) (*storag return nil, errors.Wrapf(err, "failed to retrieve role %q", id.GetId()) } if !found { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "failed to retrieve role %q", id.GetId()) + return nil, errors.Wrapf(errox.NotFound, "failed to retrieve role %q", id.GetId()) } return role, nil } @@ -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, errorhelpers.NewErrInvalidArgs("different role names in path and body") + return nil, errox.NewErrInvalidArgs("different role names in path and body") } role.Name = roleRequest.GetName() @@ -186,7 +186,7 @@ func (s *serviceImpl) GetPermissionSet(ctx context.Context, id *v1.ResourceByID) return nil, errors.Wrapf(err, "failed to retrieve permission set %s", id.GetId()) } if !found { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "failed to retrieve permission set %s", id.GetId()) + return nil, errors.Wrapf(errox.NotFound, "failed to retrieve permission set %s", id.GetId()) } return permissionSet, nil @@ -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, errorhelpers.NewErrInvalidArgs("setting id field is not allowed") + return nil, errox.NewErrInvalidArgs("setting id field is not allowed") } permissionSet.Id = rolePkg.GeneratePermissionSetID() @@ -252,7 +252,7 @@ func (s *serviceImpl) GetSimpleAccessScope(ctx context.Context, id *v1.ResourceB return nil, errors.Wrapf(err, "failed to retrieve access scope %s", id.GetId()) } if !found { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "failed to retrieve access scope %s", id.GetId()) + return nil, errors.Wrapf(errox.NotFound, "failed to retrieve access scope %s", id.GetId()) } return scope, nil @@ -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, errorhelpers.NewErrInvalidArgs("setting id field is not allowed") + return nil, errox.NewErrInvalidArgs("setting id field is not allowed") } scope.Id = rolePkg.GenerateAccessScopeID() diff --git a/central/sac/service/service_impl.go b/central/sac/service/service_impl.go index 17babfdc49548..947bf0104cb9e 100644 --- a/central/sac/service/service_impl.go +++ b/central/sac/service/service_impl.go @@ -12,7 +12,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authn" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" @@ -78,13 +78,13 @@ func (*serviceImpl) AuthFuncOverride(ctx context.Context, fullMethodName string) func (s *serviceImpl) DryRunAuthzPluginConfig(ctx context.Context, req *v1.UpsertAuthzPluginConfigRequest) (*v1.Empty, error) { if err := validateConfig(req.GetConfig()); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if _, err := s.reconcileUpsertAuthzPluginConfigRequest(ctx, req); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if err := s.testConfig(ctx, req.GetConfig()); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } return &v1.Empty{}, nil } @@ -106,11 +106,11 @@ func (s *serviceImpl) AddAuthzPluginConfig(ctx context.Context, req *v1.UpsertAu cfg := req.GetConfig() if err := validateConfig(cfg); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if cfg.GetEnabled() { if err := s.testConfig(ctx, cfg); err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "%v\nCheck the central logs for full error.", err) + return nil, errors.Wrapf(errox.InvalidArgs, "%v\nCheck the central logs for full error.", err) } } @@ -131,19 +131,19 @@ func (s *serviceImpl) UpdateAuthzPluginConfig(ctx context.Context, req *v1.Upser cfg := req.GetConfig() if cfg.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "update must specify an ID") + return nil, errors.Wrap(errox.InvalidArgs, "update must specify an ID") } if err := validateConfig(cfg); err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } reconciled, err := s.reconcileUpsertAuthzPluginConfigRequest(ctx, req) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } if cfg.GetEnabled() { if err := s.testConfig(ctx, cfg); err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "%v\nCheck the central logs for full error.", err) + return nil, errors.Wrapf(errox.InvalidArgs, "%v\nCheck the central logs for full error.", err) } } @@ -192,20 +192,20 @@ func (s *serviceImpl) reconcileUpsertAuthzPluginConfigRequest(ctx context.Contex return false, nil } if updateRequest.GetConfig() == nil { - return false, errors.Wrap(errorhelpers.ErrInvalidArgs, "request is missing authz plugin config") + return false, errors.Wrap(errox.InvalidArgs, "request is missing authz plugin config") } if updateRequest.GetConfig().GetId() == "" { - return false, errors.Wrap(errorhelpers.ErrNotFound, "id required for stored credential reconciliation") + return false, errors.Wrap(errox.NotFound, "id required for stored credential reconciliation") } existingAuthzPluginConfig, err := s.ds.GetAuthzPluginConfig(ctx, updateRequest.GetConfig().GetId()) if err != nil { return false, err } if existingAuthzPluginConfig == nil { - return false, errors.Wrapf(errorhelpers.ErrNotFound, "existing authz plugin %s not found", updateRequest.GetConfig().GetId()) + return false, errors.Wrapf(errox.NotFound, "existing authz plugin %s not found", updateRequest.GetConfig().GetId()) } if err := reconcileAuthzPluginConfigWithExisting(updateRequest.GetConfig(), existingAuthzPluginConfig); err != nil { - return false, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return false, errors.Wrap(errox.InvalidArgs, err.Error()) } return true, nil } diff --git a/central/search/service/service_impl.go b/central/search/service/service_impl.go index c930c70b47f61..c39be9fecc00a 100644 --- a/central/search/service/service_impl.go +++ b/central/search/service/service_impl.go @@ -32,7 +32,7 @@ import ( serviceAccountDataStore "github.com/stackrox/rox/central/serviceaccount/datastore" v1 "github.com/stackrox/rox/generated/api/v1" protoSet "github.com/stackrox/rox/generated/set" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -192,7 +192,7 @@ func trimMatches(matches map[string][]string, fieldPaths []string) map[string][] func RunAutoComplete(ctx context.Context, queryString string, categories []v1.SearchCategory, searchers map[v1.SearchCategory]search.Searcher) ([]string, error) { query, autocompleteKey, err := search.ParseQueryForAutocomplete(queryString) if err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "unable to parse query %q: %v", queryString, err) + return nil, errors.Wrapf(errox.InvalidArgs, "unable to parse query %q: %v", queryString, err) } // Set the max return size for the query query.Pagination = &v1.QueryPagination{ @@ -212,12 +212,12 @@ func RunAutoComplete(ctx context.Context, queryString string, categories []v1.Se if ok { utils.Should(errors.Errorf("searchers map has an entry for category %v, but the returned searcher was nil", category)) } - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "Search category %q is not implemented", category.String()) + return nil, errors.Wrapf(errox.InvalidArgs, "Search category %q is not implemented", category.String()) } optMultiMap := categoryToOptionsMultimap[category] if optMultiMap == nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "Search category %q is not implemented", category.String()) + return nil, errors.Wrapf(errox.InvalidArgs, "Search category %q is not implemented", category.String()) } autocompleteFields := optMultiMap.GetAll(autocompleteKey) @@ -279,7 +279,7 @@ func (s *serviceImpl) autocomplete(ctx context.Context, queryString string, cate func (s *serviceImpl) Autocomplete(ctx context.Context, req *v1.RawSearchRequest) (*v1.AutocompleteResponse, error) { if req.GetQuery() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "query cannot be empty") + return nil, errors.Wrap(errox.InvalidArgs, "query cannot be empty") } results, err := s.autocomplete(ctx, req.GetQuery(), req.GetCategories()) if err != nil { @@ -335,7 +335,7 @@ func GlobalSearch(ctx context.Context, query string, categories []v1.SearchCateg parsedRequest, err := search.ParseQuery(query) if err != nil { - err = errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + err = errors.Wrap(errox.InvalidArgs, err.Error()) return } if len(categories) == 0 { @@ -348,7 +348,7 @@ func GlobalSearch(ctx context.Context, query string, categories []v1.SearchCateg } searchFunc, ok := searchFuncMap[category] if !ok { - err = errors.Wrapf(errorhelpers.ErrInvalidArgs, "Search category '%s' is not implemented", category.String()) + err = errors.Wrapf(errox.InvalidArgs, "Search category '%s' is not implemented", category.String()) return } var resultsFromCategory []*v1.SearchResult diff --git a/central/secret/service/service_impl.go b/central/secret/service/service_impl.go index 2893f92574513..a35f4e6046ce4 100644 --- a/central/secret/service/service_impl.go +++ b/central/secret/service/service_impl.go @@ -11,7 +11,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -62,7 +62,7 @@ func (s *serviceImpl) GetSecret(ctx context.Context, request *v1.ResourceByID) ( return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "secret with id '%s' does not exist", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "secret with id '%s' does not exist", request.GetId()) } psr := search.NewQueryBuilder(). @@ -94,7 +94,7 @@ func (s *serviceImpl) CountSecrets(ctx context.Context, request *v1.RawQuery) (* // Fill in Query. parsedQuery, err := search.ParseQuery(request.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } numSecrets, err := s.secrets.Count(ctx, parsedQuery) @@ -109,7 +109,7 @@ func (s *serviceImpl) ListSecrets(ctx context.Context, request *v1.RawQuery) (*v // Fill in query. parsedQuery, err := search.ParseQuery(request.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } // Fill in pagination. diff --git a/central/sensor/service/service_impl.go b/central/sensor/service/service_impl.go index cd3a85259ff79..4d30a4d036499 100644 --- a/central/sensor/service/service_impl.go +++ b/central/sensor/service/service_impl.go @@ -15,7 +15,7 @@ import ( "github.com/stackrox/rox/generated/internalapi/central" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/centralsensor" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authn" "github.com/stackrox/rox/pkg/grpc/authz/idcheck" "github.com/stackrox/rox/pkg/logging" @@ -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 errorhelpers.NewErrNotAuthorized("only sensor may access this API") + return errox.NewErrNotAuthorized("only sensor may access this API") } sensorHello, sensorSupportsHello, err := receiveSensorHello(server) @@ -162,7 +162,7 @@ func (s *serviceImpl) getClusterForConnection(sensorHello *central.SensorHello, clusterIDFromCert := serviceID.GetId() if helmConfigInit == nil && centralsensor.IsInitCertClusterID(clusterIDFromCert) { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "sensor using cluster init certificate must transmit a helm-managed configuration") + return nil, errors.Wrap(errox.InvalidArgs, "sensor using cluster init certificate must transmit a helm-managed configuration") } clusterID := helmConfigInit.GetClusterId() @@ -170,7 +170,7 @@ func (s *serviceImpl) getClusterForConnection(sensorHello *central.SensorHello, var err error clusterID, err = centralsensor.GetClusterID(clusterID, clusterIDFromCert) if err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "incompatible cluster IDs in config init and certificate: %v", err) + return nil, errors.Wrapf(errox.InvalidArgs, "incompatible cluster IDs in config init and certificate: %v", err) } } diff --git a/central/sensorupgrade/controlservice/service_impl.go b/central/sensorupgrade/controlservice/service_impl.go index ecc80fa410969..86c7409efce40 100644 --- a/central/sensorupgrade/controlservice/service_impl.go +++ b/central/sensorupgrade/controlservice/service_impl.go @@ -11,7 +11,7 @@ import ( "github.com/stackrox/rox/generated/internalapi/central" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/centralsensor" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authn" "github.com/stackrox/rox/pkg/grpc/authz/idcheck" "github.com/stackrox/rox/pkg/utils" @@ -36,12 +36,12 @@ func clusterIDFromCtx(ctx context.Context) (string, error) { svc := id.Service() if svc == nil || svc.GetType() != storage.ServiceType_SENSOR_SERVICE { - return "", errorhelpers.NewErrNotAuthorized("only sensor/upgrader may access this API") + return "", errox.NewErrNotAuthorized("only sensor/upgrader may access this API") } clusterID := svc.GetId() if clusterID == "" { - return "", errorhelpers.NewErrNotAuthorized("only sensors with a valid cluster ID may access this API") + return "", errox.NewErrNotAuthorized("only sensors with a valid cluster ID may access this API") } return clusterID, nil } @@ -54,7 +54,7 @@ func (s *service) UpgradeCheckInFromUpgrader(ctx context.Context, req *central.U clusterID, err := centralsensor.GetClusterID(req.GetClusterId(), clusterIDFromCert) if err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "failed to derive cluster ID: %s", err) + return nil, errors.Wrapf(errox.InvalidArgs, "failed to derive cluster ID: %s", err) } return s.connectionManager.ProcessCheckInFromUpgrader(ctx, clusterID, req) @@ -68,7 +68,7 @@ func (s *service) UpgradeCheckInFromSensor(ctx context.Context, req *central.Upg clusterID, err := centralsensor.GetClusterID(req.GetClusterId(), clusterIDFromCert) if err != nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "failed to derive cluster ID: %s", err) + return nil, errors.Wrapf(errox.InvalidArgs, "failed to derive cluster ID: %s", err) } if err := s.connectionManager.ProcessUpgradeCheckInFromSensor(ctx, clusterID, req); err != nil { diff --git a/central/sensorupgrade/service/service_impl.go b/central/sensorupgrade/service/service_impl.go index 9e1f8c865560d..a197a6c043c2e 100644 --- a/central/sensorupgrade/service/service_impl.go +++ b/central/sensorupgrade/service/service_impl.go @@ -10,7 +10,7 @@ import ( "github.com/stackrox/rox/central/sensorupgradeconfig/datastore" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -55,14 +55,14 @@ func (s *service) GetSensorUpgradeConfig(ctx context.Context, _ *v1.Empty) (*v1. return nil, err } if config == nil { - return nil, errors.Wrap(errorhelpers.ErrNotFound, "couldn't find sensor upgrade config") + return nil, errors.Wrap(errox.NotFound, "couldn't find sensor upgrade config") } return &v1.GetSensorUpgradeConfigResponse{Config: config}, nil } func (s *service) UpdateSensorUpgradeConfig(ctx context.Context, req *v1.UpdateSensorUpgradeConfigRequest) (*v1.Empty, error) { if req.GetConfig() == nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "need to specify a config") + return nil, errors.Wrap(errox.InvalidArgs, "need to specify a config") } if err := s.configDataStore.UpsertSensorUpgradeConfig(ctx, req.GetConfig()); err != nil { return nil, err @@ -72,7 +72,7 @@ func (s *service) UpdateSensorUpgradeConfig(ctx context.Context, req *v1.UpdateS func (s *service) TriggerSensorUpgrade(ctx context.Context, req *v1.ResourceByID) (*v1.Empty, error) { if req.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "no cluster ID specified") + return nil, errors.Wrap(errox.InvalidArgs, "no cluster ID specified") } err := s.manager.TriggerUpgrade(ctx, req.GetId()) @@ -83,7 +83,7 @@ func (s *service) TriggerSensorUpgrade(ctx context.Context, req *v1.ResourceByID } func (s *service) TriggerSensorCertRotation(ctx context.Context, req *v1.ResourceByID) (*v1.Empty, error) { if req.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "no cluster ID specified") + return nil, errors.Wrap(errox.InvalidArgs, "no cluster ID specified") } err := s.manager.TriggerCertRotation(ctx, req.GetId()) diff --git a/central/serviceaccount/service/service_impl.go b/central/serviceaccount/service/service_impl.go index 8364b51c362fb..cac1020e4439e 100644 --- a/central/serviceaccount/service/service_impl.go +++ b/central/serviceaccount/service/service_impl.go @@ -15,7 +15,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -64,7 +64,7 @@ func (s *serviceImpl) GetServiceAccount(ctx context.Context, request *v1.Resourc return nil, err } if !exists { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "service account with id '%s' does not exist", request.GetId()) + return nil, errors.Wrapf(errox.NotFound, "service account with id '%s' does not exist", request.GetId()) } clusterRoles, scopedRoles, err := s.getRoles(ctx, sa) @@ -87,7 +87,7 @@ func (s *serviceImpl) GetServiceAccount(ctx context.Context, request *v1.Resourc func (s *serviceImpl) ListServiceAccounts(ctx context.Context, rawQuery *v1.RawQuery) (*v1.ListServiceAccountResponse, error) { q, err := search.ParseQuery(rawQuery.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } serviceAccounts, err := s.serviceAccounts.SearchRawServiceAccounts(ctx, q) diff --git a/central/serviceidentities/service/service_impl.go b/central/serviceidentities/service/service_impl.go index b1f33db16ba74..bfaa95edac672 100644 --- a/central/serviceidentities/service/service_impl.go +++ b/central/serviceidentities/service/service_impl.go @@ -10,7 +10,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -66,13 +66,13 @@ func (s *serviceImpl) GetServiceIdentities(ctx context.Context, _ *v1.Empty) (*v // in the response to this API call. func (s *serviceImpl) CreateServiceIdentity(ctx context.Context, request *v1.CreateServiceIdentityRequest) (*v1.CreateServiceIdentityResponse, error) { if request == nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Request must be nonempty") + return nil, errors.Wrap(errox.InvalidArgs, "Request must be nonempty") } if request.GetId() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "ID must be nonempty") + return nil, errors.Wrap(errox.InvalidArgs, "ID must be nonempty") } if request.GetType() == storage.ServiceType_UNKNOWN_SERVICE { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "Service type must be nonempty") + return nil, errors.Wrap(errox.InvalidArgs, "Service type must be nonempty") } issuedCert, err := mtls.IssueNewCert(mtls.NewSubject(request.GetId(), request.GetType())) if err != nil { diff --git a/central/user/service/service_impl.go b/central/user/service/service_impl.go index 2a8c00ae1d638..a6576db9f205f 100644 --- a/central/user/service/service_impl.go +++ b/central/user/service/service_impl.go @@ -11,7 +11,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" "github.com/stackrox/rox/pkg/grpc/authz/user" @@ -61,7 +61,7 @@ func (s *serviceImpl) GetUser(ctx context.Context, id *v1.ResourceByID) (*storag return nil, err } if user == nil { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "user %s not found", id.GetId()) + return nil, errors.Wrapf(errox.NotFound, "user %s not found", id.GetId()) } return user, nil } diff --git a/central/vulnerabilityrequest/manager/requestmgr/manager_impl.go b/central/vulnerabilityrequest/manager/requestmgr/manager_impl.go index 4a484a8fecc59..b03656358eb4a 100644 --- a/central/vulnerabilityrequest/manager/requestmgr/manager_impl.go +++ b/central/vulnerabilityrequest/manager/requestmgr/manager_impl.go @@ -25,6 +25,7 @@ import ( "github.com/stackrox/rox/pkg/batcher" "github.com/stackrox/rox/pkg/concurrency" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/sac" "github.com/stackrox/rox/pkg/search" deploymentOptionsMap "github.com/stackrox/rox/pkg/search/options/deployments" @@ -78,7 +79,7 @@ func (m *managerImpl) Stop() { func (m *managerImpl) Create(ctx context.Context, req *storage.VulnerabilityRequest) error { if err := validator.ValidateNewSuppressVulnRequest(req); err != nil { - return errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return errors.Wrap(errox.InvalidArgs, err.Error()) } // Find all requests for this CVE that are active and approved @@ -88,7 +89,7 @@ func (m *managerImpl) Create(ctx context.Context, req *storage.VulnerabilityRequ } // And validate that this CVE + VulnReqScope combo hasn't been unwatched already if err := validator.ValidateSuppressVulnRequestIsUnique(req, reqs); err != nil { - return errors.Wrap(errorhelpers.ErrAlreadyExists, err.Error()) + return errors.Wrap(errox.AlreadyExists, err.Error()) } req.Id = uuid.NewV4().String() @@ -103,7 +104,7 @@ func (m *managerImpl) Create(ctx context.Context, req *storage.VulnerabilityRequ func (m *managerImpl) Approve(ctx context.Context, id string, reqParams *common.VulnRequestParams) (*storage.VulnerabilityRequest, error) { if reqParams == nil || reqParams.Comment == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "comment must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "comment must be provided") } req, err := m.vulnReqs.UpdateRequestStatus(ctx, id, reqParams.Comment, storage.RequestStatus_APPROVED) if err != nil { @@ -127,7 +128,7 @@ func (m *managerImpl) Delete(ctx context.Context, id string) error { func (m *managerImpl) Deny(ctx context.Context, id string, reqParams *common.VulnRequestParams) (*storage.VulnerabilityRequest, error) { if reqParams.Comment == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "comment must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "comment must be provided") } req, err := m.vulnReqs.UpdateRequestStatus(ctx, id, reqParams.Comment, storage.RequestStatus_DENIED) if err != nil { @@ -154,7 +155,7 @@ func (m *managerImpl) Undo(ctx context.Context, id string, reqParams *common.Vul func (m *managerImpl) UpdateExpiry(ctx context.Context, id string, reqParams *common.VulnRequestParams) (*storage.VulnerabilityRequest, error) { // Currently, only deferral requests can be updated if reqParams.Expiry == nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "nothing to update for request - at least expiry must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "nothing to update for request - at least expiry must be provided") } req, err := m.vulnReqs.UpdateRequestExpiry(ctx, id, reqParams.Comment, reqParams.Expiry) if err != nil { diff --git a/central/vulnerabilityrequest/service/service_impl.go b/central/vulnerabilityrequest/service/service_impl.go index 29322565b8360..f837e9d7168f8 100644 --- a/central/vulnerabilityrequest/service/service_impl.go +++ b/central/vulnerabilityrequest/service/service_impl.go @@ -12,7 +12,7 @@ import ( "github.com/stackrox/rox/central/vulnerabilityrequest/utils" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/or" "github.com/stackrox/rox/pkg/grpc/authz/perrpc" @@ -88,7 +88,7 @@ func (s *serviceImpl) GetVulnerabilityRequest(ctx context.Context, req *v1.Resou func (s *serviceImpl) ListVulnerabilityRequests(ctx context.Context, req *v1.RawQuery) (*v1.ListVulnerabilityRequestsResponse, error) { parsedQuery, err := search.ParseQuery(req.GetQuery(), search.MatchAllIfEmpty()) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } // Fill in pagination. paginated.FillPagination(parsedQuery, req.Pagination, maxRequestsReturned) diff --git a/pkg/auth/authproviders/provider_impl.go b/pkg/auth/authproviders/provider_impl.go index 48c86c22989d2..922f691b84c38 100644 --- a/pkg/auth/authproviders/provider_impl.go +++ b/pkg/auth/authproviders/provider_impl.go @@ -9,7 +9,7 @@ import ( "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/auth/tokens" "github.com/stackrox/rox/pkg/concurrency" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/sync" "github.com/stackrox/rox/pkg/utils" ) @@ -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, errorhelpers.NewErrInvariantViolation( + return nil, errox.NewErrInvariantViolation( "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 687d350accda5..15c64ab996660 100644 --- a/pkg/auth/authproviders/registry_httphandler.go +++ b/pkg/auth/authproviders/registry_httphandler.go @@ -16,7 +16,7 @@ import ( v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/pkg/auth/authproviders/idputil" "github.com/stackrox/rox/pkg/auth/tokens" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/requestinfo" "github.com/stackrox/rox/pkg/httputil" "github.com/stackrox/rox/pkg/sac" @@ -275,13 +275,13 @@ func (r *registryImpl) providersHTTPHandler(w http.ResponseWriter, req *http.Req userInfo := user.GetUserInfo() if userInfo == nil { - err := errorhelpers.NewErrNotAuthorized("failed to get user info") + err := errox.NewErrNotAuthorized("failed to get user info") r.error(w, err, typ, clientState, testMode) return } userRoles := userInfo.GetRoles() if len(userRoles) == 0 { - err := errorhelpers.GenericNoValidRole() + err := errox.GenericNoValidRole() r.error(w, err, typ, clientState, testMode) return } diff --git a/pkg/auth/authproviders/registry_httphandler_test.go b/pkg/auth/authproviders/registry_httphandler_test.go index 6f577f53eb111..a7f0ecce24f01 100644 --- a/pkg/auth/authproviders/registry_httphandler_test.go +++ b/pkg/auth/authproviders/registry_httphandler_test.go @@ -18,7 +18,7 @@ import ( "github.com/stackrox/rox/pkg/auth/authproviders/idputil" perm "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/auth/tokens" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/requestinfo" "github.com/stackrox/rox/pkg/testutils/roletest" "github.com/stretchr/testify/assert" @@ -239,7 +239,7 @@ func (s *registryProviderCallbackTestSuite) TestAuthenticationRejectsUserWithout s.assert.Equal(s.registry.redirectURL, redirectURL.Path, "callback activated for user without role "+ "should redirect to the registry redirect URL") callbackError := fmt.Errorf("access for this user is not authorized: %w, please contact your system administrator", - errorhelpers.ErrNoValidRole) + errox.NoValidRole) s.assert.Equal(callbackError.Error(), redirectURLFragments.Get("error"), "callback activated for user without role should issue an explicit message") } diff --git a/pkg/auth/authproviders/registry_impl.go b/pkg/auth/authproviders/registry_impl.go index 3199c0b398409..b301f5261158d 100644 --- a/pkg/auth/authproviders/registry_impl.go +++ b/pkg/auth/authproviders/registry_impl.go @@ -9,7 +9,7 @@ import ( "github.com/pkg/errors" "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/auth/tokens" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/logging" "github.com/stackrox/rox/pkg/sync" ) @@ -222,7 +222,7 @@ func (r *registryImpl) DeleteProvider(ctx context.Context, id string, ignoreActi func (r *registryImpl) ResolveProvider(typ, state string) (Provider, error) { factory := r.getFactory(typ) if factory == nil { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid auth provider type %q", typ) + return nil, errors.Wrapf(errox.InvalidArgs, "invalid auth provider type %q", typ) } providerID, _, err := factory.ResolveProviderAndClientState(state) @@ -231,7 +231,7 @@ func (r *registryImpl) ResolveProvider(typ, state string) (Provider, error) { } provider := r.getAuthProvider(providerID) if provider == nil { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, "could not locate auth provider %q", providerID) + return nil, errors.Wrapf(errox.NotFound, "could not locate auth provider %q", providerID) } return provider, nil } @@ -239,7 +239,7 @@ func (r *registryImpl) ResolveProvider(typ, state string) (Provider, error) { func (r *registryImpl) GetExternalUserClaim(ctx context.Context, externalToken, typ, state string) (*AuthResponse, string, error) { factory := r.getFactory(typ) if factory == nil { - return nil, "", errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid auth provider type %q", typ) + return nil, "", errors.Wrapf(errox.InvalidArgs, "invalid auth provider type %q", typ) } providerID, clientState, err := factory.ResolveProviderAndClientState(state) @@ -248,7 +248,7 @@ func (r *registryImpl) GetExternalUserClaim(ctx context.Context, externalToken, } provider := r.getAuthProvider(providerID) if provider == nil { - return nil, clientState, errors.Wrapf(errorhelpers.ErrNotFound, "could not locate auth provider %q", providerID) + return nil, clientState, errors.Wrapf(errox.NotFound, "could not locate auth provider %q", providerID) } backend, err := provider.GetOrCreateBackend(ctx) diff --git a/pkg/errorhelpers/errors.go b/pkg/errorhelpers/errors.go deleted file mode 100644 index cb7ae3cc083cf..0000000000000 --- a/pkg/errorhelpers/errors.go +++ /dev/null @@ -1,24 +0,0 @@ -package errorhelpers - -import ( - "github.com/stackrox/rox/pkg/errox" -) - -// Deprecated: use the errox errors and functions instead of these aliases. -var ( - ErrAlreadyExists = errox.AlreadyExists - ErrInvalidArgs = errox.InvalidArgs - ErrNotFound = errox.NotFound - ErrReferencedByAnotherObject = errox.ReferencedByAnotherObject - ErrInvariantViolation = errox.InvariantViolation - ErrNoCredentials = errox.NoCredentials - ErrNoValidRole = errox.NoValidRole - ErrNotAuthorized = errox.NotAuthorized - ErrNoAuthzConfigured = errox.NoAuthzConfigured - - GenericNoValidRole = errox.GenericNoValidRole - NewErrNotAuthorized = errox.NewErrNotAuthorized - NewErrNoCredentials = errox.NewErrNoCredentials - NewErrInvariantViolation = errox.NewErrInvariantViolation - NewErrInvalidArgs = errox.NewErrInvalidArgs -) diff --git a/pkg/gjson/row.go b/pkg/gjson/row.go index 5abd5446c50ef..cceb1d7b4ea9a 100644 --- a/pkg/gjson/row.go +++ b/pkg/gjson/row.go @@ -6,7 +6,7 @@ import ( "sort" "strings" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/tidwall/gjson" ) @@ -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, errorhelpers.NewErrInvariantViolation(err.Error()) + return nil, errox.NewErrInvariantViolation(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{}, errorhelpers.NewErrInvariantViolation("expected gjson " + + return gjson.Result{}, errox.NewErrInvariantViolation("expected gjson " + "results to be exactly 1") } @@ -110,10 +110,9 @@ func getRowsFromColumns(columns [][]string) [][]string { return rows } -// jaggedArrayError helper to create an errorhelpers.ErrInvariantViolation with an explanation about -// a jagged array being found +// jaggedArrayError helper to create an errox.InvariantViolation with an explanation about a jagged array being found func jaggedArrayError(maxAmount, violatedAmount, arrayIndex int) error { - return errorhelpers.NewErrInvariantViolation(fmt.Sprintf("jagged array found: yielded values within "+ + return errox.NewErrInvariantViolation(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/context.go b/pkg/grpc/authn/context.go index 1f997c425e609..a489d62472103 100644 --- a/pkg/grpc/authn/context.go +++ b/pkg/grpc/authn/context.go @@ -4,7 +4,7 @@ import ( "context" "testing" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" ) type identityContextKey struct{} @@ -20,7 +20,7 @@ func IdentityFromContext(ctx context.Context) (Identity, error) { if id != nil { return id, nil } - return nil, errorhelpers.ErrNoCredentials + return nil, errox.NoCredentials } // IdentityFromContextOrNil retrieves the identity from the context, if any. diff --git a/pkg/grpc/authn/interceptor.go b/pkg/grpc/authn/interceptor.go index 888ba9b1d9029..0a613558954da 100644 --- a/pkg/grpc/authn/interceptor.go +++ b/pkg/grpc/authn/interceptor.go @@ -5,7 +5,7 @@ import ( "errors" "github.com/stackrox/rox/pkg/contextutil" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/requestinfo" "github.com/stackrox/rox/pkg/logging" "gopkg.in/square/go-jose.v2/jwt" @@ -28,12 +28,12 @@ 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{}, errorhelpers.NewErrNoCredentials(err.Error())), nil + return context.WithValue(ctx, identityErrorContextKey{}, errox.NewErrNoCredentials(err.Error())), nil } if id != nil { // Only service identities can have no roles assigned. if len(id.Roles()) == 0 && id.Service() == nil { - return context.WithValue(ctx, identityErrorContextKey{}, errorhelpers.GenericNoValidRole()), nil + return context.WithValue(ctx, identityErrorContextKey{}, errox.GenericNoValidRole()), nil } return context.WithValue(ctx, identityContextKey{}, id), nil } diff --git a/pkg/grpc/authz/and/and.go b/pkg/grpc/authz/and/and.go index db7dfbe75b86f..371deea682949 100644 --- a/pkg/grpc/authz/and/and.go +++ b/pkg/grpc/authz/and/and.go @@ -4,6 +4,7 @@ import ( "context" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" ) @@ -19,7 +20,7 @@ func (a *and) Authorized(ctx context.Context, fullMethodName string) error { } } if len(errors) != 0 { - return errorhelpers.NewErrNotAuthorized(errorhelpers.NewErrorListWithErrors("some authorizer could not authorize this request:", errors).String()) + return errox.NewErrNotAuthorized(errorhelpers.NewErrorListWithErrors("some authorizer could not authorize this request:", errors).String()) } return nil } diff --git a/pkg/grpc/authz/deny/deny.go b/pkg/grpc/authz/deny/deny.go index d6024b8bb7e94..8f7489c0e94fb 100644 --- a/pkg/grpc/authz/deny/deny.go +++ b/pkg/grpc/authz/deny/deny.go @@ -3,14 +3,14 @@ package deny import ( "context" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" ) // AuthFunc denies all access. It is meant to be used as a default gRPC AuthFunc // to enforce that services create meaningful ones. func AuthFunc(ctx context.Context) (context.Context, error) { - return ctx, errorhelpers.ErrNoAuthzConfigured + return ctx, errox.NoAuthzConfigured } // Everyone returns an Authorizer that denies all access, even if the client @@ -25,5 +25,5 @@ type everyone struct{} // Authorized denies all access, even if the client has been authenticated. func (everyone) Authorized(context.Context, string) error { - return errorhelpers.ErrNoAuthzConfigured + return errox.NoAuthzConfigured } diff --git a/pkg/grpc/authz/idcheck/service_type.go b/pkg/grpc/authz/idcheck/service_type.go index 9d57212abbb40..96987c4585efa 100644 --- a/pkg/grpc/authz/idcheck/service_type.go +++ b/pkg/grpc/authz/idcheck/service_type.go @@ -2,7 +2,7 @@ package idcheck import ( "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authn" ) @@ -13,10 +13,10 @@ type serviceType storage.ServiceType func (s serviceType) AuthorizeByIdentity(id authn.Identity) error { svc := id.Service() if svc == nil { - return errorhelpers.ErrNoCredentials + return errox.NoCredentials } if svc.GetType() != storage.ServiceType(s) { - return errorhelpers.NewErrNotAuthorized("service source type not allowed") + return errox.NewErrNotAuthorized("service source type not allowed") } return nil } diff --git a/pkg/grpc/authz/or/or.go b/pkg/grpc/authz/or/or.go index c26914db1dfdd..f418e5f7d7339 100644 --- a/pkg/grpc/authz/or/or.go +++ b/pkg/grpc/authz/or/or.go @@ -4,6 +4,7 @@ import ( "context" "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/idcheck" ) @@ -21,7 +22,7 @@ func (o *or) Authorized(ctx context.Context, fullMethodName string) error { } errors = append(errors, err) } - return errorhelpers.NewErrNotAuthorized(errorhelpers.NewErrorListWithErrors("no authorizer could authorize this request:", errors).String()) + return errox.NewErrNotAuthorized(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 56435d1e33ae8..e07b591768c26 100644 --- a/pkg/grpc/authz/user/role.go +++ b/pkg/grpc/authz/user/role.go @@ -5,7 +5,7 @@ import ( "fmt" "github.com/stackrox/rox/pkg/auth/permissions/utils" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authn" "github.com/stackrox/rox/pkg/grpc/authz" ) @@ -30,7 +30,7 @@ func (p *roleChecker) Authorized(ctx context.Context, _ string) error { func (p *roleChecker) checkRole(roleNames []string) error { if len(roleNames) == 0 { - return errorhelpers.ErrNoValidRole + return errox.NoValidRole } for _, roleName := range roleNames { @@ -39,5 +39,5 @@ func (p *roleChecker) checkRole(roleNames []string) error { } } - return errorhelpers.NewErrNotAuthorized(fmt.Sprintf("role %q is required", p.roleName)) + return errox.NewErrNotAuthorized(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 298f726c11f6a..e0fdfae214188 100644 --- a/pkg/grpc/authz/user/user.go +++ b/pkg/grpc/authz/user/user.go @@ -6,7 +6,7 @@ import ( "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authn" "github.com/stackrox/rox/pkg/grpc/authz" "github.com/stackrox/rox/pkg/grpc/authz/internal/permissioncheck" @@ -70,18 +70,18 @@ func (p *permissionChecker) checkGlobalSACPermissions(ctx context.Context, rootS return err } if !allowed { - return errorhelpers.NewErrNotAuthorized("scoped access") + return errox.NewErrNotAuthorized("scoped access") } return nil } func (p *permissionChecker) checkPermissions(rolePerms map[string]storage.Access) error { if rolePerms == nil { - return errorhelpers.ErrNoCredentials + return errox.NoCredentials } for _, requiredPerm := range p.requiredPermissions { if !evaluateAgainstPermissions(rolePerms, requiredPerm) { - return errorhelpers.NewErrNotAuthorized(fmt.Sprintf("%q for %q", requiredPerm.Access, requiredPerm.Resource)) + return errox.NewErrNotAuthorized(fmt.Sprintf("%q for %q", requiredPerm.Access, requiredPerm.Resource)) } } return nil diff --git a/pkg/grpc/authz/user/user_test.go b/pkg/grpc/authz/user/user_test.go index bd60a0552b135..c8d00e09de592 100644 --- a/pkg/grpc/authz/user/user_test.go +++ b/pkg/grpc/authz/user/user_test.go @@ -10,7 +10,7 @@ import ( "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/auth/permissions" "github.com/stackrox/rox/pkg/auth/permissions/utils" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/grpc/authn" "github.com/stackrox/rox/pkg/grpc/authn/mocks" "github.com/stackrox/rox/pkg/grpc/authz/internal/permissioncheck" @@ -56,7 +56,7 @@ func Test_permissionChecker_Authorized(t *testing.T) { { name: "no ID in context => error", ctx: context.Background(), - err: errorhelpers.ErrNoCredentials, + err: errox.NoCredentials, }, { name: "permissions equal access => no error", @@ -78,7 +78,7 @@ func Test_permissionChecker_Authorized(t *testing.T) { Resource: nsScopedResource, Access: storage.Access_READ_ACCESS, }}, ctx: sac.WithNoAccess(ctx), - err: errorhelpers.ErrNotAuthorized, + err: errox.NotAuthorized, }, { name: "built-in scoped authz check permissions", @@ -93,7 +93,7 @@ func Test_permissionChecker_Authorized(t *testing.T) { Resource: clusterScopedResource, Access: storage.Access_READ_WRITE_ACCESS, }}, ctx: sac.WithNoAccess(ctxWithNoPermissions), - err: errorhelpers.ErrNoCredentials, + err: errox.NoCredentials, }, { name: "plugin SAC check only global permissions", @@ -117,7 +117,7 @@ func Test_permissionChecker_Authorized(t *testing.T) { Resource: globalScopedResource, Access: storage.Access_READ_WRITE_ACCESS, }}, ctx: sac.WithNoAccess(sac.SetContextPluginScopedAuthzEnabled(ctx)), - err: errorhelpers.ErrNotAuthorized, + err: errox.NotAuthorized, }, { name: "plugin SAC check only global permissions", diff --git a/pkg/grpc/errors/interceptor.go b/pkg/grpc/errors/interceptor.go index a25ca2629ec81..7f420c4cf1e34 100644 --- a/pkg/grpc/errors/interceptor.go +++ b/pkg/grpc/errors/interceptor.go @@ -5,7 +5,7 @@ import ( "errors" "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" errox_grpc "github.com/stackrox/rox/pkg/errox/grpc" "github.com/stackrox/rox/pkg/logging" "google.golang.org/grpc" @@ -21,7 +21,7 @@ var ( // Note: this interceptor should ONLY be used in dev builds. func PanicOnInvariantViolationUnaryInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { resp, err := handler(ctx, req) - if errors.Is(err, errorhelpers.ErrInvariantViolation) { + if errors.Is(err, errox.InvariantViolation) { panic(err) } return resp, err @@ -31,7 +31,7 @@ func PanicOnInvariantViolationUnaryInterceptor(ctx context.Context, req interfac // Note: this interceptor should ONLY be used in dev builds. func PanicOnInvariantViolationStreamInterceptor(srv interface{}, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { err := handler(srv, ss) - if errors.Is(err, errorhelpers.ErrInvariantViolation) { + if errors.Is(err, errox.InvariantViolation) { panic(err) } return err diff --git a/pkg/grpc/errors/interceptor_test.go b/pkg/grpc/errors/interceptor_test.go index fc4d19114d963..ec811a5ccd3e7 100644 --- a/pkg/grpc/errors/interceptor_test.go +++ b/pkg/grpc/errors/interceptor_test.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/pkg/errors" - "github.com/stackrox/rox/pkg/errorhelpers" "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/logging" "github.com/stretchr/testify/assert" @@ -41,9 +40,9 @@ func TestErrorToGrpcCodeInterceptor(t *testing.T) { { name: "Error is one of types from pkg/errorhelpers (ErrNotFound etc.) -> map to correct gRPC code, preserve error message", handler: func(ctx context.Context, req interface{}) (interface{}, error) { - return "err", errors.Wrap(errorhelpers.ErrNotFound, "error message") + return "err", errors.Wrap(errox.NotFound, "error message") }, - resp: "err", err: status.Error(codes.NotFound, errors.Wrap(errorhelpers.ErrNotFound, "error message").Error()), + resp: "err", err: status.Error(codes.NotFound, errors.Wrap(errox.NotFound, "error message").Error()), }, { name: "Error is not a gRPC status error and not a known error type -> set error to internal", @@ -129,9 +128,9 @@ func TestErrorToGrpcCodeStreamInterceptor(t *testing.T) { { name: "Error is one of types from pkg/errorhelpers (ErrNotFound etc.) -> map to correct gRPC code, preserve error message", handler: func(srv interface{}, stream grpc.ServerStream) error { - return errors.Wrap(errorhelpers.ErrNotFound, "error message") + return errors.Wrap(errox.NotFound, "error message") }, - err: status.Error(codes.NotFound, errors.Wrap(errorhelpers.ErrNotFound, "error message").Error()), + err: status.Error(codes.NotFound, errors.Wrap(errox.NotFound, "error message").Error()), }, { name: "Error is not a gRPC status error and not a known error type -> set error to internal", @@ -173,7 +172,7 @@ func TestPanicOnInvariantViolationUnaryInterceptor(t *testing.T) { { name: "Error is ErrInvariantViolation -> panic", handler: func(ctx context.Context, req interface{}) (interface{}, error) { - return "err", errorhelpers.ErrInvariantViolation + return "err", errox.InvariantViolation }, resp: nil, err: nil, panics: true, @@ -181,9 +180,9 @@ func TestPanicOnInvariantViolationUnaryInterceptor(t *testing.T) { { name: "Error is not ErrInvariantViolation -> do nothing, just pass through", handler: func(ctx context.Context, req interface{}) (interface{}, error) { - return "err", errorhelpers.ErrNoCredentials + return "err", errox.NoCredentials }, - resp: "err", err: errorhelpers.ErrNoCredentials, + resp: "err", err: errox.NoCredentials, panics: false, }, } @@ -222,16 +221,16 @@ func TestPanicOnInvariantViolationStreamInterceptor(t *testing.T) { }, "Error is ErrInvariantViolation -> panic": { handler: func(srv interface{}, stream grpc.ServerStream) error { - return errorhelpers.NewErrInvariantViolation("some explanation") + return errox.NewErrInvariantViolation("some explanation") }, err: nil, panics: true, }, "Error is not ErrInvariantViolation -> do nothing, just pass through": { handler: func(srv interface{}, stream grpc.ServerStream) error { - return errorhelpers.ErrNotFound + return errox.NotFound }, - err: errorhelpers.ErrNotFound, + err: errox.NotFound, panics: false, }, } diff --git a/pkg/grpc/requestinfo/requestinfo.go b/pkg/grpc/requestinfo/requestinfo.go index 63b98b386a0b0..be10648653cca 100644 --- a/pkg/grpc/requestinfo/requestinfo.go +++ b/pkg/grpc/requestinfo/requestinfo.go @@ -22,7 +22,7 @@ import ( "github.com/stackrox/rox/pkg/cryptoutils" "github.com/stackrox/rox/pkg/devbuild" "github.com/stackrox/rox/pkg/env" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/logging" "github.com/stackrox/rox/pkg/netutil/pipeconn" "github.com/stackrox/rox/pkg/stringutils" @@ -240,7 +240,7 @@ func (h *Handler) UpdateContextForGRPC(ctx context.Context) (context.Context, er // This should only happen if someone is trying to spoof a RequestInfo. Log, but don't return any details in the // error message. log.Errorf("error extracting RequestInfo from incoming metadata: %v", err) - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "malformed request") + return nil, errors.Wrap(errox.InvalidArgs, "malformed request") } tlsState := tlsStateFromContext(ctx) diff --git a/pkg/httputil/error_test.go b/pkg/httputil/error_test.go index 14ac8959749f2..b5558be18c972 100644 --- a/pkg/httputil/error_test.go +++ b/pkg/httputil/error_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/pkg/errors" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stretchr/testify/assert" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -51,7 +51,7 @@ func TestWriteError(t *testing.T) { }, { name: "Known internal error yields appropriate status in response header", - incomingErr: errors.Wrap(errorhelpers.ErrNotFound, "Origin: known internal error"), + incomingErr: errors.Wrap(errox.NotFound, "Origin: known internal error"), expectedStatus: 404, }, { diff --git a/pkg/images/enricher/util.go b/pkg/images/enricher/util.go index fc2ee1957993d..b0be9bfd51273 100644 --- a/pkg/images/enricher/util.go +++ b/pkg/images/enricher/util.go @@ -5,7 +5,7 @@ import ( "github.com/pkg/errors" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/images/types" "github.com/stackrox/rox/pkg/images/utils" ) @@ -13,11 +13,11 @@ import ( // EnrichImageByName takes an image name, and returns the corresponding enriched image. func EnrichImageByName(ctx context.Context, enricher ImageEnricher, enrichmentCtx EnrichmentContext, name string) (*storage.Image, error) { if name == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "image name must be specified") + return nil, errors.Wrap(errox.InvalidArgs, "image name must be specified") } containerImage, err := utils.GenerateImageFromString(name) if err != nil { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, err.Error()) + return nil, errors.Wrap(errox.InvalidArgs, err.Error()) } img := types.ToImage(containerImage) diff --git a/pkg/k8srbac/subjects.go b/pkg/k8srbac/subjects.go index e912bc1a7533b..543a91486450d 100644 --- a/pkg/k8srbac/subjects.go +++ b/pkg/k8srbac/subjects.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/logging" "github.com/stackrox/rox/pkg/stringutils" ) @@ -96,5 +96,5 @@ func GetSubject(subjectName string, bindings []*storage.K8SRoleBinding) (*storag } } } - return nil, false, errors.Wrapf(errorhelpers.ErrNotFound, "subject not found: %s", subjectName) + return nil, false, errors.Wrapf(errox.NotFound, "subject not found: %s", subjectName) } diff --git a/pkg/printers/junit.go b/pkg/printers/junit.go index 18a83be6a2f81..b3276df4085b7 100644 --- a/pkg/printers/junit.go +++ b/pkg/printers/junit.go @@ -5,7 +5,7 @@ import ( "fmt" "io" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/gjson" "github.com/stackrox/rox/pkg/set" ) @@ -143,12 +143,12 @@ func validateJUnitSuiteData(testCaseNames, failedTestCaseNames, failedTestCaseEr amountSkippedTestCases := len(skippedTestCaseNames) if amountTestCases < amountFailedTestCases+amountSkippedTestCases { - return errorhelpers.NewErrInvariantViolation(fmt.Sprintf("%d failed test cases are greater "+ + return errox.NewErrInvariantViolation(fmt.Sprintf("%d failed test cases are greater "+ "than %d overall test cases", amountTestCases, amountFailedTestCases)) } if len(failedTestCaseNames) != len(failedTestCaseErrorMessages) { - return errorhelpers.NewErrInvariantViolation(fmt.Sprintf("%d failed test cases and %d error "+ + return errox.NewErrInvariantViolation(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, errorhelpers.NewErrInvariantViolation(fmt.Sprintf("duplicate failed test "+ + return nil, errox.NewErrInvariantViolation(fmt.Sprintf("duplicate failed test "+ "case %q found", name)) } failedTestCaseMap[name] = failedTestCaseErrorMessages[i] diff --git a/pkg/printers/junit_test.go b/pkg/printers/junit_test.go index 5f5c2055a65f6..d0a6b3eb668a9 100644 --- a/pkg/printers/junit_test.go +++ b/pkg/printers/junit_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/joshdk/go-junit" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -202,20 +202,20 @@ func TestValidateJUnitSuiteData(t *testing.T) { failedTcNames: []string{"a", "b"}, failedTcErrMsg: []string{"a", "b"}, shouldFail: true, - error: errorhelpers.ErrInvariantViolation, + error: errox.InvariantViolation, }, "should fail if overall test cases < skipped test cases": { tcNames: []string{"a"}, skippedTcNames: []string{"a", "b"}, shouldFail: true, - error: errorhelpers.ErrInvariantViolation, + error: errox.InvariantViolation, }, "should fail if failed test cases != error messages": { tcNames: []string{"a", "b", "c"}, failedTcNames: []string{"a", "b"}, failedTcErrMsg: []string{"a", "b", "c"}, shouldFail: true, - error: errorhelpers.ErrInvariantViolation, + error: errox.InvariantViolation, }, } @@ -253,7 +253,7 @@ func TestCreateFailedTestCaseMap(t *testing.T) { failedTc: []string{"a", "b", "b", "c"}, failedTcErrMsg: []string{"aa", "bb", "cc", "dd"}, shouldFail: true, - error: errorhelpers.ErrInvariantViolation, + error: errox.InvariantViolation, expectedOutput: nil, }, } diff --git a/pkg/rocksdb/crud/unique_key_crud.go b/pkg/rocksdb/crud/unique_key_crud.go index abfd2a1dd9522..6e9dd934a9355 100644 --- a/pkg/rocksdb/crud/unique_key_crud.go +++ b/pkg/rocksdb/crud/unique_key_crud.go @@ -6,7 +6,7 @@ import ( "github.com/gogo/protobuf/proto" "github.com/pkg/errors" "github.com/stackrox/rox/pkg/db" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/rocksdb" "github.com/stackrox/rox/pkg/sync" ) @@ -36,7 +36,7 @@ func (c *uniqueKeyCRUD) checkForConflicts(newID []byte, newMsg proto.Message) er return nil } if bytes.Equal(newUniqueKey, c.uniqueKeyFunc(msg)) { - return errors.Wrapf(errorhelpers.ErrAlreadyExists, "unique key conflict between %s and existing %s on value: %s", newID, id, newUniqueKey) + return errors.Wrapf(errox.AlreadyExists, "unique key conflict between %s and existing %s on value: %s", newID, id, newUniqueKey) } return nil }) diff --git a/roxctl/central/db/restore/v2.go b/roxctl/central/db/restore/v2.go index 01d901182f4fa..42126eb45fa50 100644 --- a/roxctl/central/db/restore/v2.go +++ b/roxctl/central/db/restore/v2.go @@ -10,7 +10,7 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" v1 "github.com/stackrox/rox/generated/api/v1" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/httputil" "github.com/stackrox/rox/pkg/ioutils" pkgCommon "github.com/stackrox/rox/pkg/roxctl/common" @@ -76,10 +76,10 @@ func validate(cbr *cobra.Command, args []string) error { return cbr.Usage() } if len(args) > 1 { - return errors.WithMessagef(errorhelpers.ErrInvalidArgs, "too many positional arguments (%d given)", len(args)) + return errors.WithMessagef(errox.InvalidArgs, "too many positional arguments (%d given)", len(args)) } if file, _ := cbr.Flags().GetString("file"); file != "" { - return errors.WithMessage(errorhelpers.ErrInvalidArgs, "legacy --file flag must not be used in conjunction with a positional argument") + return errors.WithMessage(errox.InvalidArgs, "legacy --file flag must not be used in conjunction with a positional argument") } return nil } @@ -97,7 +97,7 @@ func (cmd *centralDbRestoreCommand) construct(cbr *cobra.Command, args []string) func (cmd *centralDbRestoreCommand) validate() error { if cmd.file == "" { - return errors.WithMessage(errorhelpers.ErrInvalidArgs, "file to restore from must be specified") + return errors.WithMessage(errox.InvalidArgs, "file to restore from must be specified") } return nil } diff --git a/roxctl/central/generate/generate.go b/roxctl/central/generate/generate.go index f83e02a83b257..088f4f1655f1f 100644 --- a/roxctl/central/generate/generate.go +++ b/roxctl/central/generate/generate.go @@ -14,7 +14,7 @@ import ( "github.com/stackrox/rox/pkg/buildinfo" "github.com/stackrox/rox/pkg/certgen" "github.com/stackrox/rox/pkg/env" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/features" "github.com/stackrox/rox/pkg/images/defaults" "github.com/stackrox/rox/pkg/mtls" @@ -185,7 +185,7 @@ func createBundle(logger environment.Logger, config renderer.Config) (*zip.Wrapp flavor, err := defaults.GetImageFlavorByName(config.K8sConfig.ImageFlavorName, buildinfo.ReleaseBuild) if err != nil { - return nil, fmt.Errorf("%w: '--%s': %v", errorhelpers.ErrInvalidArgs, flags.ImageDefaultsFlagName, err) + return nil, fmt.Errorf("%w: '--%s': %v", errox.InvalidArgs, flags.ImageDefaultsFlagName, err) } files, err := renderer.Render(config, flavor) diff --git a/roxctl/cluster/delete/delete.go b/roxctl/cluster/delete/delete.go index c383f2bdaa2ed..a8b79ec6ac4e1 100644 --- a/roxctl/cluster/delete/delete.go +++ b/roxctl/cluster/delete/delete.go @@ -9,7 +9,7 @@ import ( "github.com/spf13/cobra" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/roxctl/common/environment" "github.com/stackrox/rox/roxctl/common/flags" ) @@ -52,7 +52,7 @@ func (cmd *clusterDeleteCommand) Construct(args []string, cbr *cobra.Command) er func (cmd *clusterDeleteCommand) Validate() error { if cmd.name == "" { - return errorhelpers.ErrInvalidArgs + return errox.InvalidArgs } return nil } @@ -79,7 +79,7 @@ func (cmd *clusterDeleteCommand) Delete() error { } if cluster == nil { cmd.env.Logger().ErrfLn("Cluster with name %q not found. Valid clusters are [ %s ]", cmd.name, strings.Join(validClusters, " | ")) - return errorhelpers.ErrNotFound + return errox.NotFound } ctx, cancel := context.WithTimeout(context.Background(), cmd.timeout) diff --git a/roxctl/cluster/delete/delete_test.go b/roxctl/cluster/delete/delete_test.go index 5b5958d1132b6..d4ebd360a9eda 100644 --- a/roxctl/cluster/delete/delete_test.go +++ b/roxctl/cluster/delete/delete_test.go @@ -11,7 +11,7 @@ import ( "github.com/spf13/cobra" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/utils" "github.com/stackrox/rox/roxctl/common/environment/mocks" "github.com/stretchr/testify/suite" @@ -103,7 +103,7 @@ func (c *clusterDeleteTestSuite) TestCommandRequiresName() { err := cbr.Execute() c.Require().Error(err) - c.Assert().ErrorIs(err, errorhelpers.ErrInvalidArgs) + c.Assert().ErrorIs(err, errox.InvalidArgs) } func (c *clusterDeleteTestSuite) TestCommandFailsIfClusterNotFound() { @@ -115,7 +115,7 @@ func (c *clusterDeleteTestSuite) TestCommandFailsIfClusterNotFound() { err := cbr.Execute() c.Require().Error(err) - c.Assert().ErrorIs(err, errorhelpers.ErrNotFound) + c.Assert().ErrorIs(err, errox.NotFound) } func (c *clusterDeleteTestSuite) TestConstructSetsTimeoutFlag() { diff --git a/roxctl/common/printer/jsonprinter_factory_test.go b/roxctl/common/printer/jsonprinter_factory_test.go index 395d162f81403..6518288a59f59 100644 --- a/roxctl/common/printer/jsonprinter_factory_test.go +++ b/roxctl/common/printer/jsonprinter_factory_test.go @@ -3,7 +3,7 @@ package printer import ( "testing" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -23,7 +23,7 @@ func TestJSONPrinterFactory_CreatePrinter(t *testing.T) { j: &JSONPrinterFactory{}, format: "junit", shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, } diff --git a/roxctl/common/printer/junitprinter_factory_test.go b/roxctl/common/printer/junitprinter_factory_test.go index e8bf4750ecdcd..e71e4704de816 100644 --- a/roxctl/common/printer/junitprinter_factory_test.go +++ b/roxctl/common/printer/junitprinter_factory_test.go @@ -3,7 +3,7 @@ package printer import ( "testing" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/printers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -30,7 +30,7 @@ func TestJUnitPrinterFactory_CreatePrinter(t *testing.T) { "should fail if validate fails": { j: &JUnitPrinterFactory{}, shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, "should fail if output format is invalid": { j: &JUnitPrinterFactory{ @@ -43,7 +43,7 @@ func TestJUnitPrinterFactory_CreatePrinter(t *testing.T) { }, format: "json", shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, } @@ -79,7 +79,7 @@ func TestJUnitPrinterFactory_Validate(t *testing.T) { }, "should return an invalid args error if suite name is not set": { shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, "should return an invariant violation error if json path map is invalid": { suiteName: "testsuite", @@ -87,7 +87,7 @@ func TestJUnitPrinterFactory_Validate(t *testing.T) { printers.JUnitTestCasesExpressionKey: "test", }, shouldFail: true, - error: errorhelpers.ErrInvariantViolation, + error: errox.InvariantViolation, }, } diff --git a/roxctl/common/printer/objectprinter_factory_test.go b/roxctl/common/printer/objectprinter_factory_test.go index cb30ea905860b..5423049a0cff9 100644 --- a/roxctl/common/printer/objectprinter_factory_test.go +++ b/roxctl/common/printer/objectprinter_factory_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/spf13/cobra" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -20,7 +20,7 @@ func TestNewObjectPrinterFactory(t *testing.T) { "should fail when no CustomPrinterFactory is added": { defaultFormat: "table", shouldFail: true, - error: errorhelpers.ErrInvariantViolation, + error: errox.InvariantViolation, printerFactory: []CustomPrinterFactory{nil}, }, "should not fail if format is supported by registered CustomPrinterFactory": { @@ -34,13 +34,13 @@ func TestNewObjectPrinterFactory(t *testing.T) { "should fail if default output format is not supported by registered CustomPrinterFactory": { defaultFormat: "table", shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, printerFactory: []CustomPrinterFactory{NewJSONPrinterFactory(false, false)}, }, "should fail if duplicate CustomPrinterFactory is being registered": { defaultFormat: "json", shouldFail: true, - error: errorhelpers.ErrInvariantViolation, + error: errox.InvariantViolation, printerFactory: []CustomPrinterFactory{NewJSONPrinterFactory(false, false), NewJSONPrinterFactory(false, false)}, }, } @@ -104,7 +104,7 @@ func TestObjectPrinterFactory_validateOutputFormat(t *testing.T) { }, }, shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, } @@ -160,7 +160,7 @@ func TestObjectPrinterFactory_CreatePrinter(t *testing.T) { "json": NewJSONPrinterFactory(false, false), }, }, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, } @@ -201,7 +201,7 @@ func TestObjectPrinterFactory_validate(t *testing.T) { OutputFormat: "table", }, shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, "should fail with unsupported OutputFormat": { o: ObjectPrinterFactory{ @@ -211,7 +211,7 @@ func TestObjectPrinterFactory_validate(t *testing.T) { OutputFormat: "table", }, shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, } diff --git a/roxctl/common/printer/tabularprinter_factory_test.go b/roxctl/common/printer/tabularprinter_factory_test.go index d9c80e7c2fd08..ab89958070bd9 100644 --- a/roxctl/common/printer/tabularprinter_factory_test.go +++ b/roxctl/common/printer/tabularprinter_factory_test.go @@ -3,7 +3,7 @@ package printer import ( "testing" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -23,12 +23,12 @@ func TestTabularPrinterFactory_CreatePrinter(t *testing.T) { t: &TabularPrinterFactory{HeaderAsComment: true, NoHeader: true}, format: "csv", shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, "should fail with invalid format": { t: &TabularPrinterFactory{}, shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, } @@ -62,7 +62,7 @@ func TestTabularPrinterFactory_Validate(t *testing.T) { HeaderAsComment: true, }, shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, "should fail with columns to merge not matching header": { t: &TabularPrinterFactory{ @@ -70,7 +70,7 @@ func TestTabularPrinterFactory_Validate(t *testing.T) { columnsToMerge: []string{"a", "d", "c", "e"}, }, shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, } diff --git a/roxctl/deployment/check/check_test.go b/roxctl/deployment/check/check_test.go index 1bb9ceacda471..98de564aff193 100644 --- a/roxctl/deployment/check/check_test.go +++ b/roxctl/deployment/check/check_test.go @@ -14,7 +14,7 @@ import ( "github.com/spf13/cobra" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/utils" "github.com/stackrox/rox/roxctl/common/environment" "github.com/stackrox/rox/roxctl/common/environment/mocks" @@ -313,7 +313,7 @@ func (d *deployCheckTestSuite) TestConstruct() { timeout: expectedTimeout, f: invalidObjectPrinterFactory, shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, } @@ -346,7 +346,7 @@ func (d *deployCheckTestSuite) TestValidate() { "should fail with non existing file name": { file: "invalidfile", shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, } diff --git a/roxctl/image/scan/scan_test.go b/roxctl/image/scan/scan_test.go index c101d7ec21153..65bffdea99f94 100644 --- a/roxctl/image/scan/scan_test.go +++ b/roxctl/image/scan/scan_test.go @@ -15,7 +15,7 @@ import ( "github.com/spf13/cobra" v1 "github.com/stackrox/rox/generated/api/v1" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/utils" "github.com/stackrox/rox/roxctl/common/environment" "github.com/stackrox/rox/roxctl/common/environment/mocks" @@ -305,7 +305,7 @@ func (s *imageScanTestSuite) TestConstruct() { "invalid printer factory should return an error": { printerFactory: invalidObjPrinterFactory, shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, } @@ -398,13 +398,13 @@ func (s *imageScanTestSuite) TestValidate() { }, "invalid image name should result in an error": { image: "c:", - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, "wrong legacy output format should result in an error when new output format IS NOT used": { image: s.defaultImageScanCommand.image, legacyFormat: "table", shouldFail: true, - error: errorhelpers.ErrInvalidArgs, + error: errox.InvalidArgs, }, "wrong legacy output format should NOT result in an error when new output format IS used": { image: s.defaultImageScanCommand.image, diff --git a/sensor/common/certdistribution/service_impl.go b/sensor/common/certdistribution/service_impl.go index 29e4ec7bdafff..69cea085a1bca 100644 --- a/sensor/common/certdistribution/service_impl.go +++ b/sensor/common/certdistribution/service_impl.go @@ -11,7 +11,7 @@ import ( "github.com/stackrox/rox/generated/internalapi/sensor" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/centralsensor" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" "github.com/stackrox/rox/pkg/fileutils" "github.com/stackrox/rox/pkg/grpc/authn" "github.com/stackrox/rox/pkg/grpc/authz/allow" @@ -72,18 +72,18 @@ func (s *service) AuthFuncOverride(ctx context.Context, fullMethodName string) ( func (s *service) verifyToken(ctx context.Context, token string, expectedSubject string) error { parsedToken, err := jwt.ParseSigned(token) if err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid JWT: %s", err) + return errors.Wrapf(errox.InvalidArgs, "invalid JWT: %s", err) } var claims map[string]interface{} if err := parsedToken.UnsafeClaimsWithoutVerification(&claims); err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "unparseable claims in token: %s", err) + return errors.Wrapf(errox.InvalidArgs, "unparseable claims in token: %s", err) } if sub, ok := claims["sub"].(string); !ok { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "non-string subject claim in token") + return errors.Wrap(errox.InvalidArgs, "non-string subject claim in token") } else if sub != expectedSubject { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "unexpected subject %s", sub) + return errors.Wrapf(errox.InvalidArgs, "unexpected subject %s", sub) } // Now, create the token review @@ -96,7 +96,7 @@ func (s *service) verifyToken(ctx context.Context, token string, expectedSubject reviewWithStatus, err := s.k8sAuthnClient.TokenReviews().Create(ctx, review, metav1.CreateOptions{}) if err != nil { - return errors.Wrapf(errorhelpers.ErrInvalidArgs, "failed to authenticate with Kubernetes API server: %s", err) + return errors.Wrapf(errox.InvalidArgs, "failed to authenticate with Kubernetes API server: %s", err) } reviewStatus := reviewWithStatus.Status @@ -120,7 +120,7 @@ func (s *service) loadCertsForService(serviceName string) (certPEM, keyPEM strin if allExist, err := fileutils.AllExist(certFileName, keyFileName); err != nil { return "", "", errors.New("failed to check for existence of certificates") } else if !allExist { - return "", "", errors.Wrapf(errorhelpers.ErrNotFound, "no set of certificates for service %s is available", serviceName) + return "", "", errors.Wrapf(errox.NotFound, "no set of certificates for service %s is available", serviceName) } certBytes, err := os.ReadFile(certFileName) @@ -150,7 +150,7 @@ func (s *service) verifyRequestViaIdentity(requestingServiceIdentity *storage.Se func (s *service) verifyRequestViaServiceAccountToken(ctx context.Context, serviceName, token string) error { if token == "" { - return errors.Wrap(errorhelpers.ErrInvalidArgs, "no token specified") + return errors.Wrap(errox.InvalidArgs, "no token specified") } // This API is rate limit such that an untrusted user cannot get us to DDoS the Kubernetes API server. @@ -168,7 +168,7 @@ func (s *service) verifyRequestViaServiceAccountToken(ctx context.Context, servi func (s *service) FetchCertificate(ctx context.Context, req *sensor.FetchCertificateRequest) (*sensor.FetchCertificateResponse, error) { serviceName := services.ServiceTypeToSlugName(req.GetServiceType()) if serviceName == "" { - return nil, errors.Wrapf(errorhelpers.ErrInvalidArgs, "invalid service type %s", req.GetServiceType()) + return nil, errors.Wrapf(errox.InvalidArgs, "invalid service type %s", req.GetServiceType()) } var requestingServiceIdentity *storage.ServiceIdentity diff --git a/sensor/common/deployment/service_impl.go b/sensor/common/deployment/service_impl.go index 3926cefb0b433..aae191a5f1831 100644 --- a/sensor/common/deployment/service_impl.go +++ b/sensor/common/deployment/service_impl.go @@ -7,7 +7,7 @@ import ( "github.com/pkg/errors" "github.com/stackrox/rox/generated/internalapi/sensor" "github.com/stackrox/rox/generated/storage" - "github.com/stackrox/rox/pkg/errorhelpers" + "github.com/stackrox/rox/pkg/errox" grpcPkg "github.com/stackrox/rox/pkg/grpc" "github.com/stackrox/rox/pkg/grpc/authz/idcheck" "github.com/stackrox/rox/sensor/common/store" @@ -51,19 +51,19 @@ func (s *serviceImpl) AuthFuncOverride(ctx context.Context, fullMethodName strin func (s *serviceImpl) GetDeploymentForPod(ctx context.Context, req *sensor.GetDeploymentForPodRequest) (*storage.Deployment, error) { if req.GetPodName() == "" || req.GetNamespace() == "" { - return nil, errors.Wrap(errorhelpers.ErrInvalidArgs, "pod namespace and pod name must be provided") + return nil, errors.Wrap(errox.InvalidArgs, "pod namespace and pod name must be provided") } pod := s.pods.GetByName(req.GetPodName(), req.GetNamespace()) if pod == nil { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, + return nil, errors.Wrapf(errox.NotFound, "namespace/%s/pods/%s not found", req.GetNamespace(), req.GetPodName()) } dep := s.deployments.Get(pod.GetDeploymentId()) if dep == nil { - return nil, errors.Wrapf(errorhelpers.ErrNotFound, + return nil, errors.Wrapf(errox.NotFound, "no containing deployment found for namespace/%s/pods/%s", req.GetNamespace(), req.GetPodName()) }