From a8c75b5a3341dc639f6229eeeaf35d14dec33e72 Mon Sep 17 00:00:00 2001 From: andream16 Date: Tue, 5 Nov 2024 11:34:10 +0000 Subject: [PATCH] Replacing fmt.Errorf and error declarations with go-errors's errors.Errorf. --- sdk/component/conf.go | 22 ++++++------ sdk/component/enricher.go | 9 ++--- sdk/component/env.go | 12 +++---- sdk/component/filter.go | 9 ++--- .../storer/local/sqlite/export_test.go | 8 ++--- .../internal/storer/local/sqlite/sqlite.go | 34 +++++++++---------- sdk/component/internal/storer/storer.go | 2 +- sdk/component/internal/uuid/uuid.go | 5 ++- sdk/component/logger.go | 5 +-- sdk/component/reporter.go | 7 ++-- sdk/component/runner.go | 15 ++++---- sdk/component/scanner.go | 9 ++--- sdk/component/storer.go | 6 ++-- sdk/component/target.go | 5 +-- 14 files changed, 76 insertions(+), 72 deletions(-) diff --git a/sdk/component/conf.go b/sdk/component/conf.go index 98799adbd..676761ea0 100644 --- a/sdk/component/conf.go +++ b/sdk/component/conf.go @@ -3,6 +3,8 @@ package component import ( "fmt" + "github.com/go-errors/errors" + "github.com/smithy-security/smithy/sdk" "github.com/smithy-security/smithy/sdk/component/internal/uuid" ) @@ -199,41 +201,41 @@ func newRunnerConfig() (*RunnerConfig, error) { // --- BEGIN - BASIC ENV - BEGIN --- panicHandler, err := NewDefaultPanicHandler() if err != nil { - return nil, fmt.Errorf("could not construct panic handler: %w", err) + return nil, errors.Errorf("could not construct panic handler: %w", err) } componentName, err := fromEnvOrDefault(envVarKeyComponentName, "", withFallbackToDefaultOnError(true)) if err != nil { - return nil, fmt.Errorf("could not lookup environment for '%s': %w", envVarKeyComponentName, err) + return nil, errors.Errorf("could not lookup environment for '%s': %w", envVarKeyComponentName, err) } instanceIDStr, err := fromEnvOrDefault(envVarKeyInstanceID, "", withFallbackToDefaultOnError(true)) if err != nil { - return nil, fmt.Errorf("could not lookup environment for '%s': %w", envVarKeyInstanceID, err) + return nil, errors.Errorf("could not lookup environment for '%s': %w", envVarKeyInstanceID, err) } instanceID, err := uuid.Parse(instanceIDStr) if err != nil { - return nil, fmt.Errorf("could not parse instance ID '%s': %w", instanceIDStr, err) + return nil, errors.Errorf("could not parse instance ID '%s': %w", instanceIDStr, err) } // --- END - BASIC ENV - END --- // --- BEGIN - LOGGING ENV - BEGIN --- logLevel, err := fromEnvOrDefault(envVarKeyLoggingLogLevel, logLevelDebug.String(), withFallbackToDefaultOnError(true)) if err != nil { - return nil, fmt.Errorf("could not lookup environment for '%s': %w", envVarKeyLoggingLogLevel, err) + return nil, errors.Errorf("could not lookup environment for '%s': %w", envVarKeyLoggingLogLevel, err) } logger, err := newDefaultLogger(RunnerConfigLoggingLevel(logLevel)) if err != nil { - return nil, fmt.Errorf("could not initialised default logger for '%s': %w", envVarKeyLoggingLogLevel, err) + return nil, errors.Errorf("could not initialised default logger for '%s': %w", envVarKeyLoggingLogLevel, err) } // --- END - LOGGING ENV - END --- // --- BEGIN - STORER ENV - BEGIN --- st, err := fromEnvOrDefault(envVarKeyBackendStoreType, "", withFallbackToDefaultOnError(true)) if err != nil { - return nil, fmt.Errorf("could not lookup environment for '%s': %w", envVarKeyBackendStoreType, err) + return nil, errors.Errorf("could not lookup environment for '%s': %w", envVarKeyBackendStoreType, err) } conf := &RunnerConfig{ @@ -250,7 +252,7 @@ func newRunnerConfig() (*RunnerConfig, error) { if st != "" { var storageType = storeType(st) if !isAllowedStoreType(storageType) { - return nil, fmt.Errorf("invalid store type for '%s': %w", envVarKeyBackendStoreType, err) + return nil, errors.Errorf("invalid store type for '%s': %w", envVarKeyBackendStoreType, err) } conf.storerConfig.storeType = storageType @@ -261,13 +263,13 @@ func newRunnerConfig() (*RunnerConfig, error) { withFallbackToDefaultOnError(true), ) if err != nil { - return nil, fmt.Errorf("could not lookup environment for '%s': %w", envVarKeyBackendStoreDSN, err) + return nil, errors.Errorf("could not lookup environment for '%s': %w", envVarKeyBackendStoreDSN, err) } conf.storerConfig.dbDSN = dbDSN conf.storerConfig.store, err = newStorer(conf.storerConfig) if err != nil { - return nil, fmt.Errorf("could not initialise store for '%s': %w", envVarKeyBackendStoreType, err) + return nil, errors.Errorf("could not initialise store for '%s': %w", envVarKeyBackendStoreType, err) } } // --- END - STORER ENV - END --- diff --git a/sdk/component/enricher.go b/sdk/component/enricher.go index ca1b6b6e2..356e2ac91 100644 --- a/sdk/component/enricher.go +++ b/sdk/component/enricher.go @@ -2,7 +2,8 @@ package component import ( "context" - "fmt" + + "github.com/go-errors/errors" ) // RunEnricher runs an enricher after initialising the run context. @@ -28,7 +29,7 @@ func RunEnricher(ctx context.Context, enricher Enricher, opts ...RunnerOption) e findings, err := store.Read(ctx, instanceID) if err != nil { logger.With(logKeyError, err.Error()).Error("reading step failed") - return fmt.Errorf("could not read: %w", err) + return errors.Errorf("could not read: %w", err) } logger = logger.With(logKeyNumParsedFindings, len(findings)) @@ -38,7 +39,7 @@ func RunEnricher(ctx context.Context, enricher Enricher, opts ...RunnerOption) e enrichedFindings, err := enricher.Annotate(ctx, findings) if err != nil { logger.With(logKeyError, err.Error()).Error("enricher step failed") - return fmt.Errorf("could not enricher: %w", err) + return errors.Errorf("could not enricher: %w", err) } logger = logger.With(logKeyNumEnrichedFindings, len(enrichedFindings)) @@ -47,7 +48,7 @@ func RunEnricher(ctx context.Context, enricher Enricher, opts ...RunnerOption) e if err := store.Update(ctx, instanceID, enrichedFindings); err != nil { logger.With(logKeyError, err.Error()).Error("updating step failed") - return fmt.Errorf("could not update: %w", err) + return errors.Errorf("could not update: %w", err) } logger.Debug("updated step completed!") diff --git a/sdk/component/env.go b/sdk/component/env.go index d839582de..c8fad30d2 100644 --- a/sdk/component/env.go +++ b/sdk/component/env.go @@ -1,13 +1,13 @@ package component import ( - "errors" - "fmt" "net/url" "os" "strconv" "time" + "github.com/go-errors/errors" + "github.com/smithy-security/smithy/sdk/component/internal/uuid" ) @@ -70,14 +70,14 @@ func fromEnvOrDefault[T parseableEnvTypes](envVar string, defaultVal T, opts ... parseOpts := &defaultEnvParseOptions for _, opt := range opts { if err := opt(parseOpts); err != nil { - return dest, fmt.Errorf("option error: %w", err) + return dest, errors.Errorf("option error: %w", err) } } envStr := parseOpts.envLoader(envVar) if envStr == "" { if !parseOpts.defaultOnError { - return dest, fmt.Errorf("required env variable '%s' not found", envVar) + return dest, errors.Errorf("required env variable '%s' not found", envVar) } return defaultVal, nil } @@ -115,12 +115,12 @@ func fromEnvOrDefault[T parseableEnvTypes](envVar string, defaultVal T, opts ... return defaultVal, nil } - return dest, fmt.Errorf("failed to parse env %s to %T: %v", envVar, dest, err) + return dest, errors.Errorf("failed to parse env %s to %T: %v", envVar, dest, err) } dest, ok := v.(T) if !ok { - return dest, fmt.Errorf("failed to cast env %s to %T", envVar, dest) + return dest, errors.Errorf("failed to cast env %s to %T", envVar, dest) } return dest, nil diff --git a/sdk/component/filter.go b/sdk/component/filter.go index c99590960..6c2c71bea 100644 --- a/sdk/component/filter.go +++ b/sdk/component/filter.go @@ -2,7 +2,8 @@ package component import ( "context" - "fmt" + + "github.com/go-errors/errors" ) // RunFilter runs a filter after initialising the run context. @@ -28,7 +29,7 @@ func RunFilter(ctx context.Context, filter Filter, opts ...RunnerOption) error { findings, err := store.Read(ctx, instanceID) if err != nil { logger.With(logKeyError, err.Error()).Error("reading step failed") - return fmt.Errorf("could not read: %w", err) + return errors.Errorf("could not read: %w", err) } logger = logger.With(logKeyNumParsedFindings, len(findings)) @@ -39,7 +40,7 @@ func RunFilter(ctx context.Context, filter Filter, opts ...RunnerOption) error { switch { case err != nil: logger.With(logKeyError, err.Error()).Error("filter step failed") - return fmt.Errorf("could not filter: %w", err) + return errors.Errorf("could not filter: %w", err) case !ok: logger.Debug("no findings were filtered, returning") return nil @@ -51,7 +52,7 @@ func RunFilter(ctx context.Context, filter Filter, opts ...RunnerOption) error { if err := store.Update(ctx, instanceID, filteredFindings); err != nil { logger.With(logKeyError, err.Error()).Error("updating step failed") - return fmt.Errorf("could not update: %w", err) + return errors.Errorf("could not update: %w", err) } logger.Debug("updated step completed!") diff --git a/sdk/component/internal/storer/local/sqlite/export_test.go b/sdk/component/internal/storer/local/sqlite/export_test.go index a83aff129..02fcc135d 100644 --- a/sdk/component/internal/storer/local/sqlite/export_test.go +++ b/sdk/component/internal/storer/local/sqlite/export_test.go @@ -1,8 +1,6 @@ package sqlite -import ( - "fmt" -) +import "github.com/go-errors/errors" // CreateTable is used to create a table in testing settings. func (m *manager) CreateTable() error { @@ -16,11 +14,11 @@ func (m *manager) CreateTable() error { ); `) if err != nil { - return fmt.Errorf("could not prepare statement for creating table: %w", err) + return errors.Errorf("could not prepare statement for creating table: %w", err) } if _, err := stmt.Exec(); err != nil { - return fmt.Errorf("could not create table: %w", err) + return errors.Errorf("could not create table: %w", err) } return stmt.Close() diff --git a/sdk/component/internal/storer/local/sqlite/sqlite.go b/sdk/component/internal/storer/local/sqlite/sqlite.go index dc742c720..8af26a0d3 100644 --- a/sdk/component/internal/storer/local/sqlite/sqlite.go +++ b/sdk/component/internal/storer/local/sqlite/sqlite.go @@ -4,10 +4,10 @@ import ( "context" "database/sql" "encoding/json" - "errors" "fmt" "time" + "github.com/go-errors/errors" "github.com/jonboulle/clockwork" _ "github.com/mattn/go-sqlite3" "google.golang.org/protobuf/encoding/protojson" @@ -72,7 +72,7 @@ func NewManager(dsn string, opts ...managerOption) (*manager, error) { db, err := sql.Open("sqlite3", dsn) if err != nil { - return nil, fmt.Errorf("could not open sqlite db: %w", err) + return nil, errors.Errorf("could not open sqlite db: %w", err) } mgr := &manager{ @@ -82,7 +82,7 @@ func NewManager(dsn string, opts ...managerOption) (*manager, error) { for _, opt := range opts { if err := opt(mgr); err != nil { - return nil, fmt.Errorf("could not apply option: %w", err) + return nil, errors.Errorf("could not apply option: %w", err) } } @@ -104,7 +104,7 @@ func (m *manager) Read(ctx context.Context, instanceID uuid.UUID) ([]*ocsf.Vulne ; `) if err != nil { - return nil, fmt.Errorf("could not prepare select statement: %w", err) + return nil, errors.Errorf("could not prepare select statement: %w", err) } defer stmt.Close() @@ -118,21 +118,21 @@ func (m *manager) Read(ctx context.Context, instanceID uuid.UUID) ([]*ocsf.Vulne Scan(&jsonFindingsStr) if err != nil { if errors.Is(err, sql.ErrNoRows) { - return nil, fmt.Errorf("%s: %w", instanceID.String(), storer.ErrNoFindingsFound) + return nil, errors.Errorf("%s: %w", instanceID.String(), storer.ErrNoFindingsFound) } - return nil, fmt.Errorf("could not select findings: %w", err) + return nil, errors.Errorf("could not select findings: %w", err) } var jsonFindings []json.RawMessage if err := json.Unmarshal([]byte(jsonFindingsStr), &jsonFindings); err != nil { - return nil, fmt.Errorf("could not unmarshal json findings to []json.RawMessage: %w", err) + return nil, errors.Errorf("could not unmarshal json findings to []json.RawMessage: %w", err) } var findings []*ocsf.VulnerabilityFinding for _, jsonFinding := range jsonFindings { var finding ocsf.VulnerabilityFinding if err := protojson.Unmarshal(jsonFinding, &finding); err != nil { - return nil, fmt.Errorf("failed to unmarshal JSON findings to *ocsf.VulnerabilityFinding: %w", err) + return nil, errors.Errorf("failed to unmarshal JSON findings to *ocsf.VulnerabilityFinding: %w", err) } findings = append(findings, &finding) } @@ -153,7 +153,7 @@ func (m *manager) Write(ctx context.Context, instanceID uuid.UUID, findings []*o ; `) if err != nil { - return fmt.Errorf("could not prepare write statement: %w", err) + return errors.Errorf("could not prepare write statement: %w", err) } defer stmt.Close() @@ -162,7 +162,7 @@ func (m *manager) Write(ctx context.Context, instanceID uuid.UUID, findings []*o sql.Named(columnNameinstanceID.String(), instanceID.String()), sql.Named(columnNameFindings.String(), jsonFindings), ); err != nil { - return fmt.Errorf("could not insert findings: %w", err) + return errors.Errorf("could not insert findings: %w", err) } return nil @@ -186,7 +186,7 @@ func (m *manager) Update(ctx context.Context, instanceID uuid.UUID, findings []* ; `) if err != nil { - return fmt.Errorf("could not prepare update statement: %w", err) + return errors.Errorf("could not prepare update statement: %w", err) } defer stmt.Close() @@ -197,15 +197,15 @@ func (m *manager) Update(ctx context.Context, instanceID uuid.UUID, findings []* sql.Named(columnNameFindings.String(), jsonFindings), ) if err != nil { - return fmt.Errorf("could not update findings: %w", err) + return errors.Errorf("could not update findings: %w", err) } r, err := res.RowsAffected() switch { case err != nil: - return fmt.Errorf("could not get rows affected: %w", err) + return errors.Errorf("could not get rows affected: %w", err) case r <= 0: - return fmt.Errorf( + return errors.Errorf( "could not update findings for instance '%s': %w", instanceID.String(), storer.ErrNoFindingsFound, @@ -218,7 +218,7 @@ func (m *manager) Update(ctx context.Context, instanceID uuid.UUID, findings []* // Close closes the connection to the underlying database. func (m *manager) Close(ctx context.Context) error { if err := m.db.Close(); err != nil { - return fmt.Errorf("could not close sqlite db: %w", err) + return errors.Errorf("could not close sqlite db: %w", err) } return nil } @@ -228,14 +228,14 @@ func (m *manager) marshalFindings(findings []*ocsf.VulnerabilityFinding) (string for _, finding := range findings { b, err := protojson.Marshal(finding) if err != nil { - return "", fmt.Errorf("could not json marshal finding: %w", err) + return "", errors.Errorf("could not json marshal finding: %w", err) } rawFindings = append(rawFindings, b) } jsonFindings, err := json.Marshal(rawFindings) if err != nil { - return "", fmt.Errorf("could not json marshal findings: %w", err) + return "", errors.Errorf("could not json marshal findings: %w", err) } return string(jsonFindings), nil diff --git a/sdk/component/internal/storer/storer.go b/sdk/component/internal/storer/storer.go index 82bb810a3..3eedf7a3f 100644 --- a/sdk/component/internal/storer/storer.go +++ b/sdk/component/internal/storer/storer.go @@ -1,5 +1,5 @@ package storer -import "errors" +import "github.com/go-errors/errors" var ErrNoFindingsFound = errors.New("no findings found") diff --git a/sdk/component/internal/uuid/uuid.go b/sdk/component/internal/uuid/uuid.go index 10c52bcac..74eed0bca 100644 --- a/sdk/component/internal/uuid/uuid.go +++ b/sdk/component/internal/uuid/uuid.go @@ -1,8 +1,7 @@ package uuid import ( - "fmt" - + "github.com/go-errors/errors" "github.com/google/uuid" ) @@ -23,7 +22,7 @@ func Parse(s string) (UUID, error) { } u, err := uuid.Parse(s) if err != nil { - return Nil, fmt.Errorf("invalid UUID string: %s", s) + return Nil, errors.Errorf("invalid UUID string: %s", s) } return UUID(u), nil } diff --git a/sdk/component/logger.go b/sdk/component/logger.go index 008cf913b..1cde5516f 100644 --- a/sdk/component/logger.go +++ b/sdk/component/logger.go @@ -2,9 +2,10 @@ package component import ( "context" - "fmt" "log/slog" "os" + + "github.com/go-errors/errors" ) const ( @@ -104,7 +105,7 @@ func newDefaultLogger(level RunnerConfigLoggingLevel) (*defaultLogger, error) { case logLevelWarn: logLevel = slog.LevelWarn default: - return nil, fmt.Errorf("unknown logger level: %s", level) + return nil, errors.Errorf("unknown logger level: %s", level) } return &defaultLogger{ diff --git a/sdk/component/reporter.go b/sdk/component/reporter.go index 58f001eb5..1bd40f759 100644 --- a/sdk/component/reporter.go +++ b/sdk/component/reporter.go @@ -2,7 +2,8 @@ package component import ( "context" - "fmt" + + "github.com/go-errors/errors" ) // RunReporter runs a reporter after initialising the run context. @@ -30,7 +31,7 @@ func RunReporter(ctx context.Context, reporter Reporter, opts ...RunnerOption) e logger. With(logKeyError, err.Error()). Debug("could not execute read step") - return fmt.Errorf("could not read findings: %w", err) + return errors.Errorf("could not read findings: %w", err) } logger.Debug("read step completed!") @@ -40,7 +41,7 @@ func RunReporter(ctx context.Context, reporter Reporter, opts ...RunnerOption) e logger. With(logKeyError, err.Error()). Debug("could not execute report step") - return fmt.Errorf("could not report findings: %w", err) + return errors.Errorf("could not report findings: %w", err) } logger.Debug("reporter step completed!") diff --git a/sdk/component/runner.go b/sdk/component/runner.go index 39d50d9b4..538c66dfa 100644 --- a/sdk/component/runner.go +++ b/sdk/component/runner.go @@ -2,11 +2,10 @@ package component import ( "context" - "errors" - "fmt" "os/signal" "syscall" + "github.com/go-errors/errors" "golang.org/x/sync/errgroup" ) @@ -26,7 +25,7 @@ type ( func newRunner(opts ...RunnerOption) (*runner, error) { cfg, err := newRunnerConfig() if err != nil { - return nil, fmt.Errorf("could not create default runner configuration: %w", err) + return nil, errors.Errorf("could not create default runner configuration: %w", err) } r := &runner{config: cfg} @@ -38,7 +37,7 @@ func newRunner(opts ...RunnerOption) (*runner, error) { } if err := r.config.isValid(); err != nil { - return nil, fmt.Errorf("invalid configuration: %w", err) + return nil, errors.Errorf("invalid configuration: %w", err) } return r, nil @@ -61,7 +60,7 @@ func run( ) error { r, err := newRunner(opts...) if err != nil { - return fmt.Errorf("could not create runner: %w", err) + return errors.Errorf("could not create runner: %w", err) } var ( @@ -112,7 +111,7 @@ func run( logger.Error("received an unexpected panic in the component runner, handling...") if panicErr, ok := r.config.PanicHandler.HandlePanic(ctx, pe); ok { logger.Error("shutting application down...") - syncErrs <- fmt.Errorf("unexpected panic error in the component runner: %w", panicErr) + syncErrs <- errors.Errorf("unexpected panic error in the component runner: %w", panicErr) } logger.Error("panic handled in the component runner!") } @@ -122,7 +121,7 @@ func run( // TODO: potentially decompose run steps to handle cancellations separately. // Actually run the component. if err := componentRunner(ctx, conf); err != nil { - return fmt.Errorf("could not run component: %w", err) + return errors.Errorf("could not run component: %w", err) } logger.Debug("component done! Preparing to exit...") @@ -133,7 +132,7 @@ func run( // Wait for all the runner bits to be done and report an error if fatal and unexpected. if err := g.Wait(); err != nil && !isContextErr(err) { - return fmt.Errorf("unexpected run error: %w", err) + return errors.Errorf("unexpected run error: %w", err) } return nil diff --git a/sdk/component/scanner.go b/sdk/component/scanner.go index f85d34998..d6a15a0bb 100644 --- a/sdk/component/scanner.go +++ b/sdk/component/scanner.go @@ -2,7 +2,8 @@ package component import ( "context" - "fmt" + + "github.com/go-errors/errors" ) // RunScanner runs a scanner after initialising the run context. @@ -30,7 +31,7 @@ func RunScanner(ctx context.Context, scanner Scanner, opts ...RunnerOption) erro logger. With(logKeyError, err.Error()). Debug("could not execute transform step") - return fmt.Errorf("could not transform raw findings: %w", err) + return errors.Errorf("could not transform raw findings: %w", err) } logger = logger. @@ -44,7 +45,7 @@ func RunScanner(ctx context.Context, scanner Scanner, opts ...RunnerOption) erro With(logKeyError, err.Error()). With(logKeyRawFinding, rv). Error("invalid raw finding") - return fmt.Errorf("invalid raw finding: %w", err) + return errors.Errorf("invalid raw finding: %w", err) } } @@ -55,7 +56,7 @@ func RunScanner(ctx context.Context, scanner Scanner, opts ...RunnerOption) erro logger. With(logKeyError, err.Error()). Debug("could not execute store step") - return fmt.Errorf("could not store vulnerabilities: %w", err) + return errors.Errorf("could not store vulnerabilities: %w", err) } logger.Debug("store step completed!") diff --git a/sdk/component/storer.go b/sdk/component/storer.go index 8a4924c08..126920a65 100644 --- a/sdk/component/storer.go +++ b/sdk/component/storer.go @@ -1,7 +1,7 @@ package component import ( - "fmt" + "github.com/go-errors/errors" "github.com/smithy-security/smithy/sdk/component/internal/storer/local/sqlite" ) @@ -18,9 +18,9 @@ func newStorer(conf runnerConfigStorer) (Storer, error) { if conf.storeType == storeTypeLocal { localMgr, err := sqlite.NewManager(conf.dbDSN) if err != nil { - return nil, fmt.Errorf("unable to initialize local sqlite manager: %w", err) + return nil, errors.Errorf("unable to initialize local sqlite manager: %w", err) } return localMgr, nil } - return nil, fmt.Errorf("curently unsupported store type: %s", conf.storeType) + return nil, errors.Errorf("curently unsupported store type: %s", conf.storeType) } diff --git a/sdk/component/target.go b/sdk/component/target.go index f8834078d..9e3247bf0 100644 --- a/sdk/component/target.go +++ b/sdk/component/target.go @@ -2,7 +2,8 @@ package component import ( "context" - "fmt" + + "github.com/go-errors/errors" ) // RunTarget runs a target after initialising the run context. @@ -16,7 +17,7 @@ func RunTarget(ctx context.Context, target Target, opts ...RunnerOption) error { if err := target.Prepare(ctx); err != nil { logger.With(logKeyError, err.Error()).Error("preparing target failed") - return fmt.Errorf("could not prepare target: %w", err) + return errors.Errorf("could not prepare target: %w", err) } logger.Debug("component has completed successfully!")