Browse Source

errors.Wrap -> fmt.Errorf; clean up imports (#2297)

mmetc 2 years ago
parent
commit
fddf597040

+ 3 - 5
cmd/crowdsec-cli/alerts.go

@@ -15,7 +15,6 @@ import (
 
 
 	"github.com/fatih/color"
 	"github.com/fatih/color"
 	"github.com/go-openapi/strfmt"
 	"github.com/go-openapi/strfmt"
-	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 	"github.com/spf13/cobra"
 	"github.com/spf13/cobra"
 	"gopkg.in/yaml.v2"
 	"gopkg.in/yaml.v2"
@@ -155,7 +154,6 @@ var alertTemplate = `
 
 
 `
 `
 
 
-
 func DisplayOneAlert(alert *models.Alert, withDetail bool) error {
 func DisplayOneAlert(alert *models.Alert, withDetail bool) error {
 	if csConfig.Cscli.Output == "human" {
 	if csConfig.Cscli.Output == "human" {
 		tmpl, err := template.New("alert").Parse(alertTemplate)
 		tmpl, err := template.New("alert").Parse(alertTemplate)
@@ -211,11 +209,11 @@ func NewAlertsCmd() *cobra.Command {
 		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
 		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
 			var err error
 			var err error
 			if err := csConfig.LoadAPIClient(); err != nil {
 			if err := csConfig.LoadAPIClient(); err != nil {
-				return errors.Wrap(err, "loading api client")
+				return fmt.Errorf("loading api client: %w", err)
 			}
 			}
 			apiURL, err := url.Parse(csConfig.API.Client.Credentials.URL)
 			apiURL, err := url.Parse(csConfig.API.Client.Credentials.URL)
 			if err != nil {
 			if err != nil {
-				return errors.Wrapf(err, "parsing api url %s", apiURL)
+				return fmt.Errorf("parsing api url %s: %w", apiURL, err)
 			}
 			}
 			Client, err = apiclient.NewClient(&apiclient.Config{
 			Client, err = apiclient.NewClient(&apiclient.Config{
 				MachineID:     csConfig.API.Client.Credentials.Login,
 				MachineID:     csConfig.API.Client.Credentials.Login,
@@ -226,7 +224,7 @@ func NewAlertsCmd() *cobra.Command {
 			})
 			})
 
 
 			if err != nil {
 			if err != nil {
-				return errors.Wrap(err, "new api client")
+				return fmt.Errorf("new api client: %w", err)
 			}
 			}
 			return nil
 			return nil
 		},
 		},

+ 11 - 8
cmd/crowdsec-cli/capi.go

@@ -6,6 +6,11 @@ import (
 	"net/url"
 	"net/url"
 	"os"
 	"os"
 
 
+	"github.com/go-openapi/strfmt"
+	log "github.com/sirupsen/logrus"
+	"github.com/spf13/cobra"
+	"gopkg.in/yaml.v2"
+
 	"github.com/crowdsecurity/go-cs-lib/pkg/version"
 	"github.com/crowdsecurity/go-cs-lib/pkg/version"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/apiclient"
 	"github.com/crowdsecurity/crowdsec/pkg/apiclient"
@@ -14,11 +19,6 @@ import (
 	"github.com/crowdsecurity/crowdsec/pkg/fflag"
 	"github.com/crowdsecurity/crowdsec/pkg/fflag"
 	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/crowdsecurity/crowdsec/pkg/types"
 	"github.com/crowdsecurity/crowdsec/pkg/types"
-	"github.com/go-openapi/strfmt"
-	"github.com/pkg/errors"
-	log "github.com/sirupsen/logrus"
-	"github.com/spf13/cobra"
-	"gopkg.in/yaml.v2"
 )
 )
 
 
 const CAPIBaseURL string = "https://api.crowdsec.net/"
 const CAPIBaseURL string = "https://api.crowdsec.net/"
@@ -31,8 +31,11 @@ func NewCapiCmd() *cobra.Command {
 		Args:              cobra.MinimumNArgs(1),
 		Args:              cobra.MinimumNArgs(1),
 		DisableAutoGenTag: true,
 		DisableAutoGenTag: true,
 		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
 		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
-			if err := csConfig.LoadAPIServer(); err != nil || csConfig.DisableAPI {
-				return errors.Wrap(err, "Local API is disabled, please run this command on the local API machine")
+			if err := csConfig.LoadAPIServer(); err != nil {
+				return fmt.Errorf("local API is disabled, please run this command on the local API machine: %w", err)
+			}
+			if csConfig.DisableAPI {
+				return nil
 			}
 			}
 			if csConfig.API.Server.OnlineClient == nil {
 			if csConfig.API.Server.OnlineClient == nil {
 				log.Fatalf("no configuration for Central API in '%s'", *csConfig.FilePath)
 				log.Fatalf("no configuration for Central API in '%s'", *csConfig.FilePath)
@@ -133,7 +136,7 @@ func NewCapiStatusCmd() *cobra.Command {
 		Run: func(cmd *cobra.Command, args []string) {
 		Run: func(cmd *cobra.Command, args []string) {
 			var err error
 			var err error
 			if csConfig.API.Server == nil {
 			if csConfig.API.Server == nil {
-				log.Fatalln("There is no configuration on 'api.server:'")
+				log.Fatal("There is no configuration on 'api.server:'")
 			}
 			}
 			if csConfig.API.Server.OnlineClient == nil {
 			if csConfig.API.Server.OnlineClient == nil {
 				log.Fatalf("Please provide credentials for the Central API (CAPI) in '%s'", csConfig.API.Server.OnlineClient.CredentialsFilePath)
 				log.Fatalf("Please provide credentials for the Central API (CAPI) in '%s'", csConfig.API.Server.OnlineClient.CredentialsFilePath)

+ 12 - 15
cmd/crowdsec-cli/config_backup.go

@@ -5,7 +5,6 @@ import (
 	"os"
 	"os"
 	"path/filepath"
 	"path/filepath"
 
 
-	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 	"github.com/spf13/cobra"
 	"github.com/spf13/cobra"
 
 
@@ -33,17 +32,17 @@ func backupConfigToDirectory(dirPath string) error {
 	/*if parent directory doesn't exist, bail out. create final dir with Mkdir*/
 	/*if parent directory doesn't exist, bail out. create final dir with Mkdir*/
 	parentDir := filepath.Dir(dirPath)
 	parentDir := filepath.Dir(dirPath)
 	if _, err := os.Stat(parentDir); err != nil {
 	if _, err := os.Stat(parentDir); err != nil {
-		return errors.Wrapf(err, "while checking parent directory %s existence", parentDir)
+		return fmt.Errorf("while checking parent directory %s existence: %w", parentDir, err)
 	}
 	}
 
 
 	if err = os.Mkdir(dirPath, 0o700); err != nil {
 	if err = os.Mkdir(dirPath, 0o700); err != nil {
-		return errors.Wrapf(err, "while creating %s", dirPath)
+		return fmt.Errorf("while creating %s: %w", dirPath, err)
 	}
 	}
 
 
 	if csConfig.ConfigPaths.SimulationFilePath != "" {
 	if csConfig.ConfigPaths.SimulationFilePath != "" {
 		backupSimulation := filepath.Join(dirPath, "simulation.yaml")
 		backupSimulation := filepath.Join(dirPath, "simulation.yaml")
 		if err = CopyFile(csConfig.ConfigPaths.SimulationFilePath, backupSimulation); err != nil {
 		if err = CopyFile(csConfig.ConfigPaths.SimulationFilePath, backupSimulation); err != nil {
-			return errors.Wrapf(err, "failed copy %s to %s", csConfig.ConfigPaths.SimulationFilePath, backupSimulation)
+			return fmt.Errorf("failed copy %s to %s: %w", csConfig.ConfigPaths.SimulationFilePath, backupSimulation, err)
 		}
 		}
 
 
 		log.Infof("Saved simulation to %s", backupSimulation)
 		log.Infof("Saved simulation to %s", backupSimulation)
@@ -56,13 +55,13 @@ func backupConfigToDirectory(dirPath string) error {
 	if csConfig.Crowdsec != nil && csConfig.Crowdsec.AcquisitionFilePath != "" {
 	if csConfig.Crowdsec != nil && csConfig.Crowdsec.AcquisitionFilePath != "" {
 		backupAcquisition := filepath.Join(dirPath, "acquis.yaml")
 		backupAcquisition := filepath.Join(dirPath, "acquis.yaml")
 		if err = CopyFile(csConfig.Crowdsec.AcquisitionFilePath, backupAcquisition); err != nil {
 		if err = CopyFile(csConfig.Crowdsec.AcquisitionFilePath, backupAcquisition); err != nil {
-			return fmt.Errorf("failed copy %s to %s : %s", csConfig.Crowdsec.AcquisitionFilePath, backupAcquisition, err)
+			return fmt.Errorf("failed copy %s to %s: %s", csConfig.Crowdsec.AcquisitionFilePath, backupAcquisition, err)
 		}
 		}
 	}
 	}
 
 
 	acquisBackupDir := filepath.Join(dirPath, "acquis")
 	acquisBackupDir := filepath.Join(dirPath, "acquis")
 	if err = os.Mkdir(acquisBackupDir, 0o700); err != nil {
 	if err = os.Mkdir(acquisBackupDir, 0o700); err != nil {
-		return fmt.Errorf("error while creating %s : %s", acquisBackupDir, err)
+		return fmt.Errorf("error while creating %s: %s", acquisBackupDir, err)
 	}
 	}
 
 
 	if csConfig.Crowdsec != nil && len(csConfig.Crowdsec.AcquisitionFiles) > 0 {
 	if csConfig.Crowdsec != nil && len(csConfig.Crowdsec.AcquisitionFiles) > 0 {
@@ -74,11 +73,11 @@ func backupConfigToDirectory(dirPath string) error {
 
 
 			targetFname, err := filepath.Abs(filepath.Join(acquisBackupDir, filepath.Base(acquisFile)))
 			targetFname, err := filepath.Abs(filepath.Join(acquisBackupDir, filepath.Base(acquisFile)))
 			if err != nil {
 			if err != nil {
-				return errors.Wrapf(err, "while saving %s to %s", acquisFile, acquisBackupDir)
+				return fmt.Errorf("while saving %s to %s: %w", acquisFile, acquisBackupDir, err)
 			}
 			}
 
 
 			if err = CopyFile(acquisFile, targetFname); err != nil {
 			if err = CopyFile(acquisFile, targetFname); err != nil {
-				return fmt.Errorf("failed copy %s to %s : %s", acquisFile, targetFname, err)
+				return fmt.Errorf("failed copy %s to %s: %w", acquisFile, targetFname, err)
 			}
 			}
 
 
 			log.Infof("Saved acquis %s to %s", acquisFile, targetFname)
 			log.Infof("Saved acquis %s to %s", acquisFile, targetFname)
@@ -88,7 +87,7 @@ func backupConfigToDirectory(dirPath string) error {
 	if ConfigFilePath != "" {
 	if ConfigFilePath != "" {
 		backupMain := fmt.Sprintf("%s/config.yaml", dirPath)
 		backupMain := fmt.Sprintf("%s/config.yaml", dirPath)
 		if err = CopyFile(ConfigFilePath, backupMain); err != nil {
 		if err = CopyFile(ConfigFilePath, backupMain); err != nil {
-			return fmt.Errorf("failed copy %s to %s : %s", ConfigFilePath, backupMain, err)
+			return fmt.Errorf("failed copy %s to %s: %s", ConfigFilePath, backupMain, err)
 		}
 		}
 
 
 		log.Infof("Saved default yaml to %s", backupMain)
 		log.Infof("Saved default yaml to %s", backupMain)
@@ -97,7 +96,7 @@ func backupConfigToDirectory(dirPath string) error {
 	if csConfig.API != nil && csConfig.API.Server != nil && csConfig.API.Server.OnlineClient != nil && csConfig.API.Server.OnlineClient.CredentialsFilePath != "" {
 	if csConfig.API != nil && csConfig.API.Server != nil && csConfig.API.Server.OnlineClient != nil && csConfig.API.Server.OnlineClient.CredentialsFilePath != "" {
 		backupCAPICreds := fmt.Sprintf("%s/online_api_credentials.yaml", dirPath)
 		backupCAPICreds := fmt.Sprintf("%s/online_api_credentials.yaml", dirPath)
 		if err = CopyFile(csConfig.API.Server.OnlineClient.CredentialsFilePath, backupCAPICreds); err != nil {
 		if err = CopyFile(csConfig.API.Server.OnlineClient.CredentialsFilePath, backupCAPICreds); err != nil {
-			return fmt.Errorf("failed copy %s to %s : %s", csConfig.API.Server.OnlineClient.CredentialsFilePath, backupCAPICreds, err)
+			return fmt.Errorf("failed copy %s to %s: %s", csConfig.API.Server.OnlineClient.CredentialsFilePath, backupCAPICreds, err)
 		}
 		}
 
 
 		log.Infof("Saved online API credentials to %s", backupCAPICreds)
 		log.Infof("Saved online API credentials to %s", backupCAPICreds)
@@ -106,7 +105,7 @@ func backupConfigToDirectory(dirPath string) error {
 	if csConfig.API != nil && csConfig.API.Client != nil && csConfig.API.Client.CredentialsFilePath != "" {
 	if csConfig.API != nil && csConfig.API.Client != nil && csConfig.API.Client.CredentialsFilePath != "" {
 		backupLAPICreds := fmt.Sprintf("%s/local_api_credentials.yaml", dirPath)
 		backupLAPICreds := fmt.Sprintf("%s/local_api_credentials.yaml", dirPath)
 		if err = CopyFile(csConfig.API.Client.CredentialsFilePath, backupLAPICreds); err != nil {
 		if err = CopyFile(csConfig.API.Client.CredentialsFilePath, backupLAPICreds); err != nil {
-			return fmt.Errorf("failed copy %s to %s : %s", csConfig.API.Client.CredentialsFilePath, backupLAPICreds, err)
+			return fmt.Errorf("failed copy %s to %s: %s", csConfig.API.Client.CredentialsFilePath, backupLAPICreds, err)
 		}
 		}
 
 
 		log.Infof("Saved local API credentials to %s", backupLAPICreds)
 		log.Infof("Saved local API credentials to %s", backupLAPICreds)
@@ -115,20 +114,19 @@ func backupConfigToDirectory(dirPath string) error {
 	if csConfig.API != nil && csConfig.API.Server != nil && csConfig.API.Server.ProfilesPath != "" {
 	if csConfig.API != nil && csConfig.API.Server != nil && csConfig.API.Server.ProfilesPath != "" {
 		backupProfiles := fmt.Sprintf("%s/profiles.yaml", dirPath)
 		backupProfiles := fmt.Sprintf("%s/profiles.yaml", dirPath)
 		if err = CopyFile(csConfig.API.Server.ProfilesPath, backupProfiles); err != nil {
 		if err = CopyFile(csConfig.API.Server.ProfilesPath, backupProfiles); err != nil {
-			return fmt.Errorf("failed copy %s to %s : %s", csConfig.API.Server.ProfilesPath, backupProfiles, err)
+			return fmt.Errorf("failed copy %s to %s: %s", csConfig.API.Server.ProfilesPath, backupProfiles, err)
 		}
 		}
 
 
 		log.Infof("Saved profiles to %s", backupProfiles)
 		log.Infof("Saved profiles to %s", backupProfiles)
 	}
 	}
 
 
 	if err = BackupHub(dirPath); err != nil {
 	if err = BackupHub(dirPath); err != nil {
-		return fmt.Errorf("failed to backup hub config : %s", err)
+		return fmt.Errorf("failed to backup hub config: %s", err)
 	}
 	}
 
 
 	return nil
 	return nil
 }
 }
 
 
-
 func runConfigBackup(cmd *cobra.Command, args []string) error {
 func runConfigBackup(cmd *cobra.Command, args []string) error {
 	if err := csConfig.LoadHub(); err != nil {
 	if err := csConfig.LoadHub(); err != nil {
 		return err
 		return err
@@ -146,7 +144,6 @@ func runConfigBackup(cmd *cobra.Command, args []string) error {
 	return nil
 	return nil
 }
 }
 
 
-
 func NewConfigBackupCmd() *cobra.Command {
 func NewConfigBackupCmd() *cobra.Command {
 	cmdConfigBackup := &cobra.Command{
 	cmdConfigBackup := &cobra.Command{
 		Use:   `backup "directory"`,
 		Use:   `backup "directory"`,

+ 2 - 5
cmd/crowdsec-cli/config_restore.go

@@ -7,7 +7,6 @@ import (
 	"os"
 	"os"
 	"path/filepath"
 	"path/filepath"
 
 
-	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 	"github.com/spf13/cobra"
 	"github.com/spf13/cobra"
 	"gopkg.in/yaml.v2"
 	"gopkg.in/yaml.v2"
@@ -133,7 +132,7 @@ func restoreConfigFromDirectory(dirPath string, oldBackup bool) error {
 		for _, acquisFile := range acquisFiles {
 		for _, acquisFile := range acquisFiles {
 			targetFname, err := filepath.Abs(csConfig.Crowdsec.AcquisitionDirPath + "/" + filepath.Base(acquisFile))
 			targetFname, err := filepath.Abs(csConfig.Crowdsec.AcquisitionDirPath + "/" + filepath.Base(acquisFile))
 			if err != nil {
 			if err != nil {
-				return errors.Wrapf(err, "while saving %s to %s", acquisFile, targetFname)
+				return fmt.Errorf("while saving %s to %s: %w", acquisFile, targetFname, err)
 			}
 			}
 
 
 			log.Debugf("restoring %s to %s", acquisFile, targetFname)
 			log.Debugf("restoring %s to %s", acquisFile, targetFname)
@@ -156,7 +155,7 @@ func restoreConfigFromDirectory(dirPath string, oldBackup bool) error {
 
 
 			targetFname, err := filepath.Abs(filepath.Join(acquisBackupDir, filepath.Base(acquisFile)))
 			targetFname, err := filepath.Abs(filepath.Join(acquisBackupDir, filepath.Base(acquisFile)))
 			if err != nil {
 			if err != nil {
-				return errors.Wrapf(err, "while saving %s to %s", acquisFile, acquisBackupDir)
+				return fmt.Errorf("while saving %s to %s: %w", acquisFile, acquisBackupDir, err)
 			}
 			}
 
 
 			if err = CopyFile(acquisFile, targetFname); err != nil {
 			if err = CopyFile(acquisFile, targetFname); err != nil {
@@ -174,7 +173,6 @@ func restoreConfigFromDirectory(dirPath string, oldBackup bool) error {
 	return nil
 	return nil
 }
 }
 
 
-
 func runConfigRestore(cmd *cobra.Command, args []string) error {
 func runConfigRestore(cmd *cobra.Command, args []string) error {
 	flags := cmd.Flags()
 	flags := cmd.Flags()
 
 
@@ -199,7 +197,6 @@ func runConfigRestore(cmd *cobra.Command, args []string) error {
 	return nil
 	return nil
 }
 }
 
 
-
 func NewConfigRestoreCmd() *cobra.Command {
 func NewConfigRestoreCmd() *cobra.Command {
 	cmdConfigRestore := &cobra.Command{
 	cmdConfigRestore := &cobra.Command{
 		Use:   `restore "directory"`,
 		Use:   `restore "directory"`,

+ 3 - 4
cmd/crowdsec-cli/decisions.go

@@ -15,7 +15,6 @@ import (
 	"github.com/fatih/color"
 	"github.com/fatih/color"
 	"github.com/go-openapi/strfmt"
 	"github.com/go-openapi/strfmt"
 	"github.com/jszwec/csvutil"
 	"github.com/jszwec/csvutil"
-	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 	"github.com/spf13/cobra"
 	"github.com/spf13/cobra"
 
 
@@ -112,12 +111,12 @@ func NewDecisionsCmd() *cobra.Command {
 		DisableAutoGenTag: true,
 		DisableAutoGenTag: true,
 		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
 		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
 			if err := csConfig.LoadAPIClient(); err != nil {
 			if err := csConfig.LoadAPIClient(); err != nil {
-				return errors.Wrap(err, "loading api client")
+				return fmt.Errorf("loading api client: %w", err)
 			}
 			}
 			password := strfmt.Password(csConfig.API.Client.Credentials.Password)
 			password := strfmt.Password(csConfig.API.Client.Credentials.Password)
 			apiurl, err := url.Parse(csConfig.API.Client.Credentials.URL)
 			apiurl, err := url.Parse(csConfig.API.Client.Credentials.URL)
 			if err != nil {
 			if err != nil {
-				return errors.Wrapf(err, "parsing api url %s", csConfig.API.Client.Credentials.URL)
+				return fmt.Errorf("parsing api url %s: %w", csConfig.API.Client.Credentials.URL, err)
 			}
 			}
 			Client, err = apiclient.NewClient(&apiclient.Config{
 			Client, err = apiclient.NewClient(&apiclient.Config{
 				MachineID:     csConfig.API.Client.Credentials.Login,
 				MachineID:     csConfig.API.Client.Credentials.Login,
@@ -127,7 +126,7 @@ func NewDecisionsCmd() *cobra.Command {
 				VersionPrefix: "v1",
 				VersionPrefix: "v1",
 			})
 			})
 			if err != nil {
 			if err != nil {
-				return errors.Wrap(err, "creating api client")
+				return fmt.Errorf("creating api client: %w", err)
 			}
 			}
 			return nil
 			return nil
 		},
 		},

+ 1 - 2
cmd/crowdsec-cli/lapi.go

@@ -9,7 +9,6 @@ import (
 	"strings"
 	"strings"
 
 
 	"github.com/go-openapi/strfmt"
 	"github.com/go-openapi/strfmt"
-	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 	"github.com/spf13/cobra"
 	"github.com/spf13/cobra"
 	"golang.org/x/exp/slices"
 	"golang.org/x/exp/slices"
@@ -204,7 +203,7 @@ func NewLapiCmd() *cobra.Command {
 		DisableAutoGenTag: true,
 		DisableAutoGenTag: true,
 		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
 		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
 			if err := csConfig.LoadAPIClient(); err != nil {
 			if err := csConfig.LoadAPIClient(); err != nil {
-				return errors.Wrap(err, "loading api client")
+				return fmt.Errorf("loading api client: %w", err)
 			}
 			}
 			return nil
 			return nil
 		},
 		},

+ 25 - 33
cmd/crowdsec-cli/notifications.go

@@ -15,7 +15,6 @@ import (
 
 
 	"github.com/fatih/color"
 	"github.com/fatih/color"
 	"github.com/go-openapi/strfmt"
 	"github.com/go-openapi/strfmt"
-	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 	"github.com/spf13/cobra"
 	"github.com/spf13/cobra"
 	"gopkg.in/tomb.v2"
 	"gopkg.in/tomb.v2"
@@ -28,14 +27,12 @@ import (
 	"github.com/crowdsecurity/crowdsec/pkg/csprofiles"
 	"github.com/crowdsecurity/crowdsec/pkg/csprofiles"
 )
 )
 
 
-
 type NotificationsCfg struct {
 type NotificationsCfg struct {
 	Config   csplugin.PluginConfig  `json:"plugin_config"`
 	Config   csplugin.PluginConfig  `json:"plugin_config"`
 	Profiles []*csconfig.ProfileCfg `json:"associated_profiles"`
 	Profiles []*csconfig.ProfileCfg `json:"associated_profiles"`
 	ids      []uint
 	ids      []uint
 }
 }
 
 
-
 func NewNotificationsCmd() *cobra.Command {
 func NewNotificationsCmd() *cobra.Command {
 	var cmdNotifications = &cobra.Command{
 	var cmdNotifications = &cobra.Command{
 		Use:               "notifications [action]",
 		Use:               "notifications [action]",
@@ -57,7 +54,6 @@ func NewNotificationsCmd() *cobra.Command {
 		},
 		},
 	}
 	}
 
 
-
 	cmdNotifications.AddCommand(NewNotificationsListCmd())
 	cmdNotifications.AddCommand(NewNotificationsListCmd())
 	cmdNotifications.AddCommand(NewNotificationsInspectCmd())
 	cmdNotifications.AddCommand(NewNotificationsInspectCmd())
 	cmdNotifications.AddCommand(NewNotificationsReinjectCmd())
 	cmdNotifications.AddCommand(NewNotificationsReinjectCmd())
@@ -65,18 +61,17 @@ func NewNotificationsCmd() *cobra.Command {
 	return cmdNotifications
 	return cmdNotifications
 }
 }
 
 
-
 func getNotificationsConfiguration() (map[string]NotificationsCfg, error) {
 func getNotificationsConfiguration() (map[string]NotificationsCfg, error) {
 	pcfgs := map[string]csplugin.PluginConfig{}
 	pcfgs := map[string]csplugin.PluginConfig{}
 	wf := func(path string, info fs.FileInfo, err error) error {
 	wf := func(path string, info fs.FileInfo, err error) error {
 		if info == nil {
 		if info == nil {
-			return errors.Wrapf(err, "error while traversing directory %s", path)
+			return fmt.Errorf("error while traversing directory %s: %w", path, err)
 		}
 		}
 		name := filepath.Join(csConfig.ConfigPaths.NotificationDir, info.Name()) //Avoid calling info.Name() twice
 		name := filepath.Join(csConfig.ConfigPaths.NotificationDir, info.Name()) //Avoid calling info.Name() twice
 		if (strings.HasSuffix(name, "yaml") || strings.HasSuffix(name, "yml")) && !(info.IsDir()) {
 		if (strings.HasSuffix(name, "yaml") || strings.HasSuffix(name, "yml")) && !(info.IsDir()) {
 			ts, err := csplugin.ParsePluginConfigFile(name)
 			ts, err := csplugin.ParsePluginConfigFile(name)
 			if err != nil {
 			if err != nil {
-				return errors.Wrapf(err, "Loading notifification plugin configuration with %s", name)
+				return fmt.Errorf("loading notifification plugin configuration with %s: %w", name, err)
 			}
 			}
 			for _, t := range ts {
 			for _, t := range ts {
 				pcfgs[t.Name] = t
 				pcfgs[t.Name] = t
@@ -86,14 +81,14 @@ func getNotificationsConfiguration() (map[string]NotificationsCfg, error) {
 	}
 	}
 
 
 	if err := filepath.Walk(csConfig.ConfigPaths.NotificationDir, wf); err != nil {
 	if err := filepath.Walk(csConfig.ConfigPaths.NotificationDir, wf); err != nil {
-		return nil, errors.Wrap(err, "Loading notifification plugin configuration")
+		return nil, fmt.Errorf("while loading notifification plugin configuration: %w", err)
 	}
 	}
 
 
 	// A bit of a tricky stuf now: reconcile profiles and notification plugins
 	// A bit of a tricky stuf now: reconcile profiles and notification plugins
 	ncfgs := map[string]NotificationsCfg{}
 	ncfgs := map[string]NotificationsCfg{}
 	profiles, err := csprofiles.NewProfile(csConfig.API.Server.Profiles)
 	profiles, err := csprofiles.NewProfile(csConfig.API.Server.Profiles)
 	if err != nil {
 	if err != nil {
-		return nil, errors.Wrap(err, "Cannot extract profiles from configuration")
+		return nil, fmt.Errorf("while extracting profiles from configuration: %w", err)
 	}
 	}
 	for profileID, profile := range profiles {
 	for profileID, profile := range profiles {
 	loop:
 	loop:
@@ -129,7 +124,6 @@ func getNotificationsConfiguration() (map[string]NotificationsCfg, error) {
 	return ncfgs, nil
 	return ncfgs, nil
 }
 }
 
 
-
 func NewNotificationsListCmd() *cobra.Command {
 func NewNotificationsListCmd() *cobra.Command {
 	var cmdNotificationsList = &cobra.Command{
 	var cmdNotificationsList = &cobra.Command{
 		Use:               "list",
 		Use:               "list",
@@ -141,7 +135,7 @@ func NewNotificationsListCmd() *cobra.Command {
 		RunE: func(cmd *cobra.Command, arg []string) error {
 		RunE: func(cmd *cobra.Command, arg []string) error {
 			ncfgs, err := getNotificationsConfiguration()
 			ncfgs, err := getNotificationsConfiguration()
 			if err != nil {
 			if err != nil {
-				return errors.Wrap(err, "Can't build profiles configuration")
+				return fmt.Errorf("can't build profiles configuration: %w", err)
 			}
 			}
 
 
 			if csConfig.Cscli.Output == "human" {
 			if csConfig.Cscli.Output == "human" {
@@ -149,14 +143,14 @@ func NewNotificationsListCmd() *cobra.Command {
 			} else if csConfig.Cscli.Output == "json" {
 			} else if csConfig.Cscli.Output == "json" {
 				x, err := json.MarshalIndent(ncfgs, "", " ")
 				x, err := json.MarshalIndent(ncfgs, "", " ")
 				if err != nil {
 				if err != nil {
-					return errors.New("failed to marshal notification configuration")
+					return fmt.Errorf("failed to marshal notification configuration: %w", err)
 				}
 				}
 				fmt.Printf("%s", string(x))
 				fmt.Printf("%s", string(x))
 			} else if csConfig.Cscli.Output == "raw" {
 			} else if csConfig.Cscli.Output == "raw" {
 				csvwriter := csv.NewWriter(os.Stdout)
 				csvwriter := csv.NewWriter(os.Stdout)
 				err := csvwriter.Write([]string{"Name", "Type", "Profile name"})
 				err := csvwriter.Write([]string{"Name", "Type", "Profile name"})
 				if err != nil {
 				if err != nil {
-					return errors.Wrap(err, "failed to write raw header")
+					return fmt.Errorf("failed to write raw header: %w", err)
 				}
 				}
 				for _, b := range ncfgs {
 				for _, b := range ncfgs {
 					profilesList := []string{}
 					profilesList := []string{}
@@ -165,7 +159,7 @@ func NewNotificationsListCmd() *cobra.Command {
 					}
 					}
 					err := csvwriter.Write([]string{b.Config.Name, b.Config.Type, strings.Join(profilesList, ", ")})
 					err := csvwriter.Write([]string{b.Config.Name, b.Config.Type, strings.Join(profilesList, ", ")})
 					if err != nil {
 					if err != nil {
-						return errors.Wrap(err, "failed to write raw content")
+						return fmt.Errorf("failed to write raw content: %w", err)
 					}
 					}
 				}
 				}
 				csvwriter.Flush()
 				csvwriter.Flush()
@@ -177,7 +171,6 @@ func NewNotificationsListCmd() *cobra.Command {
 	return cmdNotificationsList
 	return cmdNotificationsList
 }
 }
 
 
-
 func NewNotificationsInspectCmd() *cobra.Command {
 func NewNotificationsInspectCmd() *cobra.Command {
 	var cmdNotificationsInspect = &cobra.Command{
 	var cmdNotificationsInspect = &cobra.Command{
 		Use:               "inspect",
 		Use:               "inspect",
@@ -195,14 +188,14 @@ func NewNotificationsInspectCmd() *cobra.Command {
 			pluginName := arg[0]
 			pluginName := arg[0]
 
 
 			if pluginName == "" {
 			if pluginName == "" {
-				errors.New("Please provide a plugin name to inspect")
+				return fmt.Errorf("please provide a plugin name to inspect")
 			}
 			}
 			ncfgs, err := getNotificationsConfiguration()
 			ncfgs, err := getNotificationsConfiguration()
 			if err != nil {
 			if err != nil {
-				return errors.Wrap(err, "Can't build profiles configuration")
+				return fmt.Errorf("can't build profiles configuration: %w", err)
 			}
 			}
 			if cfg, ok = ncfgs[pluginName]; !ok {
 			if cfg, ok = ncfgs[pluginName]; !ok {
-				return errors.New("The provided plugin name doesn't exist or isn't active")
+				return fmt.Errorf("plugin '%s' does not exist or is not active", pluginName)
 			}
 			}
 
 
 			if csConfig.Cscli.Output == "human" || csConfig.Cscli.Output == "raw" {
 			if csConfig.Cscli.Output == "human" || csConfig.Cscli.Output == "raw" {
@@ -216,7 +209,7 @@ func NewNotificationsInspectCmd() *cobra.Command {
 			} else if csConfig.Cscli.Output == "json" {
 			} else if csConfig.Cscli.Output == "json" {
 				x, err := json.MarshalIndent(cfg, "", " ")
 				x, err := json.MarshalIndent(cfg, "", " ")
 				if err != nil {
 				if err != nil {
-					return errors.New("failed to marshal notification configuration")
+					return fmt.Errorf("failed to marshal notification configuration: %w", err)
 				}
 				}
 				fmt.Printf("%s", string(x))
 				fmt.Printf("%s", string(x))
 			}
 			}
@@ -227,7 +220,6 @@ func NewNotificationsInspectCmd() *cobra.Command {
 	return cmdNotificationsInspect
 	return cmdNotificationsInspect
 }
 }
 
 
-
 func NewNotificationsReinjectCmd() *cobra.Command {
 func NewNotificationsReinjectCmd() *cobra.Command {
 	var remediation bool
 	var remediation bool
 	var alertOverride string
 	var alertOverride string
@@ -250,26 +242,26 @@ cscli notifications reinject <alert_id> -a '{"remediation": true,"scenario":"not
 			)
 			)
 			if len(args) != 1 {
 			if len(args) != 1 {
 				printHelp(cmd)
 				printHelp(cmd)
-				return errors.New("Wrong number of argument: there should be one argument")
+				return fmt.Errorf("wrong number of argument: there should be one argument")
 			}
 			}
 
 
 			//first: get the alert
 			//first: get the alert
 			id, err := strconv.Atoi(args[0])
 			id, err := strconv.Atoi(args[0])
 			if err != nil {
 			if err != nil {
-				return errors.New(fmt.Sprintf("bad alert id %s", args[0]))
+				return fmt.Errorf("bad alert id %s", args[0])
 			}
 			}
 			if err := csConfig.LoadAPIClient(); err != nil {
 			if err := csConfig.LoadAPIClient(); err != nil {
-				return errors.Wrapf(err, "loading api client")
+				return fmt.Errorf("loading api client: %w", err)
 			}
 			}
 			if csConfig.API.Client == nil {
 			if csConfig.API.Client == nil {
-				return errors.New("There is no configuration on 'api_client:'")
+				return fmt.Errorf("missing configuration on 'api_client:'")
 			}
 			}
 			if csConfig.API.Client.Credentials == nil {
 			if csConfig.API.Client.Credentials == nil {
-				return errors.New(fmt.Sprintf("Please provide credentials for the API in '%s'", csConfig.API.Client.CredentialsFilePath))
+				return fmt.Errorf("missing API credentials in '%s'", csConfig.API.Client.CredentialsFilePath)
 			}
 			}
 			apiURL, err := url.Parse(csConfig.API.Client.Credentials.URL)
 			apiURL, err := url.Parse(csConfig.API.Client.Credentials.URL)
 			if err != nil {
 			if err != nil {
-				return errors.Wrapf(err, "error parsing the URL of the API")
+				return fmt.Errorf("error parsing the URL of the API: %w", err)
 			}
 			}
 			client, err := apiclient.NewClient(&apiclient.Config{
 			client, err := apiclient.NewClient(&apiclient.Config{
 				MachineID:     csConfig.API.Client.Credentials.Login,
 				MachineID:     csConfig.API.Client.Credentials.Login,
@@ -279,16 +271,16 @@ cscli notifications reinject <alert_id> -a '{"remediation": true,"scenario":"not
 				VersionPrefix: "v1",
 				VersionPrefix: "v1",
 			})
 			})
 			if err != nil {
 			if err != nil {
-				return errors.Wrapf(err, "error creating the client for the API")
+				return fmt.Errorf("error creating the client for the API: %w", err)
 			}
 			}
 			alert, _, err := client.Alerts.GetByID(context.Background(), id)
 			alert, _, err := client.Alerts.GetByID(context.Background(), id)
 			if err != nil {
 			if err != nil {
-				return errors.Wrapf(err, fmt.Sprintf("can't find alert with id %s", args[0]))
+				return fmt.Errorf("can't find alert with id %s: %w", args[0], err)
 			}
 			}
 
 
 			if alertOverride != "" {
 			if alertOverride != "" {
 				if err = json.Unmarshal([]byte(alertOverride), alert); err != nil {
 				if err = json.Unmarshal([]byte(alertOverride), alert); err != nil {
-					return errors.Wrapf(err, "Can't unmarshal the data given in the alert flag")
+					return fmt.Errorf("can't unmarshal data in the alert flag: %w", err)
 				}
 				}
 			}
 			}
 			if !remediation {
 			if !remediation {
@@ -298,7 +290,7 @@ cscli notifications reinject <alert_id> -a '{"remediation": true,"scenario":"not
 			// second we start plugins
 			// second we start plugins
 			err = pluginBroker.Init(csConfig.PluginConfig, csConfig.API.Server.Profiles, csConfig.ConfigPaths)
 			err = pluginBroker.Init(csConfig.PluginConfig, csConfig.API.Server.Profiles, csConfig.ConfigPaths)
 			if err != nil {
 			if err != nil {
-				return errors.Wrapf(err, "Can't initialize plugins")
+				return fmt.Errorf("can't initialize plugins: %w", err)
 			}
 			}
 
 
 			pluginTomb.Go(func() error {
 			pluginTomb.Go(func() error {
@@ -310,13 +302,13 @@ cscli notifications reinject <alert_id> -a '{"remediation": true,"scenario":"not
 
 
 			profiles, err := csprofiles.NewProfile(csConfig.API.Server.Profiles)
 			profiles, err := csprofiles.NewProfile(csConfig.API.Server.Profiles)
 			if err != nil {
 			if err != nil {
-				return errors.Wrap(err, "Cannot extract profiles from configuration")
+				return fmt.Errorf("cannot extract profiles from configuration: %w", err)
 			}
 			}
 
 
 			for id, profile := range profiles {
 			for id, profile := range profiles {
 				_, matched, err := profile.EvaluateProfile(alert)
 				_, matched, err := profile.EvaluateProfile(alert)
 				if err != nil {
 				if err != nil {
-					return errors.Wrapf(err, "can't evaluate profile %s", profile.Cfg.Name)
+					return fmt.Errorf("can't evaluate profile %s: %w", profile.Cfg.Name, err)
 				}
 				}
 				if !matched {
 				if !matched {
 					log.Infof("The profile %s didn't match", profile.Cfg.Name)
 					log.Infof("The profile %s didn't match", profile.Cfg.Name)
@@ -344,7 +336,7 @@ cscli notifications reinject <alert_id> -a '{"remediation": true,"scenario":"not
 			}
 			}
 
 
 			//			time.Sleep(2 * time.Second) // There's no mechanism to ensure notification has been sent
 			//			time.Sleep(2 * time.Second) // There's no mechanism to ensure notification has been sent
-			pluginTomb.Kill(errors.New("terminating"))
+			pluginTomb.Kill(fmt.Errorf("terminating"))
 			pluginTomb.Wait()
 			pluginTomb.Wait()
 			return nil
 			return nil
 		},
 		},

+ 1 - 2
cmd/crowdsec-cli/scenarios.go

@@ -4,7 +4,6 @@ import (
 	"fmt"
 	"fmt"
 
 
 	"github.com/fatih/color"
 	"github.com/fatih/color"
-	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 	"github.com/spf13/cobra"
 	"github.com/spf13/cobra"
 
 
@@ -33,7 +32,7 @@ cscli scenarios remove crowdsecurity/ssh-bf
 			}
 			}
 
 
 			if err := cwhub.SetHubBranch(); err != nil {
 			if err := cwhub.SetHubBranch(); err != nil {
-				return errors.Wrap(err, "while setting hub branch")
+				return fmt.Errorf("while setting hub branch: %w", err)
 			}
 			}
 
 
 			if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
 			if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {

+ 8 - 3
cmd/crowdsec/api.go

@@ -1,6 +1,7 @@
 package main
 package main
 
 
 import (
 import (
+	"fmt"
 	"runtime"
 	"runtime"
 	"time"
 	"time"
 
 
@@ -20,7 +21,7 @@ func initAPIServer(cConfig *csconfig.Config) (*apiserver.APIServer, error) {
 
 
 	apiServer, err := apiserver.NewServer(cConfig.API.Server)
 	apiServer, err := apiserver.NewServer(cConfig.API.Server)
 	if err != nil {
 	if err != nil {
-		return nil, errors.Wrap(err, "unable to run local API")
+		return nil, fmt.Errorf("unable to run local API: %w", err)
 	}
 	}
 
 
 	if hasPlugins(cConfig.API.Server.Profiles) {
 	if hasPlugins(cConfig.API.Server.Profiles) {
@@ -29,23 +30,27 @@ func initAPIServer(cConfig *csconfig.Config) (*apiserver.APIServer, error) {
 		if cConfig.PluginConfig == nil && runtime.GOOS != "windows" {
 		if cConfig.PluginConfig == nil && runtime.GOOS != "windows" {
 			return nil, errors.New("plugins are enabled, but the plugin_config section is missing in the configuration")
 			return nil, errors.New("plugins are enabled, but the plugin_config section is missing in the configuration")
 		}
 		}
+
 		if cConfig.ConfigPaths.NotificationDir == "" {
 		if cConfig.ConfigPaths.NotificationDir == "" {
 			return nil, errors.New("plugins are enabled, but config_paths.notification_dir is not defined")
 			return nil, errors.New("plugins are enabled, but config_paths.notification_dir is not defined")
 		}
 		}
+
 		if cConfig.ConfigPaths.PluginDir == "" {
 		if cConfig.ConfigPaths.PluginDir == "" {
 			return nil, errors.New("plugins are enabled, but config_paths.plugin_dir is not defined")
 			return nil, errors.New("plugins are enabled, but config_paths.plugin_dir is not defined")
 		}
 		}
+
 		err = pluginBroker.Init(cConfig.PluginConfig, cConfig.API.Server.Profiles, cConfig.ConfigPaths)
 		err = pluginBroker.Init(cConfig.PluginConfig, cConfig.API.Server.Profiles, cConfig.ConfigPaths)
 		if err != nil {
 		if err != nil {
-			return nil, errors.Wrap(err, "unable to run local API")
+			return nil, fmt.Errorf("unable to run plugin broker: %w", err)
 		}
 		}
+
 		log.Info("initiated plugin broker")
 		log.Info("initiated plugin broker")
 		apiServer.AttachPluginBroker(&pluginBroker)
 		apiServer.AttachPluginBroker(&pluginBroker)
 	}
 	}
 
 
 	err = apiServer.InitController()
 	err = apiServer.InitController()
 	if err != nil {
 	if err != nil {
-		return nil, errors.Wrap(err, "unable to run local API")
+		return nil, fmt.Errorf("unable to run local API: %w", err)
 	}
 	}
 
 
 	return apiServer, nil
 	return apiServer, nil

+ 4 - 5
cmd/crowdsec/crowdsec.go

@@ -3,10 +3,12 @@ package main
 import (
 import (
 	"fmt"
 	"fmt"
 	"os"
 	"os"
+	"path/filepath"
 	"sync"
 	"sync"
 	"time"
 	"time"
 
 
-	"path/filepath"
+	log "github.com/sirupsen/logrus"
+	"gopkg.in/yaml.v2"
 
 
 	"github.com/crowdsecurity/go-cs-lib/pkg/trace"
 	"github.com/crowdsecurity/go-cs-lib/pkg/trace"
 
 
@@ -16,9 +18,6 @@ import (
 	leaky "github.com/crowdsecurity/crowdsec/pkg/leakybucket"
 	leaky "github.com/crowdsecurity/crowdsec/pkg/leakybucket"
 	"github.com/crowdsecurity/crowdsec/pkg/parser"
 	"github.com/crowdsecurity/crowdsec/pkg/parser"
 	"github.com/crowdsecurity/crowdsec/pkg/types"
 	"github.com/crowdsecurity/crowdsec/pkg/types"
-	"github.com/pkg/errors"
-	log "github.com/sirupsen/logrus"
-	"gopkg.in/yaml.v2"
 )
 )
 
 
 func initCrowdsec(cConfig *csconfig.Config) (*parser.Parsers, error) {
 func initCrowdsec(cConfig *csconfig.Config) (*parser.Parsers, error) {
@@ -118,7 +117,7 @@ func runCrowdsec(cConfig *csconfig.Config, parsers *parser.Parsers) error {
 			aggregated = true
 			aggregated = true
 		}
 		}
 		if err := acquisition.GetMetrics(dataSources, aggregated); err != nil {
 		if err := acquisition.GetMetrics(dataSources, aggregated); err != nil {
-			return errors.Wrap(err, "while fetching prometheus metrics for datasources.")
+			return fmt.Errorf("while fetching prometheus metrics for datasources: %w", err)
 		}
 		}
 
 
 	}
 	}

+ 8 - 8
cmd/crowdsec/main.go

@@ -51,14 +51,14 @@ var (
 )
 )
 
 
 type Flags struct {
 type Flags struct {
-	ConfigFile     string
+	ConfigFile string
 
 
-	LogLevelTrace  bool
-	LogLevelDebug  bool
-	LogLevelInfo   bool
-	LogLevelWarn   bool
-	LogLevelError  bool
-	LogLevelFatal  bool
+	LogLevelTrace bool
+	LogLevelDebug bool
+	LogLevelInfo  bool
+	LogLevelWarn  bool
+	LogLevelError bool
+	LogLevelFatal bool
 
 
 	PrintVersion   bool
 	PrintVersion   bool
 	SingleFileType string
 	SingleFileType string
@@ -110,7 +110,7 @@ func LoadAcquisition(cConfig *csconfig.Config) error {
 
 
 		dataSources, err = acquisition.LoadAcquisitionFromDSN(flags.OneShotDSN, flags.Labels, flags.Transform)
 		dataSources, err = acquisition.LoadAcquisitionFromDSN(flags.OneShotDSN, flags.Labels, flags.Transform)
 		if err != nil {
 		if err != nil {
-			return errors.Wrapf(err, "failed to configure datasource for %s", flags.OneShotDSN)
+			return fmt.Errorf("failed to configure datasource for %s: %w", flags.OneShotDSN, err)
 		}
 		}
 	} else {
 	} else {
 		dataSources, err = acquisition.LoadAcquisitionFromFile(cConfig.Crowdsec)
 		dataSources, err = acquisition.LoadAcquisitionFromFile(cConfig.Crowdsec)

+ 8 - 7
cmd/crowdsec/output.go

@@ -7,6 +7,10 @@ import (
 	"sync"
 	"sync"
 	"time"
 	"time"
 
 
+	"github.com/go-openapi/strfmt"
+	"github.com/pkg/errors"
+	log "github.com/sirupsen/logrus"
+
 	"github.com/crowdsecurity/go-cs-lib/pkg/version"
 	"github.com/crowdsecurity/go-cs-lib/pkg/version"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/apiclient"
 	"github.com/crowdsecurity/crowdsec/pkg/apiclient"
@@ -16,9 +20,6 @@ import (
 	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/crowdsecurity/crowdsec/pkg/parser"
 	"github.com/crowdsecurity/crowdsec/pkg/parser"
 	"github.com/crowdsecurity/crowdsec/pkg/types"
 	"github.com/crowdsecurity/crowdsec/pkg/types"
-	"github.com/go-openapi/strfmt"
-	"github.com/pkg/errors"
-	log "github.com/sirupsen/logrus"
 )
 )
 
 
 func dedupAlerts(alerts []types.RuntimeAlert) ([]*models.Alert, error) {
 func dedupAlerts(alerts []types.RuntimeAlert) ([]*models.Alert, error) {
@@ -50,11 +51,11 @@ func PushAlerts(alerts []types.RuntimeAlert, client *apiclient.ApiClient) error
 	alertsToPush, err := dedupAlerts(alerts)
 	alertsToPush, err := dedupAlerts(alerts)
 
 
 	if err != nil {
 	if err != nil {
-		return errors.Wrap(err, "failed to transform alerts for api")
+		return fmt.Errorf("failed to transform alerts for api: %w", err)
 	}
 	}
 	_, _, err = client.Alerts.Add(ctx, alertsToPush)
 	_, _, err = client.Alerts.Add(ctx, alertsToPush)
 	if err != nil {
 	if err != nil {
-		return errors.Wrap(err, "failed sending alert to LAPI")
+		return fmt.Errorf("failed sending alert to LAPI: %w", err)
 	}
 	}
 	return nil
 	return nil
 }
 }
@@ -104,11 +105,11 @@ func runOutput(input chan types.Event, overflow chan types.Event, buckets *leaky
 		Scenarios: scenarios,
 		Scenarios: scenarios,
 	})
 	})
 	if err != nil {
 	if err != nil {
-		return errors.Wrapf(err, "authenticate watcher (%s)", apiConfig.Login)
+		return fmt.Errorf("authenticate watcher (%s): %w", apiConfig.Login, err)
 	}
 	}
 
 
 	if err := Client.GetClient().Transport.(*apiclient.JWTTransport).Expiration.UnmarshalText([]byte(authResp.Expire)); err != nil {
 	if err := Client.GetClient().Transport.(*apiclient.JWTTransport).Expiration.UnmarshalText([]byte(authResp.Expire)); err != nil {
-		return errors.Wrap(err, "unable to parse jwt expiration")
+		return fmt.Errorf("unable to parse jwt expiration: %w", err)
 	}
 	}
 
 
 	Client.GetClient().Transport.(*apiclient.JWTTransport).Token = authResp.Token
 	Client.GetClient().Transport.(*apiclient.JWTTransport).Token = authResp.Token

+ 6 - 7
cmd/crowdsec/run_in_svc_windows.go

@@ -3,7 +3,6 @@ package main
 import (
 import (
 	"fmt"
 	"fmt"
 
 
-	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 	"golang.org/x/sys/windows/svc"
 	"golang.org/x/sys/windows/svc"
 
 
@@ -22,7 +21,7 @@ func StartRunSvc() error {
 
 
 	isRunninginService, err := svc.IsWindowsService()
 	isRunninginService, err := svc.IsWindowsService()
 	if err != nil {
 	if err != nil {
-		return errors.Wrap(err, "failed to determine if we are running in windows service mode")
+		return fmt.Errorf("failed to determine if we are running in windows service mode: %w", err)
 	}
 	}
 	if isRunninginService {
 	if isRunninginService {
 		return runService(svcName)
 		return runService(svcName)
@@ -31,22 +30,22 @@ func StartRunSvc() error {
 	if flags.WinSvc == "Install" {
 	if flags.WinSvc == "Install" {
 		err = installService(svcName, svcDescription)
 		err = installService(svcName, svcDescription)
 		if err != nil {
 		if err != nil {
-			return errors.Wrapf(err, "failed to %s %s", flags.WinSvc, svcName)
+			return fmt.Errorf("failed to %s %s: %w", flags.WinSvc, svcName, err)
 		}
 		}
 	} else if flags.WinSvc == "Remove" {
 	} else if flags.WinSvc == "Remove" {
 		err = removeService(svcName)
 		err = removeService(svcName)
 		if err != nil {
 		if err != nil {
-			return errors.Wrapf(err, "failed to %s %s", flags.WinSvc, svcName)
+			return fmt.Errorf("failed to %s %s: %w", flags.WinSvc, svcName, err)
 		}
 		}
 	} else if flags.WinSvc == "Start" {
 	} else if flags.WinSvc == "Start" {
 		err = startService(svcName)
 		err = startService(svcName)
 		if err != nil {
 		if err != nil {
-			return errors.Wrapf(err, "failed to %s %s", flags.WinSvc, svcName)
+			return fmt.Errorf("failed to %s %s: %w", flags.WinSvc, svcName, err)
 		}
 		}
 	} else if flags.WinSvc == "Stop" {
 	} else if flags.WinSvc == "Stop" {
 		err = controlService(svcName, svc.Stop, svc.Stopped)
 		err = controlService(svcName, svc.Stop, svc.Stopped)
 		if err != nil {
 		if err != nil {
-			return errors.Wrapf(err, "failed to %s %s", flags.WinSvc, svcName)
+			return fmt.Errorf("failed to %s %s: %w", flags.WinSvc, svcName, err)
 		}
 		}
 	} else if flags.WinSvc == "" {
 	} else if flags.WinSvc == "" {
 		return WindowsRun()
 		return WindowsRun()
@@ -66,7 +65,7 @@ func WindowsRun() error {
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
-	// Configure logging
+
 	log.Infof("Crowdsec %s", version.String())
 	log.Infof("Crowdsec %s", version.String())
 
 
 	apiReady := make(chan bool, 1)
 	apiReady := make(chan bool, 1)

+ 14 - 14
cmd/crowdsec/serve.go

@@ -1,12 +1,12 @@
 package main
 package main
 
 
 import (
 import (
+	"fmt"
 	"os"
 	"os"
 	"os/signal"
 	"os/signal"
 	"syscall"
 	"syscall"
 	"time"
 	"time"
 
 
-	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 	"gopkg.in/tomb.v2"
 	"gopkg.in/tomb.v2"
 
 
@@ -68,7 +68,7 @@ func reloadHandler(sig os.Signal) (*csconfig.Config, error) {
 		}
 		}
 		apiServer, err := initAPIServer(cConfig)
 		apiServer, err := initAPIServer(cConfig)
 		if err != nil {
 		if err != nil {
-			return nil, errors.Wrap(err, "unable to init api server")
+			return nil, fmt.Errorf("unable to init api server: %w", err)
 		}
 		}
 
 
 		apiReady := make(chan bool, 1)
 		apiReady := make(chan bool, 1)
@@ -78,7 +78,7 @@ func reloadHandler(sig os.Signal) (*csconfig.Config, error) {
 	if !cConfig.DisableAgent {
 	if !cConfig.DisableAgent {
 		csParsers, err := initCrowdsec(cConfig)
 		csParsers, err := initCrowdsec(cConfig)
 		if err != nil {
 		if err != nil {
-			return nil, errors.Wrap(err, "unable to init crowdsec")
+			return nil, fmt.Errorf("unable to init crowdsec: %w", err)
 		}
 		}
 
 
 		// restore bucket state
 		// restore bucket state
@@ -180,13 +180,13 @@ func shutdownCrowdsec() error {
 func shutdown(sig os.Signal, cConfig *csconfig.Config) error {
 func shutdown(sig os.Signal, cConfig *csconfig.Config) error {
 	if !cConfig.DisableAgent {
 	if !cConfig.DisableAgent {
 		if err := shutdownCrowdsec(); err != nil {
 		if err := shutdownCrowdsec(); err != nil {
-			return errors.Wrap(err, "failed to shut down crowdsec")
+			return fmt.Errorf("failed to shut down crowdsec: %w", err)
 		}
 		}
 	}
 	}
 
 
 	if !cConfig.DisableAPI {
 	if !cConfig.DisableAPI {
 		if err := shutdownAPI(); err != nil {
 		if err := shutdownAPI(); err != nil {
-			return errors.Wrap(err, "failed to shut down api routines")
+			return fmt.Errorf("failed to shut down api routines: %w", err)
 		}
 		}
 	}
 	}
 
 
@@ -238,13 +238,13 @@ func HandleSignals(cConfig *csconfig.Config) error {
 				log.Warning("SIGHUP received, reloading")
 				log.Warning("SIGHUP received, reloading")
 
 
 				if err = shutdown(s, cConfig); err != nil {
 				if err = shutdown(s, cConfig); err != nil {
-					exitChan <- errors.Wrap(err, "failed shutdown")
+					exitChan <- fmt.Errorf("failed shutdown: %w", err)
 
 
 					break Loop
 					break Loop
 				}
 				}
 
 
 				if newConfig, err = reloadHandler(s); err != nil {
 				if newConfig, err = reloadHandler(s); err != nil {
-					exitChan <- errors.Wrap(err, "reload handler failure")
+					exitChan <- fmt.Errorf("reload handler failure: %w", err)
 
 
 					break Loop
 					break Loop
 				}
 				}
@@ -256,7 +256,7 @@ func HandleSignals(cConfig *csconfig.Config) error {
 			case os.Interrupt, syscall.SIGTERM:
 			case os.Interrupt, syscall.SIGTERM:
 				log.Warning("SIGTERM received, shutting down")
 				log.Warning("SIGTERM received, shutting down")
 				if err = shutdown(s, cConfig); err != nil {
 				if err = shutdown(s, cConfig); err != nil {
-					exitChan <- errors.Wrap(err, "failed shutdown")
+					exitChan <- fmt.Errorf("failed shutdown: %w", err)
 
 
 					break Loop
 					break Loop
 				}
 				}
@@ -284,17 +284,17 @@ func Serve(cConfig *csconfig.Config, apiReady chan bool, agentReady chan bool) e
 	if cConfig.API.Server != nil && cConfig.API.Server.DbConfig != nil {
 	if cConfig.API.Server != nil && cConfig.API.Server.DbConfig != nil {
 		dbClient, err := database.NewClient(cConfig.API.Server.DbConfig)
 		dbClient, err := database.NewClient(cConfig.API.Server.DbConfig)
 		if err != nil {
 		if err != nil {
-			return errors.Wrap(err, "failed to get database client")
+			return fmt.Errorf("failed to get database client: %w", err)
 		}
 		}
 
 
 		err = exprhelpers.Init(dbClient)
 		err = exprhelpers.Init(dbClient)
 		if err != nil {
 		if err != nil {
-			return errors.Wrap(err, "failed to init expr helpers")
+			return fmt.Errorf("failed to init expr helpers: %w", err)
 		}
 		}
 	} else {
 	} else {
 		err := exprhelpers.Init(nil)
 		err := exprhelpers.Init(nil)
 		if err != nil {
 		if err != nil {
-			return errors.Wrap(err, "failed to init expr helpers")
+			return fmt.Errorf("failed to init expr helpers: %w", err)
 		}
 		}
 
 
 		log.Warningln("Exprhelpers loaded without database client.")
 		log.Warningln("Exprhelpers loaded without database client.")
@@ -303,7 +303,7 @@ func Serve(cConfig *csconfig.Config, apiReady chan bool, agentReady chan bool) e
 	if cConfig.API.CTI != nil && *cConfig.API.CTI.Enabled {
 	if cConfig.API.CTI != nil && *cConfig.API.CTI.Enabled {
 		log.Infof("Crowdsec CTI helper enabled")
 		log.Infof("Crowdsec CTI helper enabled")
 		if err := exprhelpers.InitCrowdsecCTI(cConfig.API.CTI.Key, cConfig.API.CTI.CacheTimeout, cConfig.API.CTI.CacheSize, cConfig.API.CTI.LogLevel); err != nil {
 		if err := exprhelpers.InitCrowdsecCTI(cConfig.API.CTI.Key, cConfig.API.CTI.CacheTimeout, cConfig.API.CTI.CacheSize, cConfig.API.CTI.LogLevel); err != nil {
-			return errors.Wrap(err, "failed to init crowdsec cti")
+			return fmt.Errorf("failed to init crowdsec cti: %w", err)
 		}
 		}
 	}
 	}
 
 
@@ -319,7 +319,7 @@ func Serve(cConfig *csconfig.Config, apiReady chan bool, agentReady chan bool) e
 
 
 		apiServer, err := initAPIServer(cConfig)
 		apiServer, err := initAPIServer(cConfig)
 		if err != nil {
 		if err != nil {
-			return errors.Wrap(err, "api server init")
+			return fmt.Errorf("api server init: %w", err)
 		}
 		}
 
 
 		if !flags.TestMode {
 		if !flags.TestMode {
@@ -332,7 +332,7 @@ func Serve(cConfig *csconfig.Config, apiReady chan bool, agentReady chan bool) e
 	if !cConfig.DisableAgent {
 	if !cConfig.DisableAgent {
 		csParsers, err := initCrowdsec(cConfig)
 		csParsers, err := initCrowdsec(cConfig)
 		if err != nil {
 		if err != nil {
-			return errors.Wrap(err, "crowdsec init")
+			return fmt.Errorf("crowdsec init: %w", err)
 		}
 		}
 
 
 		// if it's just linting, we're done
 		// if it's just linting, we're done

+ 2 - 2
cmd/crowdsec/win_service.go

@@ -8,10 +8,10 @@
 package main
 package main
 
 
 import (
 import (
+	"fmt"
 	"syscall"
 	"syscall"
 	"time"
 	"time"
 
 
-	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 	"golang.org/x/sys/windows"
 	"golang.org/x/sys/windows"
 	"golang.org/x/sys/windows/svc"
 	"golang.org/x/sys/windows/svc"
@@ -106,7 +106,7 @@ func runService(name string) error {
 	winsvc := crowdsec_winservice{config: cConfig}
 	winsvc := crowdsec_winservice{config: cConfig}
 
 
 	if err := svc.Run(name, &winsvc); err != nil {
 	if err := svc.Run(name, &winsvc); err != nil {
-		return errors.Wrapf(err, "%s service failed", name)
+		return fmt.Errorf("%s service failed: %w", name, err)
 	}
 	}
 
 
 	log.Infof("%s service stopped", name)
 	log.Infof("%s service stopped", name)

+ 5 - 5
pkg/apiclient/alerts_service.go

@@ -5,9 +5,9 @@ import (
 	"fmt"
 	"fmt"
 	"net/http"
 	"net/http"
 
 
-	"github.com/crowdsecurity/crowdsec/pkg/models"
 	qs "github.com/google/go-querystring/query"
 	qs "github.com/google/go-querystring/query"
-	"github.com/pkg/errors"
+
+	"github.com/crowdsecurity/crowdsec/pkg/models"
 )
 )
 
 
 // type ApiAlerts service
 // type ApiAlerts service
@@ -72,7 +72,7 @@ func (s *AlertsService) List(ctx context.Context, opts AlertsListOpts) (*models.
 	u := fmt.Sprintf("%s/alerts", s.client.URLPrefix)
 	u := fmt.Sprintf("%s/alerts", s.client.URLPrefix)
 	params, err := qs.Values(opts)
 	params, err := qs.Values(opts)
 	if err != nil {
 	if err != nil {
-		return nil, nil, errors.Wrap(err, "building query")
+		return nil, nil, fmt.Errorf("building query: %w", err)
 	}
 	}
 	if len(params) > 0 {
 	if len(params) > 0 {
 		URI = fmt.Sprintf("%s?%s", u, params.Encode())
 		URI = fmt.Sprintf("%s?%s", u, params.Encode())
@@ -82,12 +82,12 @@ func (s *AlertsService) List(ctx context.Context, opts AlertsListOpts) (*models.
 
 
 	req, err := s.client.NewRequest(http.MethodGet, URI, nil)
 	req, err := s.client.NewRequest(http.MethodGet, URI, nil)
 	if err != nil {
 	if err != nil {
-		return nil, nil, errors.Wrap(err, "building request")
+		return nil, nil, fmt.Errorf("building request: %w", err)
 	}
 	}
 
 
 	resp, err := s.client.Do(ctx, req, &alerts)
 	resp, err := s.client.Do(ctx, req, &alerts)
 	if err != nil {
 	if err != nil {
-		return nil, resp, errors.Wrap(err, "performing request")
+		return nil, resp, fmt.Errorf("performing request: %w", err)
 	}
 	}
 	return &alerts, resp, nil
 	return &alerts, resp, nil
 }
 }

+ 4 - 3
pkg/apiclient/alerts_service_test.go

@@ -8,12 +8,13 @@ import (
 	"reflect"
 	"reflect"
 	"testing"
 	"testing"
 
 
-	"github.com/crowdsecurity/go-cs-lib/pkg/version"
-
-	"github.com/crowdsecurity/crowdsec/pkg/models"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
 	"github.com/stretchr/testify/require"
+
+	"github.com/crowdsecurity/go-cs-lib/pkg/version"
+
+	"github.com/crowdsecurity/crowdsec/pkg/models"
 )
 )
 
 
 func TestAlertsListAsMachine(t *testing.T) {
 func TestAlertsListAsMachine(t *testing.T) {

+ 12 - 14
pkg/apiclient/auth.go

@@ -3,23 +3,21 @@ package apiclient
 import (
 import (
 	"bytes"
 	"bytes"
 	"encoding/json"
 	"encoding/json"
-	"math/rand"
-	"sync"
-	"time"
-
-	//"errors"
 	"fmt"
 	"fmt"
 	"io"
 	"io"
+	"math/rand"
 	"net/http"
 	"net/http"
 	"net/http/httputil"
 	"net/http/httputil"
 	"net/url"
 	"net/url"
+	"sync"
+	"time"
 
 
-	"github.com/crowdsecurity/crowdsec/pkg/fflag"
-	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/go-openapi/strfmt"
 	"github.com/go-openapi/strfmt"
 	"github.com/pkg/errors"
 	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
-	//"google.golang.org/appengine/log"
+
+	"github.com/crowdsecurity/crowdsec/pkg/fflag"
+	"github.com/crowdsecurity/crowdsec/pkg/models"
 )
 )
 
 
 type APIKeyTransport struct {
 type APIKeyTransport struct {
@@ -169,11 +167,11 @@ func (t *JWTTransport) refreshJwtToken() error {
 	enc.SetEscapeHTML(false)
 	enc.SetEscapeHTML(false)
 	err = enc.Encode(auth)
 	err = enc.Encode(auth)
 	if err != nil {
 	if err != nil {
-		return errors.Wrap(err, "could not encode jwt auth body")
+		return fmt.Errorf("could not encode jwt auth body: %w", err)
 	}
 	}
 	req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s%s/watchers/login", t.URL, t.VersionPrefix), buf)
 	req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s%s/watchers/login", t.URL, t.VersionPrefix), buf)
 	if err != nil {
 	if err != nil {
-		return errors.Wrap(err, "could not create request")
+		return fmt.Errorf("could not create request: %w", err)
 	}
 	}
 	req.Header.Add("Content-Type", "application/json")
 	req.Header.Add("Content-Type", "application/json")
 	client := &http.Client{
 	client := &http.Client{
@@ -196,7 +194,7 @@ func (t *JWTTransport) refreshJwtToken() error {
 
 
 	resp, err := client.Do(req)
 	resp, err := client.Do(req)
 	if err != nil {
 	if err != nil {
-		return errors.Wrap(err, "could not get jwt token")
+		return fmt.Errorf("could not get jwt token: %w", err)
 	}
 	}
 	log.Debugf("auth-jwt : http %d", resp.StatusCode)
 	log.Debugf("auth-jwt : http %d", resp.StatusCode)
 
 
@@ -217,10 +215,10 @@ func (t *JWTTransport) refreshJwtToken() error {
 	}
 	}
 
 
 	if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
 	if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
-		return errors.Wrap(err, "unable to decode response")
+		return fmt.Errorf("unable to decode response: %w", err)
 	}
 	}
 	if err := t.Expiration.UnmarshalText([]byte(response.Expire)); err != nil {
 	if err := t.Expiration.UnmarshalText([]byte(response.Expire)); err != nil {
-		return errors.Wrap(err, "unable to parse jwt expiration")
+		return fmt.Errorf("unable to parse jwt expiration: %w", err)
 	}
 	}
 	t.Token = response.Token
 	t.Token = response.Token
 
 
@@ -263,7 +261,7 @@ func (t *JWTTransport) RoundTrip(req *http.Request) (*http.Response, error) {
 	if err != nil {
 	if err != nil {
 		/*we had an error (network error for example, or 401 because token is refused), reset the token ?*/
 		/*we had an error (network error for example, or 401 because token is refused), reset the token ?*/
 		t.Token = ""
 		t.Token = ""
-		return resp, errors.Wrapf(err, "performing jwt auth")
+		return resp, fmt.Errorf("performing jwt auth: %w", err)
 	}
 	}
 
 
 	log.Debugf("resp-jwt: %d", resp.StatusCode)
 	log.Debugf("resp-jwt: %d", resp.StatusCode)

+ 0 - 2
pkg/apiclient/auth_service.go

@@ -21,7 +21,6 @@ type enrollRequest struct {
 }
 }
 
 
 func (s *AuthService) UnregisterWatcher(ctx context.Context) (*Response, error) {
 func (s *AuthService) UnregisterWatcher(ctx context.Context) (*Response, error) {
-
 	u := fmt.Sprintf("%s/watchers", s.client.URLPrefix)
 	u := fmt.Sprintf("%s/watchers", s.client.URLPrefix)
 	req, err := s.client.NewRequest(http.MethodDelete, u, nil)
 	req, err := s.client.NewRequest(http.MethodDelete, u, nil)
 	if err != nil {
 	if err != nil {
@@ -36,7 +35,6 @@ func (s *AuthService) UnregisterWatcher(ctx context.Context) (*Response, error)
 }
 }
 
 
 func (s *AuthService) RegisterWatcher(ctx context.Context, registration models.WatcherRegistrationRequest) (*Response, error) {
 func (s *AuthService) RegisterWatcher(ctx context.Context, registration models.WatcherRegistrationRequest) (*Response, error) {
-
 	u := fmt.Sprintf("%s/watchers", s.client.URLPrefix)
 	u := fmt.Sprintf("%s/watchers", s.client.URLPrefix)
 
 
 	req, err := s.client.NewRequest(http.MethodPost, u, &registration)
 	req, err := s.client.NewRequest(http.MethodPost, u, &registration)

+ 3 - 2
pkg/apiclient/auth_service_test.go

@@ -10,11 +10,12 @@ import (
 	"net/url"
 	"net/url"
 	"testing"
 	"testing"
 
 
+	log "github.com/sirupsen/logrus"
+	"github.com/stretchr/testify/assert"
+
 	"github.com/crowdsecurity/go-cs-lib/pkg/version"
 	"github.com/crowdsecurity/go-cs-lib/pkg/version"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/crowdsecurity/crowdsec/pkg/models"
-	log "github.com/sirupsen/logrus"
-	"github.com/stretchr/testify/assert"
 )
 )
 
 
 type BasicMockPayload struct {
 type BasicMockPayload struct {

+ 3 - 4
pkg/apiclient/client.go

@@ -11,7 +11,6 @@ import (
 	"net/url"
 	"net/url"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/crowdsecurity/crowdsec/pkg/models"
-	"github.com/pkg/errors"
 )
 )
 
 
 var (
 var (
@@ -125,9 +124,9 @@ func RegisterClient(config *Config, client *http.Client) (*ApiClient, error) {
 	/*if we have http status, return it*/
 	/*if we have http status, return it*/
 	if err != nil {
 	if err != nil {
 		if resp != nil && resp.Response != nil {
 		if resp != nil && resp.Response != nil {
-			return nil, errors.Wrapf(err, "api register (%s) http %s : %s", c.BaseURL, resp.Response.Status, err)
+			return nil, fmt.Errorf("api register (%s) http %s: %w", c.BaseURL, resp.Response.Status, err)
 		}
 		}
-		return nil, errors.Wrapf(err, "api register (%s) : %s", c.BaseURL, err)
+		return nil, fmt.Errorf("api register (%s): %w", c.BaseURL, err)
 	}
 	}
 	return c, nil
 	return c, nil
 
 
@@ -166,7 +165,7 @@ func CheckResponse(r *http.Response) error {
 	if err == nil && data != nil {
 	if err == nil && data != nil {
 		err := json.Unmarshal(data, errorResponse)
 		err := json.Unmarshal(data, errorResponse)
 		if err != nil {
 		if err != nil {
-			return errors.Wrapf(err, "http code %d, invalid body", r.StatusCode)
+			return fmt.Errorf("http code %d, invalid body: %w", r.StatusCode, err)
 		}
 		}
 	} else {
 	} else {
 		errorResponse.Message = new(string)
 		errorResponse.Message = new(string)

+ 2 - 2
pkg/apiclient/client_http_test.go

@@ -8,9 +8,9 @@ import (
 	"testing"
 	"testing"
 	"time"
 	"time"
 
 
-	"github.com/crowdsecurity/go-cs-lib/pkg/version"
-
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/assert"
+
+	"github.com/crowdsecurity/go-cs-lib/pkg/version"
 )
 )
 
 
 func TestNewRequestInvalid(t *testing.T) {
 func TestNewRequestInvalid(t *testing.T) {

+ 1 - 2
pkg/apiclient/client_test.go

@@ -9,9 +9,8 @@ import (
 	"runtime"
 	"runtime"
 	"testing"
 	"testing"
 
 
-	"github.com/stretchr/testify/assert"
-
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
+	"github.com/stretchr/testify/assert"
 
 
 	"github.com/crowdsecurity/go-cs-lib/pkg/version"
 	"github.com/crowdsecurity/go-cs-lib/pkg/version"
 )
 )

+ 4 - 3
pkg/apiclient/decisions_service.go

@@ -6,14 +6,15 @@ import (
 	"fmt"
 	"fmt"
 	"net/http"
 	"net/http"
 
 
+	qs "github.com/google/go-querystring/query"
+	"github.com/pkg/errors"
+	log "github.com/sirupsen/logrus"
+
 	"github.com/crowdsecurity/go-cs-lib/pkg/ptr"
 	"github.com/crowdsecurity/go-cs-lib/pkg/ptr"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/crowdsecurity/crowdsec/pkg/modelscapi"
 	"github.com/crowdsecurity/crowdsec/pkg/modelscapi"
 	"github.com/crowdsecurity/crowdsec/pkg/types"
 	"github.com/crowdsecurity/crowdsec/pkg/types"
-	qs "github.com/google/go-querystring/query"
-	"github.com/pkg/errors"
-	log "github.com/sirupsen/logrus"
 )
 )
 
 
 type DecisionsService service
 type DecisionsService service

+ 4 - 3
pkg/apiclient/decisions_service_test.go

@@ -8,14 +8,15 @@ import (
 	"reflect"
 	"reflect"
 	"testing"
 	"testing"
 
 
+	log "github.com/sirupsen/logrus"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
 	"github.com/crowdsecurity/go-cs-lib/pkg/ptr"
 	"github.com/crowdsecurity/go-cs-lib/pkg/ptr"
 	"github.com/crowdsecurity/go-cs-lib/pkg/version"
 	"github.com/crowdsecurity/go-cs-lib/pkg/version"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/crowdsecurity/crowdsec/pkg/modelscapi"
 	"github.com/crowdsecurity/crowdsec/pkg/modelscapi"
-	log "github.com/sirupsen/logrus"
-	"github.com/stretchr/testify/assert"
-	"github.com/stretchr/testify/require"
 )
 )
 
 
 func TestDecisionsList(t *testing.T) {
 func TestDecisionsList(t *testing.T) {

+ 4 - 4
pkg/apiclient/decisions_sync_service.go

@@ -5,9 +5,9 @@ import (
 	"fmt"
 	"fmt"
 	"net/http"
 	"net/http"
 
 
-	"github.com/crowdsecurity/crowdsec/pkg/models"
-	"github.com/pkg/errors"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
+
+	"github.com/crowdsecurity/crowdsec/pkg/models"
 )
 )
 
 
 type DecisionDeleteService service
 type DecisionDeleteService service
@@ -18,12 +18,12 @@ func (d *DecisionDeleteService) Add(ctx context.Context, deletedDecisions *model
 	u := fmt.Sprintf("%s/decisions/delete", d.client.URLPrefix)
 	u := fmt.Sprintf("%s/decisions/delete", d.client.URLPrefix)
 	req, err := d.client.NewRequest(http.MethodPost, u, &deletedDecisions)
 	req, err := d.client.NewRequest(http.MethodPost, u, &deletedDecisions)
 	if err != nil {
 	if err != nil {
-		return nil, nil, errors.Wrap(err, "while building request")
+		return nil, nil, fmt.Errorf("while building request: %w", err)
 	}
 	}
 
 
 	resp, err := d.client.Do(ctx, req, &response)
 	resp, err := d.client.Do(ctx, req, &response)
 	if err != nil {
 	if err != nil {
-		return nil, resp, errors.Wrap(err, "while performing request")
+		return nil, resp, fmt.Errorf("while performing request: %w", err)
 	}
 	}
 	if resp.Response.StatusCode != http.StatusOK {
 	if resp.Response.StatusCode != http.StatusOK {
 		log.Warnf("Decisions delete response : http %s", resp.Response.Status)
 		log.Warnf("Decisions delete response : http %s", resp.Response.Status)

+ 2 - 3
pkg/apiclient/signal.go

@@ -8,7 +8,6 @@ import (
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/models"
 	"github.com/crowdsecurity/crowdsec/pkg/models"
-	"github.com/pkg/errors"
 )
 )
 
 
 type SignalService service
 type SignalService service
@@ -19,12 +18,12 @@ func (s *SignalService) Add(ctx context.Context, signals *models.AddSignalsReque
 	u := fmt.Sprintf("%s/signals", s.client.URLPrefix)
 	u := fmt.Sprintf("%s/signals", s.client.URLPrefix)
 	req, err := s.client.NewRequest(http.MethodPost, u, &signals)
 	req, err := s.client.NewRequest(http.MethodPost, u, &signals)
 	if err != nil {
 	if err != nil {
-		return nil, nil, errors.Wrap(err, "while building request")
+		return nil, nil, fmt.Errorf("while building request: %w", err)
 	}
 	}
 
 
 	resp, err := s.client.Do(ctx, req, &response)
 	resp, err := s.client.Do(ctx, req, &response)
 	if err != nil {
 	if err != nil {
-		return nil, resp, errors.Wrap(err, "while performing request")
+		return nil, resp, fmt.Errorf("while performing request: %w", err)
 	}
 	}
 	if resp.Response.StatusCode != http.StatusOK {
 	if resp.Response.StatusCode != http.StatusOK {
 		log.Warnf("Signal push response : http %s", resp.Response.Status)
 		log.Warnf("Signal push response : http %s", resp.Response.Status)

+ 1 - 1
test/bats/04_capi.bats

@@ -60,5 +60,5 @@ setup() {
     ONLINE_API_CREDENTIALS_YAML="$(config_get '.api.server.online_client.credentials_path')"
     ONLINE_API_CREDENTIALS_YAML="$(config_get '.api.server.online_client.credentials_path')"
     rm "${ONLINE_API_CREDENTIALS_YAML}"
     rm "${ONLINE_API_CREDENTIALS_YAML}"
     rune -1 cscli capi status
     rune -1 cscli capi status
-    assert_stderr --partial "Local API is disabled, please run this command on the local API machine: loading online client credentials: failed to read api server credentials configuration file '${ONLINE_API_CREDENTIALS_YAML}': open ${ONLINE_API_CREDENTIALS_YAML}: no such file or directory"
+    assert_stderr --partial "local API is disabled, please run this command on the local API machine: loading online client credentials: failed to read api server credentials configuration file '${ONLINE_API_CREDENTIALS_YAML}': open ${ONLINE_API_CREDENTIALS_YAML}: no such file or directory"
 }
 }

+ 9 - 9
test/bats/72_plugin_badconfig.bats

@@ -36,35 +36,35 @@ teardown() {
     config_set '.plugin_config.user="" | .plugin_config.group="nogroup"'
     config_set '.plugin_config.user="" | .plugin_config.group="nogroup"'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     rune -1 timeout 2s "${CROWDSEC}"
     rune -1 timeout 2s "${CROWDSEC}"
-    assert_stderr --partial "api server init: unable to run local API: while loading plugin: while getting process attributes: both plugin user and group must be set"
+    assert_stderr --partial "api server init: unable to run plugin broker: while loading plugin: while getting process attributes: both plugin user and group must be set"
 }
 }
 
 
 @test "misconfigured plugin, only group is empty" {
 @test "misconfigured plugin, only group is empty" {
     config_set '(.plugin_config.user="nobody") | (.plugin_config.group="")'
     config_set '(.plugin_config.user="nobody") | (.plugin_config.group="")'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     rune -1 timeout 2s "${CROWDSEC}"
     rune -1 timeout 2s "${CROWDSEC}"
-    assert_stderr --partial "api server init: unable to run local API: while loading plugin: while getting process attributes: both plugin user and group must be set"
+    assert_stderr --partial "api server init: unable to run plugin broker: while loading plugin: while getting process attributes: both plugin user and group must be set"
 }
 }
 
 
 @test "misconfigured plugin, user does not exist" {
 @test "misconfigured plugin, user does not exist" {
     config_set '(.plugin_config.user="userdoesnotexist") | (.plugin_config.group="groupdoesnotexist")'
     config_set '(.plugin_config.user="userdoesnotexist") | (.plugin_config.group="groupdoesnotexist")'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     rune -1 timeout 2s "${CROWDSEC}"
     rune -1 timeout 2s "${CROWDSEC}"
-    assert_stderr --partial "api server init: unable to run local API: while loading plugin: while getting process attributes: user: unknown user userdoesnotexist"
+    assert_stderr --partial "api server init: unable to run plugin broker: while loading plugin: while getting process attributes: user: unknown user userdoesnotexist"
 }
 }
 
 
 @test "misconfigured plugin, group does not exist" {
 @test "misconfigured plugin, group does not exist" {
     config_set '(.plugin_config.user=strenv(USER)) | (.plugin_config.group="groupdoesnotexist")'
     config_set '(.plugin_config.user=strenv(USER)) | (.plugin_config.group="groupdoesnotexist")'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     rune -1 timeout 2s "${CROWDSEC}"
     rune -1 timeout 2s "${CROWDSEC}"
-    assert_stderr --partial "api server init: unable to run local API: while loading plugin: while getting process attributes: group: unknown group groupdoesnotexist"
+    assert_stderr --partial "api server init: unable to run plugin broker: while loading plugin: while getting process attributes: group: unknown group groupdoesnotexist"
 }
 }
 
 
 @test "bad plugin name" {
 @test "bad plugin name" {
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     cp "${PLUGIN_DIR}"/notification-http "${PLUGIN_DIR}"/badname
     cp "${PLUGIN_DIR}"/notification-http "${PLUGIN_DIR}"/badname
     rune -1 timeout 2s "${CROWDSEC}"
     rune -1 timeout 2s "${CROWDSEC}"
-    assert_stderr --partial "api server init: unable to run local API: while loading plugin: plugin name ${PLUGIN_DIR}/badname is invalid. Name should be like {type-name}"
+    assert_stderr --partial "api server init: unable to run plugin broker: while loading plugin: plugin name ${PLUGIN_DIR}/badname is invalid. Name should be like {type-name}"
 }
 }
 
 
 @test "duplicate notification config" {
 @test "duplicate notification config" {
@@ -85,14 +85,14 @@ teardown() {
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     chmod g+w "${PLUGIN_DIR}"/notification-http
     chmod g+w "${PLUGIN_DIR}"/notification-http
     rune -1 timeout 2s "${CROWDSEC}"
     rune -1 timeout 2s "${CROWDSEC}"
-    assert_stderr --partial "api server init: unable to run local API: while loading plugin: plugin at ${PLUGIN_DIR}/notification-http is group writable, group writable plugins are invalid"
+    assert_stderr --partial "api server init: unable to run plugin broker: while loading plugin: plugin at ${PLUGIN_DIR}/notification-http is group writable, group writable plugins are invalid"
 }
 }
 
 
 @test "bad plugin permission (world writable)" {
 @test "bad plugin permission (world writable)" {
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     chmod o+w "${PLUGIN_DIR}"/notification-http
     chmod o+w "${PLUGIN_DIR}"/notification-http
     rune -1 timeout 2s "${CROWDSEC}"
     rune -1 timeout 2s "${CROWDSEC}"
-    assert_stderr --partial "api server init: unable to run local API: while loading plugin: plugin at ${PLUGIN_DIR}/notification-http is world writable, world writable plugins are invalid"
+    assert_stderr --partial "api server init: unable to run plugin broker: while loading plugin: plugin at ${PLUGIN_DIR}/notification-http is world writable, world writable plugins are invalid"
 }
 }
 
 
 @test "config.yaml: missing .plugin_config section" {
 @test "config.yaml: missing .plugin_config section" {
@@ -116,9 +116,9 @@ teardown() {
     assert_stderr --partial "api server init: plugins are enabled, but config_paths.plugin_dir is not defined"
     assert_stderr --partial "api server init: plugins are enabled, but config_paths.plugin_dir is not defined"
 }
 }
 
 
-@test "unable to run local API: while reading plugin config" {
+@test "unable to run plugin broker: while reading plugin config" {
     config_set '.config_paths.notification_dir="/this/path/does/not/exist"'
     config_set '.config_paths.notification_dir="/this/path/does/not/exist"'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
     rune -1 timeout 2s "${CROWDSEC}"
     rune -1 timeout 2s "${CROWDSEC}"
-    assert_stderr --partial "api server init: unable to run local API: while loading plugin config: open /this/path/does/not/exist: no such file or directory"
+    assert_stderr --partial "api server init: unable to run plugin broker: while loading plugin config: open /this/path/does/not/exist: no such file or directory"
 }
 }