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

This commit is contained in:
mmetc 2023-06-22 15:01:34 +02:00 committed by GitHub
parent 8bfeb7d90d
commit fddf597040
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
29 changed files with 162 additions and 177 deletions

View file

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

View file

@ -6,6 +6,11 @@ import (
"net/url"
"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/crowdsec/pkg/apiclient"
@ -14,11 +19,6 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/fflag"
"github.com/crowdsecurity/crowdsec/pkg/models"
"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/"
@ -31,8 +31,11 @@ func NewCapiCmd() *cobra.Command {
Args: cobra.MinimumNArgs(1),
DisableAutoGenTag: true,
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 {
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) {
var err error
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 {
log.Fatalf("Please provide credentials for the Central API (CAPI) in '%s'", csConfig.API.Server.OnlineClient.CredentialsFilePath)

View file

@ -5,7 +5,6 @@ import (
"os"
"path/filepath"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"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*/
parentDir := filepath.Dir(dirPath)
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 {
return errors.Wrapf(err, "while creating %s", dirPath)
return fmt.Errorf("while creating %s: %w", dirPath, err)
}
if csConfig.ConfigPaths.SimulationFilePath != "" {
backupSimulation := filepath.Join(dirPath, "simulation.yaml")
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)
@ -56,13 +55,13 @@ func backupConfigToDirectory(dirPath string) error {
if csConfig.Crowdsec != nil && csConfig.Crowdsec.AcquisitionFilePath != "" {
backupAcquisition := filepath.Join(dirPath, "acquis.yaml")
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")
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 {
@ -74,11 +73,11 @@ func backupConfigToDirectory(dirPath string) error {
targetFname, err := filepath.Abs(filepath.Join(acquisBackupDir, filepath.Base(acquisFile)))
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 {
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)
@ -88,7 +87,7 @@ func backupConfigToDirectory(dirPath string) error {
if ConfigFilePath != "" {
backupMain := fmt.Sprintf("%s/config.yaml", dirPath)
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)
@ -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 != "" {
backupCAPICreds := fmt.Sprintf("%s/online_api_credentials.yaml", dirPath)
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)
@ -106,7 +105,7 @@ func backupConfigToDirectory(dirPath string) error {
if csConfig.API != nil && csConfig.API.Client != nil && csConfig.API.Client.CredentialsFilePath != "" {
backupLAPICreds := fmt.Sprintf("%s/local_api_credentials.yaml", dirPath)
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)
@ -115,20 +114,19 @@ func backupConfigToDirectory(dirPath string) error {
if csConfig.API != nil && csConfig.API.Server != nil && csConfig.API.Server.ProfilesPath != "" {
backupProfiles := fmt.Sprintf("%s/profiles.yaml", dirPath)
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)
}
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
}
func runConfigBackup(cmd *cobra.Command, args []string) error {
if err := csConfig.LoadHub(); err != nil {
return err
@ -146,7 +144,6 @@ func runConfigBackup(cmd *cobra.Command, args []string) error {
return nil
}
func NewConfigBackupCmd() *cobra.Command {
cmdConfigBackup := &cobra.Command{
Use: `backup "directory"`,

View file

@ -7,7 +7,6 @@ import (
"os"
"path/filepath"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
@ -133,7 +132,7 @@ func restoreConfigFromDirectory(dirPath string, oldBackup bool) error {
for _, acquisFile := range acquisFiles {
targetFname, err := filepath.Abs(csConfig.Crowdsec.AcquisitionDirPath + "/" + filepath.Base(acquisFile))
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)
@ -156,7 +155,7 @@ func restoreConfigFromDirectory(dirPath string, oldBackup bool) error {
targetFname, err := filepath.Abs(filepath.Join(acquisBackupDir, filepath.Base(acquisFile)))
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 {
@ -174,7 +173,6 @@ func restoreConfigFromDirectory(dirPath string, oldBackup bool) error {
return nil
}
func runConfigRestore(cmd *cobra.Command, args []string) error {
flags := cmd.Flags()
@ -199,7 +197,6 @@ func runConfigRestore(cmd *cobra.Command, args []string) error {
return nil
}
func NewConfigRestoreCmd() *cobra.Command {
cmdConfigRestore := &cobra.Command{
Use: `restore "directory"`,

View file

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

View file

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

View file

@ -15,7 +15,6 @@ import (
"github.com/fatih/color"
"github.com/go-openapi/strfmt"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/tomb.v2"
@ -28,14 +27,12 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/csprofiles"
)
type NotificationsCfg struct {
Config csplugin.PluginConfig `json:"plugin_config"`
Profiles []*csconfig.ProfileCfg `json:"associated_profiles"`
ids []uint
}
func NewNotificationsCmd() *cobra.Command {
var cmdNotifications = &cobra.Command{
Use: "notifications [action]",
@ -57,7 +54,6 @@ func NewNotificationsCmd() *cobra.Command {
},
}
cmdNotifications.AddCommand(NewNotificationsListCmd())
cmdNotifications.AddCommand(NewNotificationsInspectCmd())
cmdNotifications.AddCommand(NewNotificationsReinjectCmd())
@ -65,18 +61,17 @@ func NewNotificationsCmd() *cobra.Command {
return cmdNotifications
}
func getNotificationsConfiguration() (map[string]NotificationsCfg, error) {
pcfgs := map[string]csplugin.PluginConfig{}
wf := func(path string, info fs.FileInfo, err error) error {
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
if (strings.HasSuffix(name, "yaml") || strings.HasSuffix(name, "yml")) && !(info.IsDir()) {
ts, err := csplugin.ParsePluginConfigFile(name)
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 {
pcfgs[t.Name] = t
@ -86,14 +81,14 @@ func getNotificationsConfiguration() (map[string]NotificationsCfg, error) {
}
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
ncfgs := map[string]NotificationsCfg{}
profiles, err := csprofiles.NewProfile(csConfig.API.Server.Profiles)
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 {
loop:
@ -129,7 +124,6 @@ func getNotificationsConfiguration() (map[string]NotificationsCfg, error) {
return ncfgs, nil
}
func NewNotificationsListCmd() *cobra.Command {
var cmdNotificationsList = &cobra.Command{
Use: "list",
@ -141,7 +135,7 @@ func NewNotificationsListCmd() *cobra.Command {
RunE: func(cmd *cobra.Command, arg []string) error {
ncfgs, err := getNotificationsConfiguration()
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" {
@ -149,14 +143,14 @@ func NewNotificationsListCmd() *cobra.Command {
} else if csConfig.Cscli.Output == "json" {
x, err := json.MarshalIndent(ncfgs, "", " ")
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))
} else if csConfig.Cscli.Output == "raw" {
csvwriter := csv.NewWriter(os.Stdout)
err := csvwriter.Write([]string{"Name", "Type", "Profile name"})
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 {
profilesList := []string{}
@ -165,7 +159,7 @@ func NewNotificationsListCmd() *cobra.Command {
}
err := csvwriter.Write([]string{b.Config.Name, b.Config.Type, strings.Join(profilesList, ", ")})
if err != nil {
return errors.Wrap(err, "failed to write raw content")
return fmt.Errorf("failed to write raw content: %w", err)
}
}
csvwriter.Flush()
@ -177,7 +171,6 @@ func NewNotificationsListCmd() *cobra.Command {
return cmdNotificationsList
}
func NewNotificationsInspectCmd() *cobra.Command {
var cmdNotificationsInspect = &cobra.Command{
Use: "inspect",
@ -195,14 +188,14 @@ func NewNotificationsInspectCmd() *cobra.Command {
pluginName := arg[0]
if pluginName == "" {
errors.New("Please provide a plugin name to inspect")
return fmt.Errorf("please provide a plugin name to inspect")
}
ncfgs, err := getNotificationsConfiguration()
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 {
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" {
@ -216,7 +209,7 @@ func NewNotificationsInspectCmd() *cobra.Command {
} else if csConfig.Cscli.Output == "json" {
x, err := json.MarshalIndent(cfg, "", " ")
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))
}
@ -227,7 +220,6 @@ func NewNotificationsInspectCmd() *cobra.Command {
return cmdNotificationsInspect
}
func NewNotificationsReinjectCmd() *cobra.Command {
var remediation bool
var alertOverride string
@ -250,26 +242,26 @@ cscli notifications reinject <alert_id> -a '{"remediation": true,"scenario":"not
)
if len(args) != 1 {
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
id, err := strconv.Atoi(args[0])
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 {
return errors.Wrapf(err, "loading api client")
return fmt.Errorf("loading api client: %w", err)
}
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 {
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)
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{
MachineID: csConfig.API.Client.Credentials.Login,
@ -279,16 +271,16 @@ cscli notifications reinject <alert_id> -a '{"remediation": true,"scenario":"not
VersionPrefix: "v1",
})
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)
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 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 {
@ -298,7 +290,7 @@ cscli notifications reinject <alert_id> -a '{"remediation": true,"scenario":"not
// second we start plugins
err = pluginBroker.Init(csConfig.PluginConfig, csConfig.API.Server.Profiles, csConfig.ConfigPaths)
if err != nil {
return errors.Wrapf(err, "Can't initialize plugins")
return fmt.Errorf("can't initialize plugins: %w", err)
}
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)
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 {
_, matched, err := profile.EvaluateProfile(alert)
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 {
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
pluginTomb.Kill(errors.New("terminating"))
pluginTomb.Kill(fmt.Errorf("terminating"))
pluginTomb.Wait()
return nil
},

View file

@ -4,7 +4,6 @@ import (
"fmt"
"github.com/fatih/color"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -33,7 +32,7 @@ cscli scenarios remove crowdsecurity/ssh-bf
}
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 {

View file

@ -1,6 +1,7 @@
package main
import (
"fmt"
"runtime"
"time"
@ -20,7 +21,7 @@ func initAPIServer(cConfig *csconfig.Config) (*apiserver.APIServer, error) {
apiServer, err := apiserver.NewServer(cConfig.API.Server)
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) {
@ -29,23 +30,27 @@ func initAPIServer(cConfig *csconfig.Config) (*apiserver.APIServer, error) {
if cConfig.PluginConfig == nil && runtime.GOOS != "windows" {
return nil, errors.New("plugins are enabled, but the plugin_config section is missing in the configuration")
}
if cConfig.ConfigPaths.NotificationDir == "" {
return nil, errors.New("plugins are enabled, but config_paths.notification_dir is not defined")
}
if cConfig.ConfigPaths.PluginDir == "" {
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)
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")
apiServer.AttachPluginBroker(&pluginBroker)
}
err = apiServer.InitController()
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

View file

@ -3,10 +3,12 @@ package main
import (
"fmt"
"os"
"path/filepath"
"sync"
"time"
"path/filepath"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"github.com/crowdsecurity/go-cs-lib/pkg/trace"
@ -16,9 +18,6 @@ import (
leaky "github.com/crowdsecurity/crowdsec/pkg/leakybucket"
"github.com/crowdsecurity/crowdsec/pkg/parser"
"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) {
@ -118,7 +117,7 @@ func runCrowdsec(cConfig *csconfig.Config, parsers *parser.Parsers) error {
aggregated = true
}
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)
}
}

View file

@ -51,14 +51,14 @@ var (
)
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
SingleFileType string
@ -110,7 +110,7 @@ func LoadAcquisition(cConfig *csconfig.Config) error {
dataSources, err = acquisition.LoadAcquisitionFromDSN(flags.OneShotDSN, flags.Labels, flags.Transform)
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 {
dataSources, err = acquisition.LoadAcquisitionFromFile(cConfig.Crowdsec)

View file

@ -7,6 +7,10 @@ import (
"sync"
"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/crowdsec/pkg/apiclient"
@ -16,9 +20,6 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/parser"
"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) {
@ -50,11 +51,11 @@ func PushAlerts(alerts []types.RuntimeAlert, client *apiclient.ApiClient) error
alertsToPush, err := dedupAlerts(alerts)
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)
if err != nil {
return errors.Wrap(err, "failed sending alert to LAPI")
return fmt.Errorf("failed sending alert to LAPI: %w", err)
}
return nil
}
@ -104,11 +105,11 @@ func runOutput(input chan types.Event, overflow chan types.Event, buckets *leaky
Scenarios: scenarios,
})
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 {
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

View file

@ -3,7 +3,6 @@ package main
import (
"fmt"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"golang.org/x/sys/windows/svc"
@ -22,7 +21,7 @@ func StartRunSvc() error {
isRunninginService, err := svc.IsWindowsService()
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 {
return runService(svcName)
@ -31,22 +30,22 @@ func StartRunSvc() error {
if flags.WinSvc == "Install" {
err = installService(svcName, svcDescription)
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" {
err = removeService(svcName)
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" {
err = startService(svcName)
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" {
err = controlService(svcName, svc.Stop, svc.Stopped)
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 == "" {
return WindowsRun()
@ -66,7 +65,7 @@ func WindowsRun() error {
if err != nil {
return err
}
// Configure logging
log.Infof("Crowdsec %s", version.String())
apiReady := make(chan bool, 1)

View file

@ -1,12 +1,12 @@
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"gopkg.in/tomb.v2"
@ -68,7 +68,7 @@ func reloadHandler(sig os.Signal) (*csconfig.Config, error) {
}
apiServer, err := initAPIServer(cConfig)
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)
@ -78,7 +78,7 @@ func reloadHandler(sig os.Signal) (*csconfig.Config, error) {
if !cConfig.DisableAgent {
csParsers, err := initCrowdsec(cConfig)
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
@ -180,13 +180,13 @@ func shutdownCrowdsec() error {
func shutdown(sig os.Signal, cConfig *csconfig.Config) error {
if !cConfig.DisableAgent {
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 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")
if err = shutdown(s, cConfig); err != nil {
exitChan <- errors.Wrap(err, "failed shutdown")
exitChan <- fmt.Errorf("failed shutdown: %w", err)
break Loop
}
if newConfig, err = reloadHandler(s); err != nil {
exitChan <- errors.Wrap(err, "reload handler failure")
exitChan <- fmt.Errorf("reload handler failure: %w", err)
break Loop
}
@ -256,7 +256,7 @@ func HandleSignals(cConfig *csconfig.Config) error {
case os.Interrupt, syscall.SIGTERM:
log.Warning("SIGTERM received, shutting down")
if err = shutdown(s, cConfig); err != nil {
exitChan <- errors.Wrap(err, "failed shutdown")
exitChan <- fmt.Errorf("failed shutdown: %w", err)
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 {
dbClient, err := database.NewClient(cConfig.API.Server.DbConfig)
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)
if err != nil {
return errors.Wrap(err, "failed to init expr helpers")
return fmt.Errorf("failed to init expr helpers: %w", err)
}
} else {
err := exprhelpers.Init(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.")
@ -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 {
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 {
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)
if err != nil {
return errors.Wrap(err, "api server init")
return fmt.Errorf("api server init: %w", err)
}
if !flags.TestMode {
@ -332,7 +332,7 @@ func Serve(cConfig *csconfig.Config, apiReady chan bool, agentReady chan bool) e
if !cConfig.DisableAgent {
csParsers, err := initCrowdsec(cConfig)
if err != nil {
return errors.Wrap(err, "crowdsec init")
return fmt.Errorf("crowdsec init: %w", err)
}
// if it's just linting, we're done

View file

@ -8,10 +8,10 @@
package main
import (
"fmt"
"syscall"
"time"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/svc"
@ -106,7 +106,7 @@ func runService(name string) error {
winsvc := crowdsec_winservice{config: cConfig}
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)

View file

@ -5,9 +5,9 @@ import (
"fmt"
"net/http"
"github.com/crowdsecurity/crowdsec/pkg/models"
qs "github.com/google/go-querystring/query"
"github.com/pkg/errors"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
// 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)
params, err := qs.Values(opts)
if err != nil {
return nil, nil, errors.Wrap(err, "building query")
return nil, nil, fmt.Errorf("building query: %w", err)
}
if len(params) > 0 {
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)
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)
if err != nil {
return nil, resp, errors.Wrap(err, "performing request")
return nil, resp, fmt.Errorf("performing request: %w", err)
}
return &alerts, resp, nil
}

View file

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

View file

@ -3,23 +3,21 @@ package apiclient
import (
"bytes"
"encoding/json"
"math/rand"
"sync"
"time"
//"errors"
"fmt"
"io"
"math/rand"
"net/http"
"net/http/httputil"
"net/url"
"sync"
"time"
"github.com/crowdsecurity/crowdsec/pkg/fflag"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/go-openapi/strfmt"
"github.com/pkg/errors"
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 {
@ -169,11 +167,11 @@ func (t *JWTTransport) refreshJwtToken() error {
enc.SetEscapeHTML(false)
err = enc.Encode(auth)
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)
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")
client := &http.Client{
@ -196,7 +194,7 @@ func (t *JWTTransport) refreshJwtToken() error {
resp, err := client.Do(req)
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)
@ -217,10 +215,10 @@ func (t *JWTTransport) refreshJwtToken() error {
}
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 {
return errors.Wrap(err, "unable to parse jwt expiration")
return fmt.Errorf("unable to parse jwt expiration: %w", err)
}
t.Token = response.Token
@ -263,7 +261,7 @@ func (t *JWTTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if err != nil {
/*we had an error (network error for example, or 401 because token is refused), reset the 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)

View file

@ -21,7 +21,6 @@ type enrollRequest struct {
}
func (s *AuthService) UnregisterWatcher(ctx context.Context) (*Response, error) {
u := fmt.Sprintf("%s/watchers", s.client.URLPrefix)
req, err := s.client.NewRequest(http.MethodDelete, u, 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) {
u := fmt.Sprintf("%s/watchers", s.client.URLPrefix)
req, err := s.client.NewRequest(http.MethodPost, u, &registration)

View file

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

View file

@ -11,7 +11,6 @@ import (
"net/url"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/pkg/errors"
)
var (
@ -125,9 +124,9 @@ func RegisterClient(config *Config, client *http.Client) (*ApiClient, error) {
/*if we have http status, return it*/
if err != 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
@ -166,7 +165,7 @@ func CheckResponse(r *http.Response) error {
if err == nil && data != nil {
err := json.Unmarshal(data, errorResponse)
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 {
errorResponse.Message = new(string)

View file

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

View file

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

View file

@ -6,14 +6,15 @@ import (
"fmt"
"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/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/modelscapi"
"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

View file

@ -8,14 +8,15 @@ import (
"reflect"
"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/version"
"github.com/crowdsecurity/crowdsec/pkg/models"
"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) {

View file

@ -5,9 +5,9 @@ import (
"fmt"
"net/http"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
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)
req, err := d.client.NewRequest(http.MethodPost, u, &deletedDecisions)
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)
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 {
log.Warnf("Decisions delete response : http %s", resp.Response.Status)

View file

@ -8,7 +8,6 @@ import (
log "github.com/sirupsen/logrus"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/pkg/errors"
)
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)
req, err := s.client.NewRequest(http.MethodPost, u, &signals)
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)
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 {
log.Warnf("Signal push response : http %s", resp.Response.Status)

View file

@ -60,5 +60,5 @@ setup() {
ONLINE_API_CREDENTIALS_YAML="$(config_get '.api.server.online_client.credentials_path')"
rm "${ONLINE_API_CREDENTIALS_YAML}"
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"
}

View file

@ -36,35 +36,35 @@ teardown() {
config_set '.plugin_config.user="" | .plugin_config.group="nogroup"'
config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
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" {
config_set '(.plugin_config.user="nobody") | (.plugin_config.group="")'
config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
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" {
config_set '(.plugin_config.user="userdoesnotexist") | (.plugin_config.group="groupdoesnotexist")'
config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
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" {
config_set '(.plugin_config.user=strenv(USER)) | (.plugin_config.group="groupdoesnotexist")'
config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
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" {
config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
cp "${PLUGIN_DIR}"/notification-http "${PLUGIN_DIR}"/badname
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" {
@ -85,14 +85,14 @@ teardown() {
config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
chmod g+w "${PLUGIN_DIR}"/notification-http
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)" {
config_set "${PROFILES_PATH}" '.notifications=["http_default"]'
chmod o+w "${PLUGIN_DIR}"/notification-http
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" {
@ -116,9 +116,9 @@ teardown() {
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 "${PROFILES_PATH}" '.notifications=["http_default"]'
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"
}