Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ocu 268 - Replace errors and fmt.Errorf utilisations for go-errors. #467

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions sdk/component/conf.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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{
Expand All @@ -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
Expand All @@ -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 ---
Expand Down
9 changes: 5 additions & 4 deletions sdk/component/enricher.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package component

import (
"context"
"fmt"

"github.com/go-errors/errors"
)

// RunEnricher runs an enricher after initialising the run context.
Expand All @@ -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))
Expand All @@ -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))
Expand All @@ -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!")
Expand Down
12 changes: 6 additions & 6 deletions sdk/component/env.go
Original file line number Diff line number Diff line change
@@ -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"
)

Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand Down
9 changes: 5 additions & 4 deletions sdk/component/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package component

import (
"context"
"fmt"

"github.com/go-errors/errors"
)

// RunFilter runs a filter after initialising the run context.
Expand All @@ -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))
Expand All @@ -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
Expand All @@ -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!")
Expand Down
8 changes: 3 additions & 5 deletions sdk/component/internal/storer/local/sqlite/export_test.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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()
Expand Down
34 changes: 17 additions & 17 deletions sdk/component/internal/storer/local/sqlite/sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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{
Expand All @@ -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)
}
}

Expand All @@ -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()
Expand All @@ -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)
}
Expand All @@ -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()
Expand All @@ -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
Expand All @@ -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()
Expand All @@ -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,
Expand All @@ -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
}
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion sdk/component/internal/storer/storer.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package storer

import "errors"
import "github.com/go-errors/errors"

var ErrNoFindingsFound = errors.New("no findings found")
5 changes: 2 additions & 3 deletions sdk/component/internal/uuid/uuid.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package uuid

import (
"fmt"

"github.com/go-errors/errors"
"github.com/google/uuid"
)

Expand All @@ -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
}
Expand Down
Loading