diff --git a/cmd/app/generate/generate.go b/cmd/app/generate/generate.go index fa51ffd85..e347089da 100644 --- a/cmd/app/generate/generate.go +++ b/cmd/app/generate/generate.go @@ -37,12 +37,12 @@ func NewGenerateCommand(cfg *config.Config) *Generate { func (g *Generate) CreateCobraCmd() *cobra.Command { return &cobra.Command{ - Use: "generate", - Short: "Generate horusec configuration", - Long: "Generate the Horusec configuration", - Example: "horusec generate", - PreRunE: g.configs.PreRun, - RunE: g.runE, + Use: "generate", + Short: "Generate horusec configuration", + Long: "Generate the Horusec configuration", + Example: "horusec generate", + PersistentPreRunE: g.configs.PersistentPreRun, + RunE: g.runE, } } diff --git a/cmd/app/generate/generate_test.go b/cmd/app/generate/generate_test.go index 036c300bd..c4faa3f0f 100644 --- a/cmd/app/generate/generate_test.go +++ b/cmd/app/generate/generate_test.go @@ -46,7 +46,7 @@ func TestGenerate_CreateCobraCmd(t *testing.T) { logrus.SetOutput(stdoutMock) cobraCmd := cmd.CreateCobraCmd() // Remove the pre run hook to override the output - cobraCmd.PreRunE = nil + cobraCmd.PersistentPreRunE = nil cobraCmd.SetOut(stdoutMock) assert.NoError(t, cobraCmd.Execute()) @@ -83,7 +83,7 @@ func TestGenerate_CreateCobraCmd(t *testing.T) { logrus.SetOutput(stdoutMock) cobraCmd := cmd.CreateCobraCmd() // Remove the pre run hook to override the output - cobraCmd.PreRunE = nil + cobraCmd.PersistentPreRunE = nil cobraCmd.SetOut(stdoutMock) assert.NoError(t, cobraCmd.Execute()) diff --git a/cmd/app/start/start.go b/cmd/app/start/start.go index bbb49dbf6..85db12182 100644 --- a/cmd/app/start/start.go +++ b/cmd/app/start/start.go @@ -77,218 +77,193 @@ func NewStartCommand(configs *config.Config) *Start { } } -// CreateStartCommand load the config values from config file -// and environment variable and create the cobra command to parse -// command line flags. +// CreateStartCommand create the cobra command from start command. +// +// Note that here we only declare the flags and their default values +// the function on PersistentPreRunE field is that make the parsing of +// flags. // // nolint:funlen,lll func (s *Start) CreateStartCommand() *cobra.Command { - s.configs.MergeFromConfigFile().MergeFromEnvironmentVariables() - startCmd := &cobra.Command{ - Use: "start", - Short: "Start horusec-cli", - Long: "Start the Horusec' analysis in the current path", - Example: "horusec start", - PreRunE: s.configs.PreRun, - RunE: s.runE, + Use: "start", + Short: "Start horusec-cli", + Long: "Start the Horusec' analysis in the current path", + Example: "horusec start", + PersistentPreRunE: s.configs.PersistentPreRun, + RunE: s.runE, } startCmd.PersistentFlags(). - Int64VarP( - &s.configs.MonitorRetryInSeconds, + Int64P( "monitor-retry-count", "m", s.configs.MonitorRetryInSeconds, "The number of retries for the monitor.", ) startCmd.PersistentFlags(). - StringVarP( - &s.configs.PrintOutputType, + StringP( "output-format", "o", s.configs.PrintOutputType, "The format for the output to be shown. Options are: text (stdout), json, sonarqube", ) startCmd.PersistentFlags(). - StringSliceVarP( - &s.configs.SeveritiesToIgnore, + StringSliceP( "ignore-severity", "s", s.configs.SeveritiesToIgnore, "The level of vulnerabilities to ignore in the output. Example: -s=\"LOW, MEDIUM, HIGH\"", ) startCmd.PersistentFlags(). - StringVarP( - &s.configs.JSONOutputFilePath, + StringP( "json-output-file", "O", s.configs.JSONOutputFilePath, "If your pass output-format you can configure the output JSON location. Example: -O=\"/tmp/output.json\"", ) startCmd.PersistentFlags(). - StringSliceVarP( - &s.configs.FilesOrPathsToIgnore, + StringSliceP( "ignore", "i", s.configs.FilesOrPathsToIgnore, "Paths to ignore in the analysis. Example: -i=\"/home/user/project/assets, /home/user/project/deployments\"", ) startCmd.PersistentFlags(). - StringVarP( - &s.configs.HorusecAPIUri, + StringP( "horusec-url", "u", s.configs.HorusecAPIUri, "The Horusec API address to access the analysis engine", ) startCmd.PersistentFlags(). - Int64VarP( - &s.configs.TimeoutInSecondsRequest, + Int64P( "request-timeout", "r", s.configs.TimeoutInSecondsRequest, "The timeout threshold for the request to the Horusec API", ) startCmd.PersistentFlags(). - Int64VarP( - &s.configs.TimeoutInSecondsAnalysis, + Int64P( "analysis-timeout", "t", s.configs.TimeoutInSecondsAnalysis, "The timeout threshold for the Horusec CLI wait for the analysis to complete.", ) startCmd.PersistentFlags(). - StringVarP( - &s.configs.RepositoryAuthorization, + StringP( "authorization", "a", s.configs.RepositoryAuthorization, "The authorization token for the Horusec API", ) startCmd.PersistentFlags(). - StringToStringVar( - &s.configs.Headers, + StringToString( "headers", s.configs.Headers, "The headers dynamic to send on request in Horusec API. Example --headers=\"{\"X-Auth-Service\": \"my-value\"}\"", ) startCmd.PersistentFlags(). - BoolVarP( - &s.configs.ReturnErrorIfFoundVulnerability, + BoolP( "return-error", "e", s.configs.ReturnErrorIfFoundVulnerability, "The return-error is the option to check if you can return \"exit(1)\" if found vulnerabilities. Example -e=\"true\"", ) startCmd.PersistentFlags(). - StringVarP( - &s.configs.ProjectPath, + StringP( "project-path", "p", s.configs.ProjectPath, "Path to run an analysis in your project", ) startCmd.PersistentFlags(). - BoolVar( - &s.configs.EnableGitHistoryAnalysis, + Bool( "enable-git-history", s.configs.EnableGitHistoryAnalysis, "When this value is \"true\" we will run tool gitleaks and search vulnerability in all git history of the project. Example --enable-git-history=\"true\"", ) startCmd.PersistentFlags(). - BoolVarP( - &s.configs.CertInsecureSkipVerify, + BoolP( "insecure-skip-verify", "S", s.configs.CertInsecureSkipVerify, "Insecure skip verify cert authority. PLEASE, try not to use it. Example -S=\"true\"", ) startCmd.PersistentFlags(). - StringVarP( - &s.configs.CertPath, + StringP( "certificate-path", "C", s.configs.CertPath, "Path to certificate of authority. Example -C=\"/example/ca.crt\"", ) startCmd.PersistentFlags(). - BoolVarP( - &s.configs.EnableCommitAuthor, + BoolP( "enable-commit-author", "G", s.configs.EnableCommitAuthor, "Used to enable or disable search with vulnerability author. Example -G=\"true\"", ) startCmd.PersistentFlags(). - StringVarP( - &s.configs.RepositoryName, + StringP( "repository-name", "n", s.configs.RepositoryName, "Used to send repository name to horus server. Example -n=\"horus\"", ) startCmd.PersistentFlags(). - StringSliceVarP( - &s.configs.FalsePositiveHashes, + StringSliceP( "false-positive", "F", s.configs.FalsePositiveHashes, "Used to ignore a vulnerability by hash and setting it to be of the false positive type. Example -F=\"hash1, hash2\"", ) startCmd.PersistentFlags(). - StringSliceVarP( - &s.configs.RiskAcceptHashes, + StringSliceP( "risk-accept", "R", s.configs.RiskAcceptHashes, "Used to ignore a vulnerability by hash and setting it to be of the risk accept type. Example -R=\"hash3, hash4\"", ) startCmd.PersistentFlags(). - StringVarP( - &s.configs.ContainerBindProjectPath, + StringP( "container-bind-project-path", "P", s.configs.ContainerBindProjectPath, "Used to pass project path in host when running horusec cli inside a container.", ) startCmd.PersistentFlags(). - StringVarP( - &s.configs.CustomRulesPath, + StringP( "custom-rules-path", "c", s.configs.CustomRulesPath, "Used to pass the path to the horusec custom rules file. Example: -c=\"./horusec/horusec-custom-rules.json\".", ) startCmd.PersistentFlags(). - BoolVarP( - &s.configs.EnableInformationSeverity, + BoolP( "information-severity", "I", s.configs.EnableInformationSeverity, "Used to enable or disable information severity vulnerabilities, information vulnerabilities can contain a lot of false positives. Example: -I=\"true\"", ) startCmd.PersistentFlags(). - StringSliceVar( - &s.configs.ShowVulnerabilitiesTypes, + StringSlice( "show-vulnerabilities-types", s.configs.ShowVulnerabilitiesTypes, "Used to show in the output vulnerabilities of types: Vulnerability, Risk Accepted, False Positive, Corrected. Example --show-vulnerabilities-types=\"Vulnerability, Risk Accepted\"", ) startCmd.PersistentFlags(). - BoolVarP( - &s.configs.EnableOwaspDependencyCheck, + BoolP( "enable-owasp-dependency-check", "w", s.configs.EnableOwaspDependencyCheck, "Enable owasp dependency check. Example -w=\"true\". Default: false", ) startCmd.PersistentFlags(). - BoolVarP( - &s.configs.EnableShellCheck, + BoolP( "enable-shellcheck", "j", s.configs.EnableShellCheck, "Enable shellcheck. Example -h=\"true\". Default: false", @@ -296,8 +271,7 @@ func (s *Start) CreateStartCommand() *cobra.Command { if !dist.IsStandAlone() { startCmd.PersistentFlags(). - BoolVarP( - &s.configs.DisableDocker, + BoolP( "disable-docker", "D", s.configs.DisableDocker, "Used to run horusec without docker if enabled it will only run the following tools: horusec-csharp, horusec-kotlin, horusec-java, horusec-kubernetes, horusec-leaks, horusec-nodejs, horusec-dart, horusec-nginx. Example: -D=\"true\"", diff --git a/cmd/app/start/start_test.go b/cmd/app/start/start_test.go index 9fbbb30ed..b7a7455e1 100644 --- a/cmd/app/start/start_test.go +++ b/cmd/app/start/start_test.go @@ -23,8 +23,6 @@ import ( "github.com/google/uuid" - "github.com/spf13/cobra" - "github.com/ZupIT/horusec/internal/controllers/requirements" "github.com/sirupsen/logrus" @@ -37,7 +35,6 @@ import ( "github.com/ZupIT/horusec/internal/utils/prompt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -230,7 +227,7 @@ func TestStartCommand_Execute(t *testing.T) { stdoutMock := bytes.NewBufferString("") logrus.SetOutput(stdoutMock) - configs := config.New().MergeFromEnvironmentVariables() + configs := config.New().LoadFromEnvironmentVariables() configs.WorkDir = &workdir.WorkDir{} analyzerControllerMock := &analyzer.Mock{} @@ -355,10 +352,6 @@ func TestStartCommand_Execute(t *testing.T) { cobraCmd.SetOut(w) cobraCmd.SetArgs([]string{"-p", "./", "-o", "json", "-O", "./tmp-json.json"}) - cobra.OnInitialize(func() { - assert.NoError(t, configs.PreRun(nil, nil), "Expected nil error to pre run config") - }) - assert.NoError(t, cobraCmd.Execute()) err := w.Close() assert.NoError(t, err) @@ -413,10 +406,6 @@ func TestStartCommand_Execute(t *testing.T) { cobraCmd.SetOut(w) cobraCmd.SetArgs([]string{"-p", "./", "--information-severity", "true"}) - cobra.OnInitialize(func() { - require.Nil(t, configs.PreRun(nil, nil), "Expected nil error to pre run config") - }) - assert.NoError(t, cobraCmd.Execute()) err := w.Close() os.Stdout = oldStdout @@ -464,10 +453,6 @@ func TestStartCommand_Execute(t *testing.T) { cobraCmd.SetOut(w) cobraCmd.SetArgs([]string{"-p", "./", "-u", "https://google.com", "-a", uuid.NewString()}) - cobra.OnInitialize(func() { - require.Nil(t, configs.PreRun(nil, nil), "Expected nil error to pre run config") - }) - assert.NoError(t, cobraCmd.Execute()) err := w.Close() os.Stdout = oldStdout @@ -515,10 +500,6 @@ func TestStartCommand_Execute(t *testing.T) { cobraCmd.SetOut(w) cobraCmd.SetArgs([]string{"-p", "./", "-o", "sonarqube", "-O", "./tmp-sonarqube.json"}) - cobra.OnInitialize(func() { - require.Nil(t, configs.PreRun(nil, nil), "Expected nil error to pre run config") - }) - assert.NoError(t, cobraCmd.Execute()) err := w.Close() os.Stdout = oldStdout @@ -580,10 +561,6 @@ func TestStartCommand_Execute(t *testing.T) { cobraCmd.SetOut(w) cobraCmd.SetArgs([]string{"-p", dstProject, "-s", "CRITICAL, LOW"}) - cobra.OnInitialize(func() { - require.Nil(t, configs.PreRun(nil, nil), "Expected nil error to pre run config") - }) - assert.NoError(t, cobraCmd.Execute()) err := w.Close() os.Stdout = oldStdout @@ -638,10 +615,6 @@ func TestStartCommand_Execute(t *testing.T) { cobraCmd.SetOut(w) cobraCmd.SetArgs([]string{"-p", dstProject}) - cobra.OnInitialize(func() { - require.Nil(t, configs.PreRun(nil, nil), "Expected nil error to pre run config") - }) - assert.NoError(t, cobraCmd.Execute()) err := w.Close() os.Stdout = oldStdout diff --git a/config/.example-horusec-cli.json b/config/.example-horusec-cli.json index 8a6d56946..d1a898426 100644 --- a/config/.example-horusec-cli.json +++ b/config/.example-horusec-cli.json @@ -45,6 +45,5 @@ }, "horusecCliCustomImages": { "go": "docker.io/company/go:latest" - }, - "horusecCliLogFilePath": "./tmp" + } } diff --git a/config/config.go b/config/config.go index b008dd620..b7e52773f 100644 --- a/config/config.go +++ b/config/config.go @@ -179,14 +179,59 @@ func New() *Config { } } -// MergeFromConfigFile merge current instance of config with values -// configured on configuration file. +// LoadGlobalFlags load global flags into current config instance. +func (c *Config) LoadGlobalFlags(cmd *cobra.Command) *Config { + c.LogLevel = c.extractFlagValueString(cmd, "log-level", c.LogLevel) + c.ConfigFilePath = c.extractFlagValueString(cmd, "config-file-path", c.ConfigFilePath) + c.LogFilePath = c.extractFlagValueString(cmd, "log-file-path", c.LogFilePath) + return c +} + +// LoadGlobalFlags load start command flags into current config instance. // -// The config file path used here is the default or the value used in -// command line args. +//nolint:funlen +func (c *Config) LoadStartFlags(cmd *cobra.Command) *Config { + c.MonitorRetryInSeconds = c.extractFlagValueInt64(cmd, "monitor-retry-count", c.MonitorRetryInSeconds) + c.PrintOutputType = c.extractFlagValueString(cmd, "output-format", c.PrintOutputType) + c.JSONOutputFilePath = c.extractFlagValueString(cmd, "json-output-file", c.JSONOutputFilePath) + c.SeveritiesToIgnore = c.extractFlagValueStringSlice(cmd, "ignore-severity", c.SeveritiesToIgnore) + c.FilesOrPathsToIgnore = c.extractFlagValueStringSlice(cmd, "ignore", c.FilesOrPathsToIgnore) + c.HorusecAPIUri = c.extractFlagValueString(cmd, "horusec-url", c.HorusecAPIUri) + c.TimeoutInSecondsRequest = c.extractFlagValueInt64(cmd, "request-timeout", c.TimeoutInSecondsRequest) + c.TimeoutInSecondsAnalysis = c.extractFlagValueInt64(cmd, "analysis-timeout", c.TimeoutInSecondsAnalysis) + c.RepositoryAuthorization = c.extractFlagValueString(cmd, "authorization", c.RepositoryAuthorization) + c.Headers = c.extractFlagValueStringToString(cmd, "headers", c.Headers) + c.ReturnErrorIfFoundVulnerability = c.extractFlagValueBool(cmd, "return-error", c.ReturnErrorIfFoundVulnerability) + c.ProjectPath = c.extractFlagValueString(cmd, "project-path", c.ProjectPath) + c.EnableGitHistoryAnalysis = c.extractFlagValueBool(cmd, "enable-git-history", c.EnableGitHistoryAnalysis) + c.CertInsecureSkipVerify = c.extractFlagValueBool(cmd, "insecure-skip-verify", c.CertInsecureSkipVerify) + c.CertPath = c.extractFlagValueString(cmd, "certificate-path", c.CertPath) + c.EnableCommitAuthor = c.extractFlagValueBool(cmd, "enable-commit-author", c.EnableCommitAuthor) + c.RepositoryName = c.extractFlagValueString(cmd, "repository-name", c.RepositoryName) + c.FalsePositiveHashes = c.extractFlagValueStringSlice(cmd, "false-positive", c.FalsePositiveHashes) + c.RiskAcceptHashes = c.extractFlagValueStringSlice(cmd, "risk-accept", c.RiskAcceptHashes) + c.ContainerBindProjectPath = c.extractFlagValueString( + cmd, "container-bind-project-path", c.ContainerBindProjectPath, + ) + c.DisableDocker = c.extractFlagValueBool(cmd, "disable-docker", c.DisableDocker) + c.CustomRulesPath = c.extractFlagValueString(cmd, "custom-rules-path", c.CustomRulesPath) + c.EnableInformationSeverity = c.extractFlagValueBool(cmd, "information-severity", c.EnableInformationSeverity) + c.ShowVulnerabilitiesTypes = c.extractFlagValueStringSlice( + cmd, "show-vulnerabilities-types", c.ShowVulnerabilitiesTypes, + ) + c.EnableOwaspDependencyCheck = c.extractFlagValueBool( + cmd, "enable-owasp-dependency-check", c.EnableOwaspDependencyCheck, + ) + c.EnableShellCheck = c.extractFlagValueBool(cmd, "enable-shellcheck", c.EnableShellCheck) + return c +} + +// LoadFromConfigFile load config values from config file into current +// config instance. Note the values loaded from config file will override +// current config instance. // //nolint:funlen,gocyclo -func (c *Config) MergeFromConfigFile() *Config { +func (c *Config) LoadFromConfigFile() *Config { if !c.setViperConfigsAndReturnIfExistFile() { return c } @@ -284,11 +329,12 @@ func (c *Config) MergeFromConfigFile() *Config { return c } -// MergeFromEnvironmentVariables merge current instance of config with values -// configured on environment variables. +// LoadFromEnvironmentVariables load config values from environment variables into +// current config instance. Note the values loaded from environemtn variables will +// override current config instance. // //nolint:lll,funlen -func (c *Config) MergeFromEnvironmentVariables() *Config { +func (c *Config) LoadFromEnvironmentVariables() *Config { c.HorusecAPIUri = env.GetEnvOrDefault(EnvHorusecAPIUri, c.HorusecAPIUri) c.TimeoutInSecondsRequest = env.GetEnvOrDefaultInt64(EnvTimeoutInSecondsRequest, c.TimeoutInSecondsRequest) c.TimeoutInSecondsAnalysis = env.GetEnvOrDefaultInt64(EnvTimeoutInSecondsAnalysis, c.TimeoutInSecondsAnalysis) @@ -332,14 +378,30 @@ func (c *Config) MergeFromEnvironmentVariables() *Config { return c } -// PreRun is a hook that normalize config values and create the log file. -// This hook is used as a PreRun on cobra commands. -func (c *Config) PreRun(_ *cobra.Command, _ []string) error { - return c.Normalize().configureLogger() +// PersistentPreRun is a hook that load user input from command line, config file +// and environment variable. +// We need first read global flags from command line, and them read the config file. +// since the user can manipulate the path. Then we read environment variables if they +// exists (will override the values from config file). Finally we read the flags from +// start command that can override values from config file and environment variables. +// +// After each read values step we normalize the paths from relative to absolute and +// finally configure and create the log file. +func (c *Config) PersistentPreRun(cmd *cobra.Command, _ []string) error { + return c. + LoadGlobalFlags(cmd). + Normalize(). + LoadFromConfigFile(). + Normalize(). + LoadFromEnvironmentVariables(). + Normalize(). + LoadStartFlags(cmd). + Normalize(). + ConfigureLogger() } -// configureLogger create the log file and configure the log output. -func (c *Config) configureLogger() error { +// ConfigureLogger create the log file and configure the log output. +func (c *Config) ConfigureLogger() error { log, err := os.OpenFile(c.LogFilePath, os.O_CREATE|os.O_RDWR, os.ModePerm) if err != nil { return err @@ -356,7 +418,7 @@ func (c *Config) IsEmptyRepositoryAuthorization() bool { func (c *Config) setViperConfigsAndReturnIfExistFile() bool { logger.LogDebugWithLevel(messages.MsgDebugConfigFileRunningOnPath + c.ConfigFilePath) if _, err := os.Stat(c.ConfigFilePath); os.IsNotExist(err) { - logger.LogDebugWithLevel(messages.MsgDebugConfigFileNotFoundOnPath) + logger.LogWarn(messages.MsgDebugConfigFileNotFoundOnPath) return false } viper.SetConfigFile(c.ConfigFilePath) @@ -449,3 +511,50 @@ func (c *Config) replaceCommaToSpaceSliceString(input []string) []string { } return response } + +func (c *Config) extractFlagValueString(cmd *cobra.Command, name, defaultValue string) string { + if cmd.PersistentFlags().Changed(name) { + flagValue, err := cmd.PersistentFlags().GetString(name) + logger.LogPanicWithLevel(messages.MsgPanicGetFlagValue, err) + return flagValue + } + return defaultValue +} + +func (c *Config) extractFlagValueInt64(cmd *cobra.Command, name string, defaultValue int64) int64 { + if cmd.PersistentFlags().Changed(name) { + flagValue, err := cmd.PersistentFlags().GetInt64(name) + logger.LogPanicWithLevel(messages.MsgPanicGetFlagValue, err) + return flagValue + } + return defaultValue +} + +func (c *Config) extractFlagValueBool(cmd *cobra.Command, name string, defaultValue bool) bool { + if cmd.PersistentFlags().Changed(name) { + flagValue, err := cmd.PersistentFlags().GetBool(name) + logger.LogPanicWithLevel(messages.MsgPanicGetFlagValue, err) + + return flagValue + } + return defaultValue +} + +func (c *Config) extractFlagValueStringSlice(cmd *cobra.Command, name string, defaultValue []string) []string { + if cmd.PersistentFlags().Changed(name) { + flagValue, err := cmd.PersistentFlags().GetStringSlice(name) + logger.LogPanicWithLevel(messages.MsgPanicGetFlagValue, err) + return flagValue + } + return defaultValue +} + +func (c *Config) extractFlagValueStringToString( + cmd *cobra.Command, name string, defaultValue map[string]string) map[string]string { + if cmd.PersistentFlags().Changed(name) { + flagValue, err := cmd.PersistentFlags().GetStringToString(name) + logger.LogPanicWithLevel(messages.MsgPanicGetFlagValue, err) + return flagValue + } + return defaultValue +} diff --git a/config/config_test.go b/config/config_test.go index a71461dc8..660137c26 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -134,7 +134,7 @@ func TestNewHorusecConfig(t *testing.T) { assert.NoError(t, err) configs := config.New() configs.ConfigFilePath = configFilePath - configs.MergeFromConfigFile() + configs.LoadFromConfigFile() assert.Equal(t, configFilePath, configs.ConfigFilePath) assert.Equal(t, "http://new-viper.horusec.com", configs.HorusecAPIUri) assert.Equal(t, int64(20), configs.TimeoutInSecondsRequest) @@ -176,7 +176,7 @@ func TestNewHorusecConfig(t *testing.T) { assert.NoError(t, err) configs := config.New() configs.ConfigFilePath = configFilePath - configs.MergeFromConfigFile() + configs.LoadFromConfigFile() assert.Equal(t, configFilePath, configs.ConfigFilePath) assert.Equal(t, "http://new-viper.horusec.com", configs.HorusecAPIUri) assert.Equal(t, int64(20), configs.TimeoutInSecondsRequest) @@ -234,7 +234,7 @@ func TestNewHorusecConfig(t *testing.T) { assert.NoError(t, os.Setenv(config.EnvCustomRulesPath, "test")) assert.NoError(t, os.Setenv(config.EnvEnableInformationSeverity, "true")) assert.NoError(t, os.Setenv(config.EnvLogFilePath, "test")) - configs.MergeFromEnvironmentVariables() + configs.LoadFromEnvironmentVariables() assert.Equal(t, configFilePath, configs.ConfigFilePath) assert.Equal(t, "http://horusec.com", configs.HorusecAPIUri) @@ -277,7 +277,7 @@ func TestNewHorusecConfig(t *testing.T) { assert.NoError(t, err) configs := config.New() configs.ConfigFilePath = configFilePath - configs.MergeFromConfigFile() + configs.LoadFromConfigFile() assert.Equal(t, configFilePath, configs.ConfigFilePath) assert.Equal(t, "http://new-viper.horusec.com", configs.HorusecAPIUri) assert.Equal(t, int64(20), configs.TimeoutInSecondsRequest) @@ -333,7 +333,7 @@ func TestNewHorusecConfig(t *testing.T) { assert.NoError(t, os.Setenv(config.EnvEnableOwaspDependencyCheck, "true")) assert.NoError(t, os.Setenv(config.EnvEnableShellCheck, "true")) assert.NoError(t, os.Setenv(config.EnvShowVulnerabilitiesTypes, fmt.Sprintf("%s, %s", vulnerability.Vulnerability.ToString(), vulnerability.RiskAccepted.ToString()))) - configs.MergeFromEnvironmentVariables() + configs.LoadFromEnvironmentVariables() assert.Equal(t, configFilePath, configs.ConfigFilePath) assert.Equal(t, int64(99), configs.TimeoutInSecondsRequest) assert.Equal(t, int64(999), configs.TimeoutInSecondsAnalysis) @@ -365,8 +365,7 @@ func TestNewHorusecConfig(t *testing.T) { startCmd := start.NewStartCommand(configs) cobraCmd := startCmd.CreateStartCommand() - // Remove the pre run hook to override the output - cobraCmd.PreRunE = nil + cobraCmd.PersistentPreRunE = configs.PersistentPreRun target, err := os.MkdirTemp(os.TempDir(), "testing-target") assert.NoError(t, err) @@ -403,18 +402,19 @@ func TestNormalizeConfigs(t *testing.T) { func TestConfig_ToBytes(t *testing.T) { t.Run("Should success when parse config to json bytes without indent", func(t *testing.T) { - config := config.New().MergeFromEnvironmentVariables() + config := config.New().LoadFromEnvironmentVariables() assert.NotEmpty(t, config.ToBytes(false)) }) t.Run("Should success when parse config to json bytes with indent", func(t *testing.T) { - config := config.New().MergeFromEnvironmentVariables() + config := config.New().LoadFromEnvironmentVariables() assert.NotEmpty(t, config.ToBytes(true)) }) } + func TestSetLogOutput(t *testing.T) { t.Run("Should success when log path is empty", func(t *testing.T) { config := config.New() - err := config.PreRun(nil, nil) + err := config.ConfigureLogger() assert.NoError(t, err) }) t.Run("Should success when log path is valid", func(t *testing.T) { @@ -423,7 +423,7 @@ func TestSetLogOutput(t *testing.T) { config := config.New() config.LogFilePath = file.Name() - err = config.PreRun(nil, nil) + err = config.ConfigureLogger() assert.NoError(t, err) }) diff --git a/internal/usecases/cli/cli_test.go b/internal/usecases/cli/cli_test.go index 50292d26d..59c6452d6 100644 --- a/internal/usecases/cli/cli_test.go +++ b/internal/usecases/cli/cli_test.go @@ -87,7 +87,7 @@ func TestValidateConfigs(t *testing.T) { t.Run("Should return error when the text output file is invalid", func(t *testing.T) { cfg := config.New() cfg.WorkDir = &workdir.WorkDir{} - cfg.MergeFromEnvironmentVariables() + cfg.LoadFromEnvironmentVariables() cfg.PrintOutputType = outputtype.Text cfg.JSONOutputFilePath = "test.test" @@ -98,7 +98,7 @@ func TestValidateConfigs(t *testing.T) { t.Run("Should not return error when the text output file is valid", func(t *testing.T) { cfg := config.New() cfg.WorkDir = &workdir.WorkDir{} - cfg.MergeFromEnvironmentVariables() + cfg.LoadFromEnvironmentVariables() cfg.PrintOutputType = (outputtype.Text) cfg.JSONOutputFilePath = "test.txt"