Skip to content

Commit

Permalink
config: fix read config file if its not default value (#661)
Browse files Browse the repository at this point in the history
Previously we are reading the config file before parsing the command
line flags, so, when a user pass a different path of config
file we weren't read the file because we was trying to read on default
value (that is the current working directory). This commit change to
parse the values manually, so, we first parse global flags, them read the
config file and environment variables and finally parse the start command
flags. The changes on config/config.go is basically a rollback from changes
made on pr #523.

Issue: #656

Signed-off-by: Matheus Alcantara <matheus.alcantara@zup.com.br>
  • Loading branch information
matheusalcantarazup authored Oct 8, 2021
1 parent 3bbda9c commit 546906f
Show file tree
Hide file tree
Showing 8 changed files with 184 additions and 129 deletions.
12 changes: 6 additions & 6 deletions cmd/app/generate/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}

Expand Down
4 changes: 2 additions & 2 deletions cmd/app/generate/generate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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())

Expand Down
100 changes: 37 additions & 63 deletions cmd/app/start/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,227 +77,201 @@ 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",
)

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\"",
Expand Down
29 changes: 1 addition & 28 deletions cmd/app/start/start_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ import (

"github.com/google/uuid"

"github.com/spf13/cobra"

"github.com/ZupIT/horusec/internal/controllers/requirements"

"github.com/sirupsen/logrus"
Expand All @@ -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) {
Expand Down Expand Up @@ -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{}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading

0 comments on commit 546906f

Please sign in to comment.