From 5d1ede7cfb8a53cfb1bbef8cb78fe3854bdc53cf Mon Sep 17 00:00:00 2001 From: Darren Lau Date: Sun, 10 Sep 2023 04:06:49 -0400 Subject: [PATCH] Use %w verb for fmt.Errorf error wrappings (#668) * Configrue linter to enable fmt.Errorf error wrapping check * Replace %v with %w verb for fmt.Errorf error wrapping --- .golangci.yml | 2 +- cmd/vmclarity-cli/asset/asset_create.go | 12 ++-- pkg/apiserver/config.go | 2 +- pkg/apiserver/database/gorm/database.go | 2 +- pkg/apiserver/database/gorm/scan_config.go | 2 +- pkg/apiserver/database/odatasql/query.go | 4 +- pkg/apiserver/rest/common.go | 2 +- pkg/apiserver/rest/server.go | 4 +- pkg/cli/utils/json_helper.go | 6 +- .../assetscanprocessor/exploits.go | 4 +- .../assetscanprocessor/infofinder.go | 4 +- .../assetscanprocessor/malware.go | 4 +- .../assetscanprocessor/misconfigurations.go | 4 +- .../assetscanprocessor/packages.go | 4 +- .../assetscanprocessor/rootkits.go | 4 +- .../assetscanprocessor/secrets.go | 4 +- .../assetscanprocessor/vulnerabilities.go | 4 +- pkg/orchestrator/discovery/discoverer.go | 2 +- pkg/orchestrator/provider/aws/client.go | 4 +- pkg/orchestrator/provider/aws/instance.go | 2 +- pkg/orchestrator/provider/aws/snapshot.go | 2 +- pkg/orchestrator/provider/azure/scannerVm.go | 2 +- pkg/orchestrator/provider/external/client.go | 12 ++-- pkg/orchestrator/provider/external/helpers.go | 10 +-- pkg/orchestrator/provider/gcp/client.go | 2 +- .../scanestimationwatcher/watcher.go | 2 +- pkg/orchestrator/scanwatcher/watcher.go | 2 +- pkg/shared/backendclient/client.go | 30 ++++----- pkg/shared/families/exploits/family.go | 4 +- pkg/shared/families/infofinder/family.go | 2 +- .../infofinder/sshtopology/scanner.go | 36 +++++------ pkg/shared/families/malware/clam/clam.go | 6 +- pkg/shared/families/malware/family.go | 2 +- pkg/shared/families/manager.go | 6 +- .../families/misconfiguration/family.go | 2 +- .../rootkits/chkrootkit/chkrootkit.go | 6 +- .../rootkits/chkrootkit/utils/parser.go | 6 +- pkg/shared/families/rootkits/family.go | 2 +- pkg/shared/families/sbom/family.go | 8 +-- pkg/shared/families/secrets/family.go | 2 +- .../families/secrets/gitleaks/gitleaks.go | 10 +-- pkg/shared/families/utils/utils.go | 4 +- pkg/shared/families/vulnerabilities/family.go | 4 +- pkg/shared/findingkey/common.go | 2 +- .../rest/dashboard_findings_impact.go | 64 +++++++++---------- .../rest/dashboard_findings_trends.go | 6 +- .../rest/dashboard_riskiest_assets.go | 10 +-- 47 files changed, 160 insertions(+), 160 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 86ea232c6..b6bf7d7dc 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -8,7 +8,7 @@ linters-settings: local-prefixes: github.com/openclarity/vmclarity errorlint: # Check whether fmt.Errorf uses the %w verb for formatting errors. See the readme for caveats - errorf: false + errorf: true gomoddirectives: # Allow local `replace` directives. Default is false. replace-local: true diff --git a/cmd/vmclarity-cli/asset/asset_create.go b/cmd/vmclarity-cli/asset/asset_create.go index 4b196f2e1..9677b9eb2 100644 --- a/cmd/vmclarity-cli/asset/asset_create.go +++ b/cmd/vmclarity-cli/asset/asset_create.go @@ -91,26 +91,26 @@ func init() { func getAssetFromJSONFile(filename string) (*models.AssetType, error) { file, err := os.Open(filename) if err != nil { - return nil, fmt.Errorf("failed to open file: %v", err) + return nil, fmt.Errorf("failed to open file: %w", err) } defer file.Close() // get the file size stat, err := file.Stat() if err != nil { - return nil, fmt.Errorf("failed to get file stat: %v", err) + return nil, fmt.Errorf("failed to get file stat: %w", err) } // read the file bs := make([]byte, stat.Size()) _, err = file.Read(bs) if err != nil { - return nil, fmt.Errorf("failed to read file: %v", err) + return nil, fmt.Errorf("failed to read file: %w", err) } assetType := &models.AssetType{} if err := assetType.UnmarshalJSON(bs); err != nil { - return nil, fmt.Errorf("failed to unmarshal asset into AssetType %v", err) + return nil, fmt.Errorf("failed to unmarshal asset into AssetType %w", err) } return assetType, nil @@ -137,12 +137,12 @@ func createAsset(ctx context.Context, assetType *models.AssetType, server string // which matches the unique properties of this asset, in this // case if the update-if-exists flag is set we'll patch the just AssetInfo and FirstSeen instead. if !errors.As(err, &conflictError) || !updateIfExists { - return nil, fmt.Errorf("failed to post asset: %v", err) + return nil, fmt.Errorf("failed to post asset: %w", err) } assetData.FirstSeen = nil err = client.PatchAsset(ctx, assetData, *conflictError.ConflictingAsset.Id) if err != nil { - return nil, fmt.Errorf("failed to patch asset: %v", err) + return nil, fmt.Errorf("failed to patch asset: %w", err) } return conflictError.ConflictingAsset, nil diff --git a/pkg/apiserver/config.go b/pkg/apiserver/config.go index 5d84cef35..657356307 100644 --- a/pkg/apiserver/config.go +++ b/pkg/apiserver/config.go @@ -109,7 +109,7 @@ func LoadConfig() (*Config, error) { if err == nil { log.Infof("\n\nconfig=%s\n\n", configB) } else { - return nil, fmt.Errorf("failed to marshal config: %v", err) + return nil, fmt.Errorf("failed to marshal config: %w", err) } return config, nil diff --git a/pkg/apiserver/database/gorm/database.go b/pkg/apiserver/database/gorm/database.go index 2204decf7..bc256a419 100644 --- a/pkg/apiserver/database/gorm/database.go +++ b/pkg/apiserver/database/gorm/database.go @@ -187,7 +187,7 @@ func initPostgres(config types.DBConfig, dbLogger logger.Interface) (*gorm.DB, e Logger: dbLogger, }) if err != nil { - return nil, fmt.Errorf("failed to open %s db: %v", config.DBName, err) + return nil, fmt.Errorf("failed to open %s db: %w", config.DBName, err) } return db, nil diff --git a/pkg/apiserver/database/gorm/scan_config.go b/pkg/apiserver/database/gorm/scan_config.go index abc799981..99ed4f9d1 100644 --- a/pkg/apiserver/database/gorm/scan_config.go +++ b/pkg/apiserver/database/gorm/scan_config.go @@ -183,7 +183,7 @@ func validateRuntimeScheduleScanConfig(scheduled *models.RuntimeScheduleScanConf // validate cron expression expr, err := cronexpr.Parse(*scheduled.CronLine) if err != nil { - return fmt.Errorf("malformed cron expression: %v", err) + return fmt.Errorf("malformed cron expression: %w", err) } // set operation time if missing diff --git a/pkg/apiserver/database/odatasql/query.go b/pkg/apiserver/database/odatasql/query.go index 15bdc1217..57f0e0be2 100644 --- a/pkg/apiserver/database/odatasql/query.go +++ b/pkg/apiserver/database/odatasql/query.go @@ -694,14 +694,14 @@ func buildWhereFromLambda(sqlVariant jsonsql.Variant, schemaMetas map[string]Sch newIdentifier := fmt.Sprintf("%sFilterOptions", identifier) subquery, err := buildWhereFromFilter(sqlVariant, schemaMetas, newFieldMetas[0], newIdentifier, fmt.Sprintf("%s.value", identifier), lambda.Children[1], fmt.Sprintf("%s.", lambda.Children[0].Token.Value)) if err != nil { - return "", fmt.Errorf("unable to build query inside lambda: %v", err) + return "", fmt.Errorf("unable to build query inside lambda: %w", err) } return fmt.Sprintf("EXISTS (SELECT 1 FROM %s AS %s WHERE %s)", sqlVariant.JSONEach(sqlVariant.JSONExtract(fieldSource, sourcePath)), identifier, subquery), nil case "all": newIdentifier := fmt.Sprintf("%sFilterOptions", identifier) subquery, err := buildWhereFromFilter(sqlVariant, schemaMetas, newFieldMetas[0], newIdentifier, fmt.Sprintf("%s.value", identifier), lambda.Children[1], fmt.Sprintf("%s.", lambda.Children[0].Token.Value)) if err != nil { - return "", fmt.Errorf("unable to build query inside lambda: %v", err) + return "", fmt.Errorf("unable to build query inside lambda: %w", err) } return fmt.Sprintf("NOT EXISTS (SELECT 1 FROM %s AS %s WHERE NOT (%s))", sqlVariant.JSONEach(sqlVariant.JSONExtract(fieldSource, sourcePath)), identifier, subquery), nil default: diff --git a/pkg/apiserver/rest/common.go b/pkg/apiserver/rest/common.go index dcf21b3c6..c0cbfc7e5 100644 --- a/pkg/apiserver/rest/common.go +++ b/pkg/apiserver/rest/common.go @@ -43,7 +43,7 @@ func sendResponse(ctx echo.Context, code int, object interface{}) error { func (s *ServerImpl) GetOpenAPISpec(ctx echo.Context) error { swagger, err := server.GetSwagger() if err != nil { - return fmt.Errorf("failed to load swagger spec: %v", err) + return fmt.Errorf("failed to load swagger spec: %w", err) } // Use the X-Forwarded-* headers to populate the OpenAPI spec with the diff --git a/pkg/apiserver/rest/server.go b/pkg/apiserver/rest/server.go index ae3873da0..c05498812 100644 --- a/pkg/apiserver/rest/server.go +++ b/pkg/apiserver/rest/server.go @@ -46,7 +46,7 @@ type Server struct { func CreateRESTServer(port int, dbHandler databaseTypes.Database) (*Server, error) { e, err := createEchoServer(dbHandler) if err != nil { - return nil, fmt.Errorf("failed to create rest server: %v", err) + return nil, fmt.Errorf("failed to create rest server: %w", err) } return &Server{ port: port, @@ -57,7 +57,7 @@ func CreateRESTServer(port int, dbHandler databaseTypes.Database) (*Server, erro func createEchoServer(dbHandler databaseTypes.Database) (*echo.Echo, error) { swagger, err := server.GetSwagger() if err != nil { - return nil, fmt.Errorf("failed to load swagger spec: %v", err) + return nil, fmt.Errorf("failed to load swagger spec: %w", err) } e := echo.New() diff --git a/pkg/cli/utils/json_helper.go b/pkg/cli/utils/json_helper.go index 013337978..b85e64aa9 100644 --- a/pkg/cli/utils/json_helper.go +++ b/pkg/cli/utils/json_helper.go @@ -28,18 +28,18 @@ func PrintJSONData(data interface{}, fields string) error { if fields == "" { dataB, err := json.Marshal(data) if err != nil { - return fmt.Errorf("failed to marshal data: %v", err) + return fmt.Errorf("failed to marshal data: %w", err) } fmt.Println(string(dataB)) return nil } j := jsonpath.New("parser") if err := j.Parse(fields); err != nil { - return fmt.Errorf("failed to parse jsonpath: %v", err) + return fmt.Errorf("failed to parse jsonpath: %w", err) } err := j.Execute(os.Stdout, data) if err != nil { - return fmt.Errorf("failed to execute jsonpath: %v", err) + return fmt.Errorf("failed to execute jsonpath: %w", err) } return nil } diff --git a/pkg/orchestrator/assetscanprocessor/exploits.go b/pkg/orchestrator/assetscanprocessor/exploits.go index 6792338ae..ce57a1bd2 100644 --- a/pkg/orchestrator/assetscanprocessor/exploits.go +++ b/pkg/orchestrator/assetscanprocessor/exploits.go @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultExploitsToFindings(ctx context.Con newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Exploit", *completedTime) if err != nil { - return fmt.Errorf("failed to check for newer existing exploits findings: %v", err) + return fmt.Errorf("failed to check for newer existing exploits findings: %w", err) } // Build a map of existing findings for this scan to prevent us @@ -131,7 +131,7 @@ func (asp *AssetScanProcessor) reconcileResultExploitsToFindings(ctx context.Con // an asset scan older than this asset scan. err = asp.invalidateOlderFindingsByType(ctx, "Exploit", assetScan.Asset.Id, *completedTime) if err != nil { - return fmt.Errorf("failed to invalidate older exploit finding: %v", err) + return fmt.Errorf("failed to invalidate older exploit finding: %w", err) } // Get all findings which aren't invalidated, and then update the asset's summary diff --git a/pkg/orchestrator/assetscanprocessor/infofinder.go b/pkg/orchestrator/assetscanprocessor/infofinder.go index 6b84fd151..d03efa2c6 100644 --- a/pkg/orchestrator/assetscanprocessor/infofinder.go +++ b/pkg/orchestrator/assetscanprocessor/infofinder.go @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultInfoFindersToFindings(ctx context. newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "InfoFinder", *completedTime) if err != nil { - return fmt.Errorf("failed to check for newer existing InfoFinder findings: %v", err) + return fmt.Errorf("failed to check for newer existing InfoFinder findings: %w", err) } // Build a map of existing findings for this scan to prevent us @@ -129,7 +129,7 @@ func (asp *AssetScanProcessor) reconcileResultInfoFindersToFindings(ctx context. // an asset scan older than this asset scan. err = asp.invalidateOlderFindingsByType(ctx, "InfoFinder", assetScan.Asset.Id, *completedTime) if err != nil { - return fmt.Errorf("failed to invalidate older InfoFinder finding: %v", err) + return fmt.Errorf("failed to invalidate older InfoFinder finding: %w", err) } // Get all findings which aren't invalidated, and then update the asset's summary diff --git a/pkg/orchestrator/assetscanprocessor/malware.go b/pkg/orchestrator/assetscanprocessor/malware.go index de4602ec8..3d67109ea 100644 --- a/pkg/orchestrator/assetscanprocessor/malware.go +++ b/pkg/orchestrator/assetscanprocessor/malware.go @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultMalwareToFindings(ctx context.Cont newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Malware", *completedTime) if err != nil { - return fmt.Errorf("failed to check for newer existing malware findings: %v", err) + return fmt.Errorf("failed to check for newer existing malware findings: %w", err) } // Build a map of existing findings for this scan to prevent us @@ -128,7 +128,7 @@ func (asp *AssetScanProcessor) reconcileResultMalwareToFindings(ctx context.Cont // an asset scan older than this asset scan. err = asp.invalidateOlderFindingsByType(ctx, "Malware", assetScan.Asset.Id, *completedTime) if err != nil { - return fmt.Errorf("failed to invalidate older malware finding: %v", err) + return fmt.Errorf("failed to invalidate older malware finding: %w", err) } // Get all findings which aren't invalidated, and then update the asset's summary diff --git a/pkg/orchestrator/assetscanprocessor/misconfigurations.go b/pkg/orchestrator/assetscanprocessor/misconfigurations.go index 044de6b01..7b15f2d64 100644 --- a/pkg/orchestrator/assetscanprocessor/misconfigurations.go +++ b/pkg/orchestrator/assetscanprocessor/misconfigurations.go @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultMisconfigurationsToFindings(ctx co newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Misconfiguration", *completedTime) if err != nil { - return fmt.Errorf("failed to check for newer existing misconfiguration findings: %v", err) + return fmt.Errorf("failed to check for newer existing misconfiguration findings: %w", err) } // Build a map of existing findings for this scan to prevent us @@ -133,7 +133,7 @@ func (asp *AssetScanProcessor) reconcileResultMisconfigurationsToFindings(ctx co // an asset scan older than this asset scan. err = asp.invalidateOlderFindingsByType(ctx, "Misconfiguration", assetScan.Asset.Id, *completedTime) if err != nil { - return fmt.Errorf("failed to invalidate older misconfiguration finding: %v", err) + return fmt.Errorf("failed to invalidate older misconfiguration finding: %w", err) } // Get all findings which aren't invalidated, and then update the asset's summary diff --git a/pkg/orchestrator/assetscanprocessor/packages.go b/pkg/orchestrator/assetscanprocessor/packages.go index 6df44fc5f..212ce873e 100644 --- a/pkg/orchestrator/assetscanprocessor/packages.go +++ b/pkg/orchestrator/assetscanprocessor/packages.go @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultPackagesToFindings(ctx context.Con newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Package", *completedTime) if err != nil { - return fmt.Errorf("failed to check for newer existing package findings: %v", err) + return fmt.Errorf("failed to check for newer existing package findings: %w", err) } // Build a map of existing findings for this scan to prevent us @@ -132,7 +132,7 @@ func (asp *AssetScanProcessor) reconcileResultPackagesToFindings(ctx context.Con // an asset scan older than this asset scan. err = asp.invalidateOlderFindingsByType(ctx, "Package", assetScan.Asset.Id, *completedTime) if err != nil { - return fmt.Errorf("failed to invalidate older package finding: %v", err) + return fmt.Errorf("failed to invalidate older package finding: %w", err) } // Get all findings which aren't invalidated, and then update the asset's summary diff --git a/pkg/orchestrator/assetscanprocessor/rootkits.go b/pkg/orchestrator/assetscanprocessor/rootkits.go index 5c6e2136f..627b95f0c 100644 --- a/pkg/orchestrator/assetscanprocessor/rootkits.go +++ b/pkg/orchestrator/assetscanprocessor/rootkits.go @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultRootkitsToFindings(ctx context.Con newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Rootkit", *completedTime) if err != nil { - return fmt.Errorf("failed to check for newer existing rootkit findings: %v", err) + return fmt.Errorf("failed to check for newer existing rootkit findings: %w", err) } // Build a map of existing findings for this scan to prevent us @@ -128,7 +128,7 @@ func (asp *AssetScanProcessor) reconcileResultRootkitsToFindings(ctx context.Con // an asset scan older than this asset scan. err = asp.invalidateOlderFindingsByType(ctx, "Rootkit", assetScan.Asset.Id, *completedTime) if err != nil { - return fmt.Errorf("failed to invalidate older rootkit finding: %v", err) + return fmt.Errorf("failed to invalidate older rootkit finding: %w", err) } // Get all findings which aren't invalidated, and then update the asset's summary diff --git a/pkg/orchestrator/assetscanprocessor/secrets.go b/pkg/orchestrator/assetscanprocessor/secrets.go index 2352f2c87..51e9b9833 100644 --- a/pkg/orchestrator/assetscanprocessor/secrets.go +++ b/pkg/orchestrator/assetscanprocessor/secrets.go @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultSecretsToFindings(ctx context.Cont newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Secret", *completedTime) if err != nil { - return fmt.Errorf("failed to check for newer existing secret findings: %v", err) + return fmt.Errorf("failed to check for newer existing secret findings: %w", err) } // Build a map of existing findings for this scan to prevent us @@ -132,7 +132,7 @@ func (asp *AssetScanProcessor) reconcileResultSecretsToFindings(ctx context.Cont // an asset scan older than this asset scan. err = asp.invalidateOlderFindingsByType(ctx, "Secret", assetScan.Asset.Id, *completedTime) if err != nil { - return fmt.Errorf("failed to invalidate older secret finding: %v", err) + return fmt.Errorf("failed to invalidate older secret finding: %w", err) } // Get all findings which aren't invalidated, and then update the asset's summary diff --git a/pkg/orchestrator/assetscanprocessor/vulnerabilities.go b/pkg/orchestrator/assetscanprocessor/vulnerabilities.go index 04a6f9128..63a017907 100644 --- a/pkg/orchestrator/assetscanprocessor/vulnerabilities.go +++ b/pkg/orchestrator/assetscanprocessor/vulnerabilities.go @@ -33,7 +33,7 @@ func (asp *AssetScanProcessor) reconcileResultVulnerabilitiesToFindings(ctx cont newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Vulnerability", *completedTime) if err != nil { - return fmt.Errorf("failed to check for newer existing vulnerability findings: %v", err) + return fmt.Errorf("failed to check for newer existing vulnerability findings: %w", err) } existingFilter := fmt.Sprintf("findingInfo/objectType eq 'Vulnerability' and foundBy/id eq '%s'", *assetScan.Id) @@ -121,7 +121,7 @@ func (asp *AssetScanProcessor) reconcileResultVulnerabilitiesToFindings(ctx cont // an asset scan older than this asset scan. err = asp.invalidateOlderFindingsByType(ctx, "Vulnerability", assetScan.Asset.Id, *completedTime) if err != nil { - return fmt.Errorf("failed to invalidate older vulnerability finding: %v", err) + return fmt.Errorf("failed to invalidate older vulnerability finding: %w", err) } // Get all findings which aren't invalidated, and then update the asset's summary diff --git a/pkg/orchestrator/discovery/discoverer.go b/pkg/orchestrator/discovery/discoverer.go index fcdd9d0f8..04ff7d60c 100644 --- a/pkg/orchestrator/discovery/discoverer.go +++ b/pkg/orchestrator/discovery/discoverer.go @@ -108,7 +108,7 @@ func (d *Discoverer) DiscoverAndCreateAssets(ctx context.Context) error { } if err := discoverer.Err(); err != nil { - return fmt.Errorf("failed to discover assets: %v", err) + return fmt.Errorf("failed to discover assets: %w", err) } // Find all assets which are not already terminatedOn and were not diff --git a/pkg/orchestrator/provider/aws/client.go b/pkg/orchestrator/provider/aws/client.go index 8d43feb77..cbd454a5d 100644 --- a/pkg/orchestrator/provider/aws/client.go +++ b/pkg/orchestrator/provider/aws/client.go @@ -794,7 +794,7 @@ func (c *Client) GetInstances(ctx context.Context, filters []ec2types.Filter, re options.Region = regionID }) if err != nil { - return nil, fmt.Errorf("failed to describe instances: %v", err) + return nil, fmt.Errorf("failed to describe instances: %w", err) } ret = append(ret, c.getInstancesFromDescribeInstancesOutput(ctx, out, regionID)...) @@ -813,7 +813,7 @@ func (c *Client) GetInstances(ctx context.Context, filters []ec2types.Filter, re options.Region = regionID }) if err != nil { - return nil, fmt.Errorf("failed to describe instances: %v", err) + return nil, fmt.Errorf("failed to describe instances: %w", err) } ret = append(ret, c.getInstancesFromDescribeInstancesOutput(ctx, out, regionID)...) } diff --git a/pkg/orchestrator/provider/aws/instance.go b/pkg/orchestrator/provider/aws/instance.go index 45af22e42..33ad86352 100644 --- a/pkg/orchestrator/provider/aws/instance.go +++ b/pkg/orchestrator/provider/aws/instance.go @@ -99,7 +99,7 @@ func (i *Instance) Delete(ctx context.Context) error { options.Region = i.Region }) if err != nil { - return fmt.Errorf("failed to terminate instances: %v", err) + return fmt.Errorf("failed to terminate instances: %w", err) } return nil diff --git a/pkg/orchestrator/provider/aws/snapshot.go b/pkg/orchestrator/provider/aws/snapshot.go index 98c99aec8..7236c18ee 100644 --- a/pkg/orchestrator/provider/aws/snapshot.go +++ b/pkg/orchestrator/provider/aws/snapshot.go @@ -128,7 +128,7 @@ func (s *Snapshot) Delete(ctx context.Context) error { options.Region = s.Region }) if err != nil { - return fmt.Errorf("failed to delete snapshot: %v", err) + return fmt.Errorf("failed to delete snapshot: %w", err) } return nil diff --git a/pkg/orchestrator/provider/azure/scannerVm.go b/pkg/orchestrator/provider/azure/scannerVm.go index 7e1735597..83e6e5756 100644 --- a/pkg/orchestrator/provider/azure/scannerVm.go +++ b/pkg/orchestrator/provider/azure/scannerVm.go @@ -58,7 +58,7 @@ func (c *Client) ensureScannerVirtualMachine(ctx context.Context, config *provid userData, err := cloudinit.New(config) if err != nil { - return armcompute.VirtualMachine{}, fmt.Errorf("failed to generate cloud-init: %v", err) + return armcompute.VirtualMachine{}, fmt.Errorf("failed to generate cloud-init: %w", err) } userDataBase64 := base64.StdEncoding.EncodeToString([]byte(userData)) diff --git a/pkg/orchestrator/provider/external/client.go b/pkg/orchestrator/provider/external/client.go index e0c3419c5..8fba174b6 100644 --- a/pkg/orchestrator/provider/external/client.go +++ b/pkg/orchestrator/provider/external/client.go @@ -55,7 +55,7 @@ func New(_ context.Context) (*Client, error) { conn, err := grpc.Dial(config.ProviderPluginAddress, opts...) if err != nil { - return nil, fmt.Errorf("failed to dial grpc. address=%v: %v", config.ProviderPluginAddress, err) + return nil, fmt.Errorf("failed to dial grpc. address=%v: %w", config.ProviderPluginAddress, err) } client.conn = conn client.providerClient = provider_service.NewProviderClient(conn) @@ -79,7 +79,7 @@ func (c *Client) DiscoverAssets(ctx context.Context) provider.AssetDiscoverer { res, err := c.providerClient.DiscoverAssets(ctx, &provider_service.DiscoverAssetsParams{}) if err != nil { - assetDiscoverer.Error = fmt.Errorf("failed to discover assets: %v", err) + assetDiscoverer.Error = fmt.Errorf("failed to discover assets: %w", err) return } @@ -87,7 +87,7 @@ func (c *Client) DiscoverAssets(ctx context.Context) provider.AssetDiscoverer { for _, asset := range assets { modelsAsset, err := convertAssetToModels(asset) if err != nil { - assetDiscoverer.Error = fmt.Errorf("failed to convert asset to models asset: %v", err) + assetDiscoverer.Error = fmt.Errorf("failed to convert asset to models asset: %w", err) return } @@ -106,7 +106,7 @@ func (c *Client) DiscoverAssets(ctx context.Context) provider.AssetDiscoverer { func (c *Client) RunAssetScan(ctx context.Context, config *provider.ScanJobConfig) error { scanJobConfig, err := convertScanJobConfig(config) if err != nil { - return fmt.Errorf("failed to convert scan job config: %v", err) + return fmt.Errorf("failed to convert scan job config: %w", err) } res, err := c.providerClient.RunAssetScan(ctx, &provider_service.RunAssetScanParams{ @@ -137,14 +137,14 @@ func (c *Client) RunAssetScan(ctx context.Context, config *provider.ScanJobConfi func (c *Client) RemoveAssetScan(ctx context.Context, config *provider.ScanJobConfig) error { scanJobConfig, err := convertScanJobConfig(config) if err != nil { - return fmt.Errorf("failed to convert scan job config: %v", err) + return fmt.Errorf("failed to convert scan job config: %w", err) } _, err = c.providerClient.RemoveAssetScan(ctx, &provider_service.RemoveAssetScanParams{ ScanJobConfig: scanJobConfig, }) if err != nil { - return fmt.Errorf("failed to remove asset scan: %v", err) + return fmt.Errorf("failed to remove asset scan: %w", err) } return nil } diff --git a/pkg/orchestrator/provider/external/helpers.go b/pkg/orchestrator/provider/external/helpers.go index 3c43bf99d..3a35ff1b6 100644 --- a/pkg/orchestrator/provider/external/helpers.go +++ b/pkg/orchestrator/provider/external/helpers.go @@ -47,7 +47,7 @@ func convertAssetToModels(asset *provider_service.Asset) (models.Asset, error) { SecurityGroups: &[]models.SecurityGroup{}, Tags: convertTagsToModels(vminfo.Tags), }); err != nil { - return models.Asset{}, fmt.Errorf("failed to convert asset from VMInfo: %v", err) + return models.Asset{}, fmt.Errorf("failed to convert asset from VMInfo: %w", err) } case *provider_service.Asset_Dirinfo: dirinfo := asset.GetDirinfo() @@ -56,7 +56,7 @@ func convertAssetToModels(asset *provider_service.Asset) (models.Asset, error) { DirName: utils.PointerTo(dirinfo.DirName), Location: utils.PointerTo(dirinfo.Location), }); err != nil { - return models.Asset{}, fmt.Errorf("failed to convert asset from Dirinfo: %v", err) + return models.Asset{}, fmt.Errorf("failed to convert asset from Dirinfo: %w", err) } case *provider_service.Asset_Podinfo: podinfo := asset.GetPodinfo() @@ -65,7 +65,7 @@ func convertAssetToModels(asset *provider_service.Asset) (models.Asset, error) { PodName: utils.PointerTo(podinfo.PodName), Location: utils.PointerTo(podinfo.Location), }); err != nil { - return models.Asset{}, fmt.Errorf("failed to convert asset from Podinfo: %v", err) + return models.Asset{}, fmt.Errorf("failed to convert asset from Podinfo: %w", err) } default: return models.Asset{}, fmt.Errorf("unsupported asset type: %t", asset.AssetType) @@ -79,7 +79,7 @@ func convertAssetToModels(asset *provider_service.Asset) (models.Asset, error) { func convertAssetFromModels(asset models.Asset) (*provider_service.Asset, error) { value, err := asset.AssetInfo.ValueByDiscriminator() if err != nil { - return nil, fmt.Errorf("failed to value by discriminator from asset info: %v", err) + return nil, fmt.Errorf("failed to value by discriminator from asset info: %w", err) } switch info := value.(type) { @@ -151,7 +151,7 @@ func convertTagsFromModels(tags *[]models.Tag) []*provider_service.Tag { func convertScanJobConfig(config *provider.ScanJobConfig) (*provider_service.ScanJobConfig, error) { asset, err := convertAssetFromModels(config.Asset) if err != nil { - return nil, fmt.Errorf("failed to convert asset from models asset: %v", err) + return nil, fmt.Errorf("failed to convert asset from models asset: %w", err) } ret := provider_service.ScanJobConfig{ diff --git a/pkg/orchestrator/provider/gcp/client.go b/pkg/orchestrator/provider/gcp/client.go index 61f535130..ae92cb974 100644 --- a/pkg/orchestrator/provider/gcp/client.go +++ b/pkg/orchestrator/provider/gcp/client.go @@ -201,7 +201,7 @@ func (c *Client) DiscoverAssets(ctx context.Context) provider.AssetDiscoverer { regions, err := c.listAllRegions(ctx) if err != nil { - assetDiscoverer.Error = fmt.Errorf("failed to list all regions: %v", err) + assetDiscoverer.Error = fmt.Errorf("failed to list all regions: %w", err) return } diff --git a/pkg/orchestrator/scanestimationwatcher/watcher.go b/pkg/orchestrator/scanestimationwatcher/watcher.go index de77eb0e2..f6d7c7bca 100644 --- a/pkg/orchestrator/scanestimationwatcher/watcher.go +++ b/pkg/orchestrator/scanestimationwatcher/watcher.go @@ -89,7 +89,7 @@ func (w *Watcher) GetScanEstimations(ctx context.Context) ([]ScanEstimationRecon } scanEstimations, err := w.backend.GetScanEstimations(ctx, params) if err != nil { - return nil, fmt.Errorf("failed to get running sScanEstimations: %v", err) + return nil, fmt.Errorf("failed to get running sScanEstimations: %w", err) } switch { diff --git a/pkg/orchestrator/scanwatcher/watcher.go b/pkg/orchestrator/scanwatcher/watcher.go index b77073398..4285e1add 100644 --- a/pkg/orchestrator/scanwatcher/watcher.go +++ b/pkg/orchestrator/scanwatcher/watcher.go @@ -90,7 +90,7 @@ func (w *Watcher) GetRunningScans(ctx context.Context) ([]ScanReconcileEvent, er } scans, err := w.backend.GetScans(ctx, params) if err != nil { - return nil, fmt.Errorf("failed to get running scans: %v", err) + return nil, fmt.Errorf("failed to get running scans: %w", err) } switch { diff --git a/pkg/shared/backendclient/client.go b/pkg/shared/backendclient/client.go index a03214340..7003d1f84 100644 --- a/pkg/shared/backendclient/client.go +++ b/pkg/shared/backendclient/client.go @@ -140,7 +140,7 @@ func (b *BackendClient) PatchAssetScan(ctx context.Context, assetScan models.Ass func (b *BackendClient) PostScan(ctx context.Context, scan models.Scan) (*models.Scan, error) { resp, err := b.apiClient.PostScansWithResponse(ctx, scan) if err != nil { - return nil, fmt.Errorf("failed to create a scan: %v", err) + return nil, fmt.Errorf("failed to create a scan: %w", err) } switch resp.StatusCode() { case http.StatusCreated: @@ -175,7 +175,7 @@ func (b *BackendClient) PostScan(ctx context.Context, scan models.Scan) (*models func (b *BackendClient) PostAssetScan(ctx context.Context, assetScan models.AssetScan) (*models.AssetScan, error) { resp, err := b.apiClient.PostAssetScansWithResponse(ctx, assetScan) if err != nil { - return nil, fmt.Errorf("failed to create an asset scan: %v", err) + return nil, fmt.Errorf("failed to create an asset scan: %w", err) } switch resp.StatusCode() { case http.StatusCreated: @@ -211,7 +211,7 @@ func (b *BackendClient) PatchScan(ctx context.Context, scanID models.ScanID, sca params := models.PatchScansScanIDParams{} resp, err := b.apiClient.PatchScansScanIDWithResponse(ctx, scanID, ¶ms, *scan) if err != nil { - return fmt.Errorf("failed to update a scan: %v", err) + return fmt.Errorf("failed to update a scan: %w", err) } switch resp.StatusCode() { case http.StatusOK: @@ -269,7 +269,7 @@ func (b *BackendClient) PatchAssetScanStatus(ctx context.Context, assetScanID st params := models.PatchAssetScansAssetScanIDParams{} resp, err := b.apiClient.PatchAssetScansAssetScanIDWithResponse(ctx, assetScanID, ¶ms, assetScan) if err != nil { - return fmt.Errorf("failed to update an asset scan status: %v", err) + return fmt.Errorf("failed to update an asset scan status: %w", err) } switch resp.StatusCode() { case http.StatusOK: @@ -301,7 +301,7 @@ func (b *BackendClient) PatchAssetScanStatus(ctx context.Context, assetScanID st func (b *BackendClient) GetScan(ctx context.Context, scanID string, params models.GetScansScanIDParams) (*models.Scan, error) { resp, err := b.apiClient.GetScansScanIDWithResponse(ctx, scanID, ¶ms) if err != nil { - return nil, fmt.Errorf("failed to get a scan: %v", err) + return nil, fmt.Errorf("failed to get a scan: %w", err) } switch resp.StatusCode() { case http.StatusOK: @@ -363,7 +363,7 @@ func (b *BackendClient) PostScanConfig(ctx context.Context, scanConfig models.Sc func (b *BackendClient) GetScanEstimation(ctx context.Context, scanEstimationID string, params models.GetScanEstimationsScanEstimationIDParams) (*models.ScanEstimation, error) { resp, err := b.apiClient.GetScanEstimationsScanEstimationIDWithResponse(ctx, scanEstimationID, ¶ms) if err != nil { - return nil, fmt.Errorf("failed to get a scan estimation: %v", err) + return nil, fmt.Errorf("failed to get a scan estimation: %w", err) } switch resp.StatusCode() { case http.StatusOK: @@ -390,7 +390,7 @@ func (b *BackendClient) GetScanEstimation(ctx context.Context, scanEstimationID func (b *BackendClient) GetScanEstimations(ctx context.Context, params models.GetScanEstimationsParams) (*models.ScanEstimations, error) { resp, err := b.apiClient.GetScanEstimationsWithResponse(ctx, ¶ms) if err != nil { - return nil, fmt.Errorf("failed to get scanEstimations: %v", err) + return nil, fmt.Errorf("failed to get scanEstimations: %w", err) } switch resp.StatusCode() { case http.StatusOK: @@ -410,7 +410,7 @@ func (b *BackendClient) PatchScanEstimation(ctx context.Context, scanEstimationI params := models.PatchScanEstimationsScanEstimationIDParams{} resp, err := b.apiClient.PatchScanEstimationsScanEstimationIDWithResponse(ctx, scanEstimationID, ¶ms, *scanEstimation) if err != nil { - return fmt.Errorf("failed to update a scan estimation: %v", err) + return fmt.Errorf("failed to update a scan estimation: %w", err) } switch resp.StatusCode() { case http.StatusOK: @@ -442,7 +442,7 @@ func (b *BackendClient) PatchScanEstimation(ctx context.Context, scanEstimationI func (b *BackendClient) PostAssetScanEstimation(ctx context.Context, assetScanEstimation models.AssetScanEstimation) (*models.AssetScanEstimation, error) { resp, err := b.apiClient.PostAssetScanEstimationsWithResponse(ctx, assetScanEstimation) if err != nil { - return nil, fmt.Errorf("failed to create an asset scan estimation: %v", err) + return nil, fmt.Errorf("failed to create an asset scan estimation: %w", err) } switch resp.StatusCode() { case http.StatusCreated: @@ -657,7 +657,7 @@ func (b *BackendClient) PatchScanConfig(ctx context.Context, scanConfigID string func (b *BackendClient) GetScans(ctx context.Context, params models.GetScansParams) (*models.Scans, error) { resp, err := b.apiClient.GetScansWithResponse(ctx, ¶ms) if err != nil { - return nil, fmt.Errorf("failed to get scans: %v", err) + return nil, fmt.Errorf("failed to get scans: %w", err) } switch resp.StatusCode() { case http.StatusOK: @@ -677,7 +677,7 @@ func (b *BackendClient) GetScans(ctx context.Context, params models.GetScansPara func (b *BackendClient) PostAsset(ctx context.Context, asset models.Asset) (*models.Asset, error) { resp, err := b.apiClient.PostAssetsWithResponse(ctx, asset) if err != nil { - return nil, fmt.Errorf("failed to create an asset: %v", err) + return nil, fmt.Errorf("failed to create an asset: %w", err) } switch resp.StatusCode() { case http.StatusCreated: @@ -780,7 +780,7 @@ func (b *BackendClient) GetAsset(ctx context.Context, assetID string, params mod func (b *BackendClient) GetAssets(ctx context.Context, params models.GetAssetsParams) (*models.Assets, error) { resp, err := b.apiClient.GetAssetsWithResponse(ctx, ¶ms) if err != nil { - return nil, fmt.Errorf("failed to get assets: %v", err) + return nil, fmt.Errorf("failed to get assets: %w", err) } switch resp.StatusCode() { case http.StatusOK: @@ -799,7 +799,7 @@ func (b *BackendClient) GetAssets(ctx context.Context, params models.GetAssetsPa func (b *BackendClient) GetFindings(ctx context.Context, params models.GetFindingsParams) (*models.Findings, error) { resp, err := b.apiClient.GetFindingsWithResponse(ctx, ¶ms) if err != nil { - return nil, fmt.Errorf("failed to get findings: %v", err) + return nil, fmt.Errorf("failed to get findings: %w", err) } switch resp.StatusCode() { case http.StatusOK: @@ -818,7 +818,7 @@ func (b *BackendClient) GetFindings(ctx context.Context, params models.GetFindin func (b *BackendClient) PatchFinding(ctx context.Context, findingID models.FindingID, finding models.Finding) error { resp, err := b.apiClient.PatchFindingsFindingIDWithResponse(ctx, findingID, finding) if err != nil { - return fmt.Errorf("failed to update a finding: %v", err) + return fmt.Errorf("failed to update a finding: %w", err) } switch resp.StatusCode() { case http.StatusOK: @@ -850,7 +850,7 @@ func (b *BackendClient) PatchFinding(ctx context.Context, findingID models.Findi func (b *BackendClient) PostFinding(ctx context.Context, finding models.Finding) (*models.Finding, error) { resp, err := b.apiClient.PostFindingsWithResponse(ctx, finding) if err != nil { - return nil, fmt.Errorf("failed to create a finding: %v", err) + return nil, fmt.Errorf("failed to create a finding: %w", err) } switch resp.StatusCode() { case http.StatusCreated: diff --git a/pkg/shared/families/exploits/family.go b/pkg/shared/families/exploits/family.go index 033558824..c39d654a4 100644 --- a/pkg/shared/families/exploits/family.go +++ b/pkg/shared/families/exploits/family.go @@ -51,7 +51,7 @@ func (e Exploits) Run(ctx context.Context, res *results.Results) (interfaces.IsR vulnResults, err := results.GetResult[*vulnerabilities.Results](res) if err != nil { - return nil, fmt.Errorf("failed to get vulnerabilities results: %v", err) + return nil, fmt.Errorf("failed to get vulnerabilities results: %w", err) } cveIDs := getCVEIDsFromVulnerabilitiesResults(vulnResults) @@ -67,7 +67,7 @@ func (e Exploits) Run(ctx context.Context, res *results.Results) (interfaces.IsR startTime := time.Now() managerResults, err := manager.Run(utils.SourceType(input.InputType), input.Input) if err != nil { - return nil, fmt.Errorf("failed to scan input %q for exploits: %v", input.Input, err) + return nil, fmt.Errorf("failed to scan input %q for exploits: %w", input.Input, err) } endTime := time.Now() inputSize, err := familiesutils.GetInputSize(input) diff --git a/pkg/shared/families/infofinder/family.go b/pkg/shared/families/infofinder/family.go index a75107f04..b71cefe6b 100644 --- a/pkg/shared/families/infofinder/family.go +++ b/pkg/shared/families/infofinder/family.go @@ -47,7 +47,7 @@ func (i InfoFinder) Run(ctx context.Context, _ *results.Results) (interfaces.IsR startTime := time.Now() managerResults, err := manager.Run(utils.SourceType(input.InputType), input.Input) if err != nil { - return nil, fmt.Errorf("failed to scan input %q for info: %v", input.Input, err) + return nil, fmt.Errorf("failed to scan input %q for info: %w", input.Input, err) } endTime := time.Now() inputSize, err := familiesutils.GetInputSize(input) diff --git a/pkg/shared/families/infofinder/sshtopology/scanner.go b/pkg/shared/families/infofinder/sshtopology/scanner.go index 6a0507068..e48fabeb6 100644 --- a/pkg/shared/families/infofinder/sshtopology/scanner.go +++ b/pkg/shared/families/infofinder/sshtopology/scanner.go @@ -72,7 +72,7 @@ func (s *Scanner) Run(sourceType utils.SourceType, userInput string) error { homeUserDirs, err := getHomeUserDirs(userInput) if err != nil { // Collect the error and continue. - errs = append(errs, fmt.Errorf("failed to get home user dirs: %v", err)) + errs = append(errs, fmt.Errorf("failed to get home user dirs: %w", err)) } s.logger.Debugf("Found home user dirs %+v", homeUserDirs) @@ -101,7 +101,7 @@ func (s *Scanner) Run(sourceType utils.SourceType, userInput string) error { go func() { defer wg.Done() if sshDaemonKeysFingerprints, err := s.getSSHDaemonKeysFingerprints(userInput); err != nil { - errorsChan <- fmt.Errorf("failed to get ssh daemon keys: %v", err) + errorsChan <- fmt.Errorf("failed to get ssh daemon keys: %w", err) } else { fingerprintsChan <- sshDaemonKeysFingerprints } @@ -114,7 +114,7 @@ func (s *Scanner) Run(sourceType utils.SourceType, userInput string) error { go func() { defer wg.Done() if sshPrivateKeysFingerprints, err := s.getSSHPrivateKeysFingerprints(dir); err != nil { - errorsChan <- fmt.Errorf("failed to get ssh private keys: %v", err) + errorsChan <- fmt.Errorf("failed to get ssh private keys: %w", err) } else { fingerprintsChan <- sshPrivateKeysFingerprints } @@ -124,7 +124,7 @@ func (s *Scanner) Run(sourceType utils.SourceType, userInput string) error { go func() { defer wg.Done() if sshAuthorizedKeysFingerprints, err := s.getSSHAuthorizedKeysFingerprints(dir); err != nil { - errorsChan <- fmt.Errorf("failed to get ssh authorized keys: %v", err) + errorsChan <- fmt.Errorf("failed to get ssh authorized keys: %w", err) } else { fingerprintsChan <- sshAuthorizedKeysFingerprints } @@ -134,7 +134,7 @@ func (s *Scanner) Run(sourceType utils.SourceType, userInput string) error { go func() { defer wg.Done() if sshKnownHostsFingerprints, err := s.getSSHKnownHostsFingerprints(dir); err != nil { - errorsChan <- fmt.Errorf("failed to get ssh known hosts: %v", err) + errorsChan <- fmt.Errorf("failed to get ssh known hosts: %w", err) } else { fingerprintsChan <- sshKnownHostsFingerprints } @@ -176,7 +176,7 @@ func getHomeUserDirs(rootDir string) ([]string, error) { homeDirPath := path.Join(rootDir, "home") files, err := os.ReadDir(homeDirPath) if err != nil { - return nil, fmt.Errorf("failed to read dir (%v): %v", homeDirPath, err) + return nil, fmt.Errorf("failed to read dir (%v): %w", homeDirPath, err) } for _, f := range files { @@ -191,13 +191,13 @@ func getHomeUserDirs(rootDir string) ([]string, error) { func (s *Scanner) getSSHDaemonKeysFingerprints(rootPath string) ([]types.Info, error) { paths, err := s.getPrivateKeysPaths(path.Join(rootPath, "/etc/ssh"), false) if err != nil { - return nil, fmt.Errorf("failed to get private keys paths: %v", err) + return nil, fmt.Errorf("failed to get private keys paths: %w", err) } s.logger.Debugf("Found ssh daemon private keys paths %+v", paths) fingerprints, err := s.getFingerprints(paths, types.SSHDaemonKeyFingerprint) if err != nil { - return nil, fmt.Errorf("failed to get ssh daemon private keys fingerprints: %v", err) + return nil, fmt.Errorf("failed to get ssh daemon private keys fingerprints: %w", err) } s.logger.Debugf("Found ssh daemon private keys fingerprints %+v", fingerprints) @@ -207,13 +207,13 @@ func (s *Scanner) getSSHDaemonKeysFingerprints(rootPath string) ([]types.Info, e func (s *Scanner) getSSHPrivateKeysFingerprints(homeUserDir string) ([]types.Info, error) { paths, err := s.getPrivateKeysPaths(homeUserDir, true) if err != nil { - return nil, fmt.Errorf("failed to get private keys paths: %v", err) + return nil, fmt.Errorf("failed to get private keys paths: %w", err) } s.logger.Debugf("Found ssh private keys paths %+v", paths) infos, err := s.getFingerprints(paths, types.SSHPrivateKeyFingerprint) if err != nil { - return nil, fmt.Errorf("failed to get ssh private keys fingerprints: %v", err) + return nil, fmt.Errorf("failed to get ssh private keys fingerprints: %w", err) } s.logger.Debugf("Found ssh private keys fingerprints %+v", infos) @@ -223,7 +223,7 @@ func (s *Scanner) getSSHPrivateKeysFingerprints(homeUserDir string) ([]types.Inf func (s *Scanner) getSSHAuthorizedKeysFingerprints(homeUserDir string) ([]types.Info, error) { infos, err := s.getFingerprints([]string{path.Join(homeUserDir, ".ssh/authorized_keys")}, types.SSHAuthorizedKeyFingerprint) if err != nil { - return nil, fmt.Errorf("failed to get ssh authorized keys fingerprints: %v", err) + return nil, fmt.Errorf("failed to get ssh authorized keys fingerprints: %w", err) } s.logger.Debugf("Found ssh authorized keys fingerprints %+v", infos) @@ -233,7 +233,7 @@ func (s *Scanner) getSSHAuthorizedKeysFingerprints(homeUserDir string) ([]types. func (s *Scanner) getSSHKnownHostsFingerprints(homeUserDir string) ([]types.Info, error) { infos, err := s.getFingerprints([]string{path.Join(homeUserDir, ".ssh/known_hosts")}, types.SSHKnownHostFingerprint) if err != nil { - return nil, fmt.Errorf("failed to get ssh known hosts fingerprints: %v", err) + return nil, fmt.Errorf("failed to get ssh known hosts fingerprints: %w", err) } s.logger.Debugf("Found ssh known hosts fingerprints %+v", infos) @@ -249,12 +249,12 @@ func (s *Scanner) getFingerprints(paths []string, infoType types.InfoType) ([]ty s.logger.Debugf("File (%v) does not exist.", p) continue } else if err != nil { - return nil, fmt.Errorf("failed to check file: %v", err) + return nil, fmt.Errorf("failed to check file: %w", err) } var output []byte if output, err = s.executeSSHKeyGenFingerprintCommand("sha256", p); err != nil { - return nil, fmt.Errorf("failed to execute ssh-keygen command: %v", err) + return nil, fmt.Errorf("failed to execute ssh-keygen command: %w", err) } infos = append(infos, parseSSHKeyGenFingerprintCommandOutput(string(output), infoType, p)...) @@ -290,7 +290,7 @@ func (s *Scanner) getPrivateKeysPaths(rootPath string, recursive bool) ([]string return nil }) if err != nil { - return nil, fmt.Errorf("failed to walks the file tree rooted at %v: %v", rootPath, err) + return nil, fmt.Errorf("failed to walks the file tree rooted at %v: %w", rootPath, err) } return paths, nil @@ -299,7 +299,7 @@ func (s *Scanner) getPrivateKeysPaths(rootPath string, recursive bool) ([]string func isPrivateKey(path string) (bool, error) { f, err := os.Open(path) if err != nil { - return false, fmt.Errorf("failed to open file: %v", err) + return false, fmt.Errorf("failed to open file: %w", err) } defer f.Close() @@ -312,7 +312,7 @@ func isPrivateKey(path string) (bool, error) { } if err = scanner.Err(); err != nil { - return false, fmt.Errorf("failed to scan file: %v", err) + return false, fmt.Errorf("failed to scan file: %w", err) } return false, nil @@ -346,7 +346,7 @@ func (s *Scanner) executeSSHKeyGenFingerprintCommand(hashAlgo string, filePath s s.logger.Infof("Running command: %v", cmd.String()) output, err := sharedUtils.RunCommand(cmd) if err != nil { - return nil, fmt.Errorf("failed to run command: %v", err) + return nil, fmt.Errorf("failed to run command: %w", err) } return output, nil diff --git a/pkg/shared/families/malware/clam/clam.go b/pkg/shared/families/malware/clam/clam.go index 421cae3ae..d03f47b0c 100644 --- a/pkg/shared/families/malware/clam/clam.go +++ b/pkg/shared/families/malware/clam/clam.go @@ -133,12 +133,12 @@ func (s *Scanner) updateFreshclamConf() error { if os.IsNotExist(err) { return fmt.Errorf("freshclam.conf not found at %s", constants.FreshclamConfPath) } else if err != nil { - return fmt.Errorf("failed to check freshclam.conf: %v", err) + return fmt.Errorf("failed to check freshclam.conf: %w", err) } confContents, err = os.ReadFile(constants.FreshclamConfPath) if err != nil { - return fmt.Errorf("failed to read freshclam.conf: %v", err) + return fmt.Errorf("failed to read freshclam.conf: %w", err) } confLines = strings.Split(string(confContents), "\n") @@ -159,7 +159,7 @@ func (s *Scanner) updateFreshclamConf() error { writePermissions := 0o600 err = os.WriteFile(constants.FreshclamConfPath, confContents, os.FileMode(writePermissions)) if err != nil { - return fmt.Errorf("failed to write freshclam.conf: %v", err) + return fmt.Errorf("failed to write freshclam.conf: %w", err) } return nil diff --git a/pkg/shared/families/malware/family.go b/pkg/shared/families/malware/family.go index d23f61676..824b8dc30 100644 --- a/pkg/shared/families/malware/family.go +++ b/pkg/shared/families/malware/family.go @@ -47,7 +47,7 @@ func (m Malware) Run(ctx context.Context, _ *results.Results) (interfaces.IsResu startTime := time.Now() resultArr, err := manager.Run(utils.SourceType(input.InputType), input.Input) if err != nil { - return nil, fmt.Errorf("failed to scan input %q for malware: %v", input.Input, err) + return nil, fmt.Errorf("failed to scan input %q for malware: %w", input.Input, err) } endTime := time.Now() inputSize, err := familiesutils.GetInputSize(input) diff --git a/pkg/shared/families/manager.go b/pkg/shared/families/manager.go index c9fb7d139..a55975dd1 100644 --- a/pkg/shared/families/manager.go +++ b/pkg/shared/families/manager.go @@ -101,7 +101,7 @@ func (m *Manager) Run(ctx context.Context, notifier FamilyNotifier) []error { for _, family := range m.families { if err := notifier.FamilyStarted(ctx, family.GetType()); err != nil { - errors = append(errors, fmt.Errorf("family started notification failed: %v", err)) + errors = append(errors, fmt.Errorf("family started notification failed: %w", err)) continue } @@ -127,7 +127,7 @@ func (m *Manager) Run(ctx context.Context, notifier FamilyNotifier) []error { FamilyType: family.GetType(), Err: fmt.Errorf("failed to run family %v: aborted", family.GetType()), }); err != nil { - errors = append(errors, fmt.Errorf("family finished notification failed: %v", err)) + errors = append(errors, fmt.Errorf("family finished notification failed: %w", err)) } case r := <-result: logger.Debugf("received result from family %q: %v", family.GetType(), r) @@ -138,7 +138,7 @@ func (m *Manager) Run(ctx context.Context, notifier FamilyNotifier) []error { familyResults.SetResults(r.Result) } if err := notifier.FamilyFinished(ctx, r); err != nil { - errors = append(errors, fmt.Errorf("family finished notification failed: %v", err)) + errors = append(errors, fmt.Errorf("family finished notification failed: %w", err)) } close(result) } diff --git a/pkg/shared/families/misconfiguration/family.go b/pkg/shared/families/misconfiguration/family.go index 67346df44..86fda9379 100644 --- a/pkg/shared/families/misconfiguration/family.go +++ b/pkg/shared/families/misconfiguration/family.go @@ -47,7 +47,7 @@ func (m Misconfiguration) Run(ctx context.Context, _ *results.Results) (interfac startTime := time.Now() managerResults, err := manager.Run(utils.SourceType(input.InputType), input.Input) if err != nil { - return nil, fmt.Errorf("failed to scan input %q for misconfigurations: %v", input.Input, err) + return nil, fmt.Errorf("failed to scan input %q for misconfigurations: %w", input.Input, err) } endTime := time.Now() inputSize, err := familiesutils.GetInputSize(input) diff --git a/pkg/shared/families/rootkits/chkrootkit/chkrootkit.go b/pkg/shared/families/rootkits/chkrootkit/chkrootkit.go index 389c4568c..9fda9c4fc 100644 --- a/pkg/shared/families/rootkits/chkrootkit/chkrootkit.go +++ b/pkg/shared/families/rootkits/chkrootkit/chkrootkit.go @@ -54,7 +54,7 @@ func (s *Scanner) Run(sourceType utils.SourceType, userInput string) error { // validate that chkrootkit binary exists if _, err := os.Stat(s.config.BinaryPath); err != nil { - s.sendResults(retResults, fmt.Errorf("failed to find binary in %v: %v", s.config.BinaryPath, err)) + s.sendResults(retResults, fmt.Errorf("failed to find binary in %v: %w", s.config.BinaryPath, err)) return } @@ -68,13 +68,13 @@ func (s *Scanner) Run(sourceType utils.SourceType, userInput string) error { s.logger.Infof("running chkrootkit command: %v", cmd.String()) out, err := sharedutils.RunCommand(cmd) if err != nil { - s.sendResults(retResults, fmt.Errorf("failed to run chkrootkit command: %v", err)) + s.sendResults(retResults, fmt.Errorf("failed to run chkrootkit command: %w", err)) return } rootkits, err := chkrootkitutils.ParseChkrootkitOutput(out) if err != nil { - s.sendResults(retResults, fmt.Errorf("failed to parse chkrootkit output: %v", err)) + s.sendResults(retResults, fmt.Errorf("failed to parse chkrootkit output: %w", err)) return } rootkits = filterResults(rootkits) diff --git a/pkg/shared/families/rootkits/chkrootkit/utils/parser.go b/pkg/shared/families/rootkits/chkrootkit/utils/parser.go index d7b16b0fe..f1a35625a 100644 --- a/pkg/shared/families/rootkits/chkrootkit/utils/parser.go +++ b/pkg/shared/families/rootkits/chkrootkit/utils/parser.go @@ -112,7 +112,7 @@ func ParseChkrootkitOutput(chkrootkitOutput []byte) ([]Rootkit, error) { } else if testName == "aliens" { aliensToRootkits, err := processAliensToRootkits(result) if err != nil { - return nil, fmt.Errorf("failed to process aliens to rootkits: %v", err) + return nil, fmt.Errorf("failed to process aliens to rootkits: %w", err) } rootkits = append(rootkits, aliensToRootkits...) } else { @@ -123,7 +123,7 @@ func ParseChkrootkitOutput(chkrootkitOutput []byte) ([]Rootkit, error) { } if err := outputScanner.Err(); err != nil { - return nil, fmt.Errorf("failed to scan the output: %v", err) + return nil, fmt.Errorf("failed to scan the output: %w", err) } return rootkits, nil @@ -200,7 +200,7 @@ func processAliensToRootkits(aliensResult string) ([]Rootkit, error) { } if err := outputScanner.Err(); err != nil { - return nil, fmt.Errorf("failed to get output: %v", err) + return nil, fmt.Errorf("failed to get output: %w", err) } return utils.StringKeyMapToArray(rootkits), nil diff --git a/pkg/shared/families/rootkits/family.go b/pkg/shared/families/rootkits/family.go index 27fce52b8..bfe9b300b 100644 --- a/pkg/shared/families/rootkits/family.go +++ b/pkg/shared/families/rootkits/family.go @@ -48,7 +48,7 @@ func (r Rootkits) Run(ctx context.Context, _ *familiesresults.Results) (families startTime := time.Now() results, err := manager.Run(utils.SourceType(input.InputType), input.Input) if err != nil { - return nil, fmt.Errorf("failed to scan input %q for rootkits: %v", input.Input, err) + return nil, fmt.Errorf("failed to scan input %q for rootkits: %w", input.Input, err) } endTime := time.Now() inputSize, err := familiesutils.GetInputSize(input) diff --git a/pkg/shared/families/sbom/family.go b/pkg/shared/families/sbom/family.go index 1bb7574c9..cccbf9bd1 100644 --- a/pkg/shared/families/sbom/family.go +++ b/pkg/shared/families/sbom/family.go @@ -53,7 +53,7 @@ func (s SBOM) Run(ctx context.Context, _ *familiesresults.Results) (interfaces.I // we need to change the fact the MergedResults assumes it is only for 1 input? hash, err := cliutils.GenerateHash(utils.SourceType(s.conf.Inputs[0].InputType), s.conf.Inputs[0].Input) if err != nil { - return nil, fmt.Errorf("failed to generate hash for source %s: %v", s.conf.Inputs[0].Input, err) + return nil, fmt.Errorf("failed to generate hash for source %s: %w", s.conf.Inputs[0].Input, err) } manager := job_manager.New(s.conf.AnalyzersList, s.conf.AnalyzersConfig, logger, job.Factory) @@ -64,7 +64,7 @@ func (s SBOM) Run(ctx context.Context, _ *familiesresults.Results) (interfaces.I startTime := time.Now() results, err := manager.Run(utils.SourceType(input.InputType), input.Input) if err != nil { - return nil, fmt.Errorf("failed to analyzer input %q: %v", s.conf.Inputs[0].Input, err) + return nil, fmt.Errorf("failed to analyzer input %q: %w", s.conf.Inputs[0].Input, err) } endTime := time.Now() inputSize, err := familiesutils.GetInputSize(input) @@ -84,7 +84,7 @@ func (s SBOM) Run(ctx context.Context, _ *familiesresults.Results) (interfaces.I name := fmt.Sprintf("merge_with_%d", i) cdxBOMBytes, err := converter.GetCycloneDXSBOMFromFile(with.SbomPath) if err != nil { - return nil, fmt.Errorf("failed to get CDX SBOM from path=%s: %v", with.SbomPath, err) + return nil, fmt.Errorf("failed to get CDX SBOM from path=%s: %w", with.SbomPath, err) } results := sharedanalyzer.CreateResults(cdxBOMBytes, name, with.SbomPath, utils.SBOM) logger.Infof("Merging result from %q", with.SbomPath) @@ -95,7 +95,7 @@ func (s SBOM) Run(ctx context.Context, _ *familiesresults.Results) (interfaces.I // CreateMergedSBOMBytes so that we don't need to re-convert it mergedSBOMBytes, err := mergedResults.CreateMergedSBOMBytes("cyclonedx-json", pkg.GitRevision) if err != nil { - return nil, fmt.Errorf("failed to create merged output: %v", err) + return nil, fmt.Errorf("failed to create merged output: %w", err) } cdxBom, err := converter.GetCycloneDXSBOMFromBytes(mergedSBOMBytes) diff --git a/pkg/shared/families/secrets/family.go b/pkg/shared/families/secrets/family.go index 0ef86f08d..bf4762b71 100644 --- a/pkg/shared/families/secrets/family.go +++ b/pkg/shared/families/secrets/family.go @@ -48,7 +48,7 @@ func (s Secrets) Run(ctx context.Context, _ *familiesresults.Results) (interface startTime := time.Now() results, err := manager.Run(utils.SourceType(input.InputType), input.Input) if err != nil { - return nil, fmt.Errorf("failed to scan input %q for secrets: %v", input.Input, err) + return nil, fmt.Errorf("failed to scan input %q for secrets: %w", input.Input, err) } endTime := time.Now() inputSize, err := familiesutils.GetInputSize(input) diff --git a/pkg/shared/families/secrets/gitleaks/gitleaks.go b/pkg/shared/families/secrets/gitleaks/gitleaks.go index 1015a64dd..442014586 100644 --- a/pkg/shared/families/secrets/gitleaks/gitleaks.go +++ b/pkg/shared/families/secrets/gitleaks/gitleaks.go @@ -61,13 +61,13 @@ func (a *Scanner) Run(sourceType utils.SourceType, userInput string) error { } // validate that gitleaks binary exists if _, err := os.Stat(a.config.BinaryPath); err != nil { - a.sendResults(retResults, fmt.Errorf("failed to find binary in %v: %v", a.config.BinaryPath, err)) + a.sendResults(retResults, fmt.Errorf("failed to find binary in %v: %w", a.config.BinaryPath, err)) return } file, err := os.CreateTemp("", "gitleaks") if err != nil { - a.sendResults(retResults, fmt.Errorf("failed to create temp file. %v", err)) + a.sendResults(retResults, fmt.Errorf("failed to create temp file. %w", err)) return } defer func() { @@ -81,18 +81,18 @@ func (a *Scanner) Run(sourceType utils.SourceType, userInput string) error { a.logger.Infof("Running gitleaks command: %v", cmd.String()) _, err = sharedutils.RunCommand(cmd) if err != nil { - a.sendResults(retResults, fmt.Errorf("failed to run gitleaks command: %v", err)) + a.sendResults(retResults, fmt.Errorf("failed to run gitleaks command: %w", err)) return } out, err := os.ReadFile(reportPath) if err != nil { - a.sendResults(retResults, fmt.Errorf("failed to read report file from path %v: %v", reportPath, err)) + a.sendResults(retResults, fmt.Errorf("failed to read report file from path %v: %w", reportPath, err)) return } if err := json.Unmarshal(out, &retResults.Findings); err != nil { - a.sendResults(retResults, fmt.Errorf("failed to unmarshal results. out: %s. err: %v", out, err)) + a.sendResults(retResults, fmt.Errorf("failed to unmarshal results. out: %s. err: %w", out, err)) return } a.sendResults(retResults, nil) diff --git a/pkg/shared/families/utils/utils.go b/pkg/shared/families/utils/utils.go index 3fe90dc95..b83912c8f 100644 --- a/pkg/shared/families/utils/utils.go +++ b/pkg/shared/families/utils/utils.go @@ -67,7 +67,7 @@ func GetInputSize(input types.Input) (int64, error) { // calculate the size and add it to the cache size, err := DirSizeMB(input.Input) if err != nil { - return 0, fmt.Errorf("failed to get dir size: %v", err) + return 0, fmt.Errorf("failed to get dir size: %w", err) } InputSizesCache[input.Input] = size return size, nil @@ -98,7 +98,7 @@ func DirSizeMB(path string) (int64, error) { } if err := filepath.WalkDir(path, readSize); err != nil { - return 0, fmt.Errorf("failed to walk dir: %v", err) + return 0, fmt.Errorf("failed to walk dir: %w", err) } return dirSizeBytes / megaBytesToBytes, nil diff --git a/pkg/shared/families/vulnerabilities/family.go b/pkg/shared/families/vulnerabilities/family.go index 66c95ae50..14edc02a9 100644 --- a/pkg/shared/families/vulnerabilities/family.go +++ b/pkg/shared/families/vulnerabilities/family.go @@ -56,7 +56,7 @@ func (v Vulnerabilities) Run(ctx context.Context, res *results.Results) (interfa sbomResults, err := results.GetResult[*sbom.Results](res) if err != nil { - return nil, fmt.Errorf("failed to get sbom results: %v", err) + return nil, fmt.Errorf("failed to get sbom results: %w", err) } sbomBytes, err := sbomResults.EncodeToBytes("cyclonedx-json") @@ -66,7 +66,7 @@ func (v Vulnerabilities) Run(ctx context.Context, res *results.Results) (interfa // TODO: need to avoid writing sbom to file if err := os.WriteFile(sbomTempFilePath, sbomBytes, 0o600 /* read & write */); err != nil { // nolint:gomnd,gofumpt - return nil, fmt.Errorf("failed to write sbom to file: %v", err) + return nil, fmt.Errorf("failed to write sbom to file: %w", err) } v.conf.Inputs = append(v.conf.Inputs, types.Input{ diff --git a/pkg/shared/findingkey/common.go b/pkg/shared/findingkey/common.go index 0aac4312c..b337d1943 100644 --- a/pkg/shared/findingkey/common.go +++ b/pkg/shared/findingkey/common.go @@ -24,7 +24,7 @@ import ( func GenerateFindingKey(findingInfo *models.Finding_FindingInfo) (string, error) { value, err := findingInfo.ValueByDiscriminator() if err != nil { - return "", fmt.Errorf("failed to value by discriminator from finding info: %v", err) + return "", fmt.Errorf("failed to value by discriminator from finding info: %w", err) } switch info := value.(type) { diff --git a/pkg/uibackend/rest/dashboard_findings_impact.go b/pkg/uibackend/rest/dashboard_findings_impact.go index d3a4243fe..c46a04dc3 100644 --- a/pkg/uibackend/rest/dashboard_findings_impact.go +++ b/pkg/uibackend/rest/dashboard_findings_impact.go @@ -93,31 +93,31 @@ func (s *ServerImpl) recalculateFindingsImpact(ctx context.Context) { func (s *ServerImpl) getFindingsImpact(ctx context.Context) (models.FindingsImpact, error) { exploits, err := s.getExploitsFindingImpact(ctx) if err != nil { - return models.FindingsImpact{}, fmt.Errorf("failed to get exploits finding impact: %v", err) + return models.FindingsImpact{}, fmt.Errorf("failed to get exploits finding impact: %w", err) } malware, err := s.getMalwareFindingImpact(ctx) if err != nil { - return models.FindingsImpact{}, fmt.Errorf("failed to get malware finding impact: %v", err) + return models.FindingsImpact{}, fmt.Errorf("failed to get malware finding impact: %w", err) } misconfigurations, err := s.getMisconfigurationsFindingImpact(ctx) if err != nil { - return models.FindingsImpact{}, fmt.Errorf("failed to get misconfigurations finding impact: %v", err) + return models.FindingsImpact{}, fmt.Errorf("failed to get misconfigurations finding impact: %w", err) } rootkits, err := s.getRootkitsFindingImpact(ctx) if err != nil { - return models.FindingsImpact{}, fmt.Errorf("failed to get rootkits finding impact: %v", err) + return models.FindingsImpact{}, fmt.Errorf("failed to get rootkits finding impact: %w", err) } secrets, err := s.getSecretsFindingImpact(ctx) if err != nil { - return models.FindingsImpact{}, fmt.Errorf("failed to get secrets finding impact: %v", err) + return models.FindingsImpact{}, fmt.Errorf("failed to get secrets finding impact: %w", err) } vulnerabilities, err := s.getVulnerabilitiesFindingImpact(ctx) if err != nil { - return models.FindingsImpact{}, fmt.Errorf("failed to get vulnerabilities finding impact: %v", err) + return models.FindingsImpact{}, fmt.Errorf("failed to get vulnerabilities finding impact: %w", err) } packages, err := s.getPackagesFindingImpact(ctx) if err != nil { - return models.FindingsImpact{}, fmt.Errorf("failed to get packages finding impact: %v", err) + return models.FindingsImpact{}, fmt.Errorf("failed to get packages finding impact: %w", err) } return models.FindingsImpact{ @@ -136,14 +136,14 @@ func (s *ServerImpl) getExploitsFindingImpact(ctx context.Context) ([]models.Exp findingAssetMapCount, err := s.getFindingToAssetCountMap(ctx, "Exploit") if err != nil { - return nil, fmt.Errorf("failed to get finding to asset count map: %v", err) + return nil, fmt.Errorf("failed to get finding to asset count map: %w", err) } findingInfoCountSlice := getSortedFindingInfoCountSlice(findingAssetMapCount) ret, err = createFindingsImpact(findingInfoCountSlice, createExploitFindingImpact) if err != nil { - return nil, fmt.Errorf("failed to create exploit finding impact: %v", err) + return nil, fmt.Errorf("failed to create exploit finding impact: %w", err) } return ret, nil @@ -152,7 +152,7 @@ func (s *ServerImpl) getExploitsFindingImpact(ctx context.Context) ([]models.Exp func createExploitFindingImpact(findingInfo *backendmodels.Finding_FindingInfo, count int) (models.ExploitFindingImpact, error) { info, err := findingInfo.AsExploitFindingInfo() if err != nil { - return models.ExploitFindingImpact{}, fmt.Errorf("failed to convert finding info to exploit info: %v", err) + return models.ExploitFindingImpact{}, fmt.Errorf("failed to convert finding info to exploit info: %w", err) } return models.ExploitFindingImpact{ @@ -173,14 +173,14 @@ func (s *ServerImpl) getMalwareFindingImpact(ctx context.Context) ([]models.Malw findingAssetMapCount, err := s.getFindingToAssetCountMap(ctx, "Malware") if err != nil { - return nil, fmt.Errorf("failed to get finding asset map count: %v", err) + return nil, fmt.Errorf("failed to get finding asset map count: %w", err) } findingInfoCountSlice := getSortedFindingInfoCountSlice(findingAssetMapCount) ret, err = createFindingsImpact(findingInfoCountSlice, createMalwareFindingImpact) if err != nil { - return nil, fmt.Errorf("failed to create malware finding impact: %v", err) + return nil, fmt.Errorf("failed to create malware finding impact: %w", err) } return ret, nil @@ -189,7 +189,7 @@ func (s *ServerImpl) getMalwareFindingImpact(ctx context.Context) ([]models.Malw func createMalwareFindingImpact(findingInfo *backendmodels.Finding_FindingInfo, count int) (models.MalwareFindingImpact, error) { info, err := findingInfo.AsMalwareFindingInfo() if err != nil { - return models.MalwareFindingImpact{}, fmt.Errorf("failed to convert finding info to malware info: %v", err) + return models.MalwareFindingImpact{}, fmt.Errorf("failed to convert finding info to malware info: %w", err) } return models.MalwareFindingImpact{ @@ -207,14 +207,14 @@ func (s *ServerImpl) getMisconfigurationsFindingImpact(ctx context.Context) ([]m findingAssetMapCount, err := s.getFindingToAssetCountMap(ctx, "Misconfiguration") if err != nil { - return nil, fmt.Errorf("failed to get finding asset map count: %v", err) + return nil, fmt.Errorf("failed to get finding asset map count: %w", err) } findingInfoCountSlice := getSortedFindingInfoCountSlice(findingAssetMapCount) ret, err = createFindingsImpact(findingInfoCountSlice, createMisconfigurationFindingImpact) if err != nil { - return nil, fmt.Errorf("failed to create misconfiguration finding impact: %v", err) + return nil, fmt.Errorf("failed to create misconfiguration finding impact: %w", err) } return ret, nil @@ -223,7 +223,7 @@ func (s *ServerImpl) getMisconfigurationsFindingImpact(ctx context.Context) ([]m func createMisconfigurationFindingImpact(findingInfo *backendmodels.Finding_FindingInfo, count int) (models.MisconfigurationFindingImpact, error) { info, err := findingInfo.AsMisconfigurationFindingInfo() if err != nil { - return models.MisconfigurationFindingImpact{}, fmt.Errorf("failed to convert finding info to misconfiguration info: %v", err) + return models.MisconfigurationFindingImpact{}, fmt.Errorf("failed to convert finding info to misconfiguration info: %w", err) } return models.MisconfigurationFindingImpact{ @@ -250,14 +250,14 @@ func (s *ServerImpl) getRootkitsFindingImpact(ctx context.Context) ([]models.Roo findingAssetMapCount, err := s.getFindingToAssetCountMap(ctx, "Rootkit") if err != nil { - return nil, fmt.Errorf("failed to get finding asset map count: %v", err) + return nil, fmt.Errorf("failed to get finding asset map count: %w", err) } findingInfoCountSlice := getSortedFindingInfoCountSlice(findingAssetMapCount) ret, err = createFindingsImpact(findingInfoCountSlice, createRootkitFindingImpact) if err != nil { - return nil, fmt.Errorf("failed to create rootkit finding impact: %v", err) + return nil, fmt.Errorf("failed to create rootkit finding impact: %w", err) } return ret, nil @@ -266,7 +266,7 @@ func (s *ServerImpl) getRootkitsFindingImpact(ctx context.Context) ([]models.Roo func createRootkitFindingImpact(findingInfo *backendmodels.Finding_FindingInfo, count int) (models.RootkitFindingImpact, error) { info, err := findingInfo.AsRootkitFindingInfo() if err != nil { - return models.RootkitFindingImpact{}, fmt.Errorf("failed to convert finding info to rootkit info: %v", err) + return models.RootkitFindingImpact{}, fmt.Errorf("failed to convert finding info to rootkit info: %w", err) } return models.RootkitFindingImpact{ @@ -287,14 +287,14 @@ func (s *ServerImpl) getSecretsFindingImpact(ctx context.Context) ([]models.Secr findingAssetMapCount, err := s.getFindingToAssetCountMap(ctx, "Secret") if err != nil { - return nil, fmt.Errorf("failed to get finding asset map count: %v", err) + return nil, fmt.Errorf("failed to get finding asset map count: %w", err) } findingInfoCountSlice := getSortedFindingInfoCountSlice(findingAssetMapCount) ret, err = createFindingsImpact(findingInfoCountSlice, createSecretFindingImpact) if err != nil { - return nil, fmt.Errorf("failed to create secret finding impact: %v", err) + return nil, fmt.Errorf("failed to create secret finding impact: %w", err) } return ret, nil @@ -303,7 +303,7 @@ func (s *ServerImpl) getSecretsFindingImpact(ctx context.Context) ([]models.Secr func createSecretFindingImpact(findingInfo *backendmodels.Finding_FindingInfo, count int) (models.SecretFindingImpact, error) { info, err := findingInfo.AsSecretFindingInfo() if err != nil { - return models.SecretFindingImpact{}, fmt.Errorf("failed to convert finding info to secret info: %v", err) + return models.SecretFindingImpact{}, fmt.Errorf("failed to convert finding info to secret info: %w", err) } return models.SecretFindingImpact{ @@ -328,7 +328,7 @@ func (s *ServerImpl) getVulnerabilitiesFindingImpact(ctx context.Context) ([]mod for _, severity := range orderedSeveritiesValues { findingAssetMapCount, err := s.getVulnerabilityFindingToAssetCountMap(ctx, severity) if err != nil { - return nil, fmt.Errorf("failed to get finding asset map count: %v", err) + return nil, fmt.Errorf("failed to get finding asset map count: %w", err) } findingInfoCountSliceForSeverity := getSortedFindingInfoCountSlice(findingAssetMapCount) @@ -341,7 +341,7 @@ func (s *ServerImpl) getVulnerabilitiesFindingImpact(ctx context.Context) ([]mod ret, err := createFindingsImpact(findingInfoCountSlice, createVulnerabilityFindingImpact) if err != nil { - return nil, fmt.Errorf("failed to create vulnerability finding impact: %v", err) + return nil, fmt.Errorf("failed to create vulnerability finding impact: %w", err) } return ret, nil @@ -350,7 +350,7 @@ func (s *ServerImpl) getVulnerabilitiesFindingImpact(ctx context.Context) ([]mod func createVulnerabilityFindingImpact(findingInfo *backendmodels.Finding_FindingInfo, count int) (models.VulnerabilityFindingImpact, error) { info, err := findingInfo.AsVulnerabilityFindingInfo() if err != nil { - return models.VulnerabilityFindingImpact{}, fmt.Errorf("failed to convert finding info to vulnerability info: %v", err) + return models.VulnerabilityFindingImpact{}, fmt.Errorf("failed to convert finding info to vulnerability info: %w", err) } return models.VulnerabilityFindingImpact{ @@ -416,14 +416,14 @@ func (s *ServerImpl) getPackagesFindingImpact(ctx context.Context) ([]models.Pac findingAssetMapCount, err := s.getFindingToAssetCountMap(ctx, "Package") if err != nil { - return nil, fmt.Errorf("failed to get finding asset map count: %v", err) + return nil, fmt.Errorf("failed to get finding asset map count: %w", err) } findingInfoCountSlice := getSortedFindingInfoCountSlice(findingAssetMapCount) ret, err = createFindingsImpact(findingInfoCountSlice, createPackageFindingImpact) if err != nil { - return nil, fmt.Errorf("failed to create package finding impact: %v", err) + return nil, fmt.Errorf("failed to create package finding impact: %w", err) } return ret, nil @@ -432,7 +432,7 @@ func (s *ServerImpl) getPackagesFindingImpact(ctx context.Context) ([]models.Pac func createPackageFindingImpact(findingInfo *backendmodels.Finding_FindingInfo, count int) (models.PackageFindingImpact, error) { info, err := findingInfo.AsPackageFindingInfo() if err != nil { - return models.PackageFindingImpact{}, fmt.Errorf("failed to convert finding info to p1ackage info: %v", err) + return models.PackageFindingImpact{}, fmt.Errorf("failed to convert finding info to package info: %w", err) } return models.PackageFindingImpact{ @@ -470,13 +470,13 @@ func (s *ServerImpl) getFindingToAssetCountMapWithFilter(ctx context.Context, fi Skip: &skip, }) if err != nil { - return nil, fmt.Errorf("failed to get findings: %v", err) + return nil, fmt.Errorf("failed to get findings: %w", err) } findings := *f.Items log.Debugf("Got findings %+v", findings) if err = processFindings(findings, findingAssetMap, findingToAssetCount); err != nil { - return nil, fmt.Errorf("failed to process findings: %v", err) + return nil, fmt.Errorf("failed to process findings: %w", err) } if len(findings) < top { @@ -499,7 +499,7 @@ func processFindings(findings []backendmodels.Finding, findingAssetMap map[findi for idx, item := range findings { fKey, err := findingkey.GenerateFindingKey(item.FindingInfo) if err != nil { - return fmt.Errorf("failed to generate finding key: %v", err) + return fmt.Errorf("failed to generate finding key: %w", err) } fsKey := findingAssetKey{ FindingKey: fKey, @@ -545,7 +545,7 @@ func createFindingsImpact[T any](findingInfoCountSlice []findingInfoCount, creat infoCount := findingInfoCountSlice[i] findingImpact, err := createFunc(infoCount.FindingInfo, infoCount.AssetCount) if err != nil { - return nil, fmt.Errorf("failed to create finding impact: %v", err) + return nil, fmt.Errorf("failed to create finding impact: %w", err) } ret = append(ret, findingImpact) } diff --git a/pkg/uibackend/rest/dashboard_findings_trends.go b/pkg/uibackend/rest/dashboard_findings_trends.go index 05bde69c6..4790fd23c 100644 --- a/pkg/uibackend/rest/dashboard_findings_trends.go +++ b/pkg/uibackend/rest/dashboard_findings_trends.go @@ -54,7 +54,7 @@ func (s *ServerImpl) GetDashboardFindingsTrends(ctx echo.Context, params models. defer wg.Done() trends, err := s.getFindingTrendsForFindingType(reqCtx, ft, times) if err != nil { - errs <- fmt.Errorf("failed to get %s trends: %v", ft, err) + errs <- fmt.Errorf("failed to get %s trends: %w", ft, err) return } findingsTrendsChan <- trends @@ -108,7 +108,7 @@ func (s *ServerImpl) getFindingTrendsForFindingType(ctx context.Context, finding for i, point := range times { trend, err := s.getFindingTrendPerPoint(ctx, findingType, point) if err != nil { - return models.FindingTrends{}, fmt.Errorf("failed to get finding trend: %v", err) + return models.FindingTrends{}, fmt.Errorf("failed to get finding trend: %w", err) } trends[i] = trend } @@ -131,7 +131,7 @@ func (s *ServerImpl) getFindingTrendPerPoint(ctx context.Context, findingType mo Top: utils.PointerTo(0), }) if err != nil { - return models.FindingTrend{}, fmt.Errorf("failed to get findings for the given point: %v", err) + return models.FindingTrend{}, fmt.Errorf("failed to get findings for the given point: %w", err) } return models.FindingTrend{ diff --git a/pkg/uibackend/rest/dashboard_riskiest_assets.go b/pkg/uibackend/rest/dashboard_riskiest_assets.go index fbcf039de..a6ad49b8e 100644 --- a/pkg/uibackend/rest/dashboard_riskiest_assets.go +++ b/pkg/uibackend/rest/dashboard_riskiest_assets.go @@ -104,7 +104,7 @@ func (s *ServerImpl) GetDashboardRiskiestAssets(ctx echo.Context) error { func (s *ServerImpl) getRiskiestAssetsForFindingType(ctx context.Context, findingType backendmodels.ScanType) ([]models.RiskyAsset, error) { riskiestAssets, err := s.getRiskiestAssetsPerFinding(ctx, findingType) if err != nil { - return nil, fmt.Errorf("failed to get riskiest assets: %v", err) + return nil, fmt.Errorf("failed to get riskiest assets: %w", err) } return toAPIRiskyAssets(*riskiestAssets.Items, findingType), nil @@ -113,7 +113,7 @@ func (s *ServerImpl) getRiskiestAssetsForFindingType(ctx context.Context, findin func (s *ServerImpl) getRiskiestAssetsForVulnerabilityType(ctx context.Context) ([]models.VulnerabilityRiskyAsset, error) { assets, err := s.getRiskiestAssetsPerFinding(ctx, backendmodels.VULNERABILITY) if err != nil { - return nil, fmt.Errorf("failed to get riskiest assets: %v", err) + return nil, fmt.Errorf("failed to get riskiest assets: %w", err) } return toAPIVulnerabilityRiskyAssets(*assets.Items), nil @@ -122,7 +122,7 @@ func (s *ServerImpl) getRiskiestAssetsForVulnerabilityType(ctx context.Context) func (s *ServerImpl) getRiskiestAssetsPerFinding(ctx context.Context, findingType backendmodels.ScanType) (*backendmodels.Assets, error) { totalFindingField, err := getTotalFindingFieldName(findingType) if err != nil { - return nil, fmt.Errorf("failed to get total findings field name: %v", err) + return nil, fmt.Errorf("failed to get total findings field name: %w", err) } riskiestAssets, err := s.BackendClient.GetAssets(ctx, backendmodels.GetAssetsParams{ @@ -132,7 +132,7 @@ func (s *ServerImpl) getRiskiestAssetsPerFinding(ctx context.Context, findingTyp Filter: utils.PointerTo(fmt.Sprintf("terminatedOn eq null and summary/%s ne null", totalFindingField)), }) if err != nil { - return nil, fmt.Errorf("failed to get assets: %v", err) + return nil, fmt.Errorf("failed to get assets: %w", err) } return riskiestAssets, nil @@ -243,7 +243,7 @@ func containerImageInfoToAssetInfo(info backendmodels.ContainerImageInfo) (*mode func vmInfoToAssetInfo(info backendmodels.VMInfo) (*models.AssetInfo, error) { assetType, err := getVMAssetType(info.InstanceProvider) if err != nil { - return nil, fmt.Errorf("failed to get asset type: %v", err) + return nil, fmt.Errorf("failed to get asset type: %w", err) } return &models.AssetInfo{ Location: &info.Location,