From 8b70e7fc2fbbce6faae2a10b656c34836196d802 Mon Sep 17 00:00:00 2001 From: Zach Rice Date: Sat, 12 Mar 2022 10:44:51 -0600 Subject: [PATCH] handle goimports/go vet warnings --- cmd/detect.go | 38 ++++++++++------- cmd/protect.go | 98 ++++++++++++++++++++++++++++++------------- cmd/root.go | 15 +++++-- config/allowlist.go | 10 +---- config/config_test.go | 5 ++- config/rule.go | 7 ---- config/utils.go | 36 ---------------- detect/detect.go | 45 ++++++++++++++++---- detect/detect_test.go | 28 ++++++++++--- report/finding.go | 8 ---- report/report.go | 9 ++-- report/sarif_test.go | 6 ++- 12 files changed, 178 insertions(+), 127 deletions(-) diff --git a/cmd/detect.go b/cmd/detect.go index 7437ca32..43782be9 100644 --- a/cmd/detect.go +++ b/cmd/detect.go @@ -34,53 +34,58 @@ func runDetect(cmd *cobra.Command, args []string) { err error ) - viper.Unmarshal(&vc) + // Load config + if err = viper.Unmarshal(&vc); err != nil { + log.Fatal().Err(err).Msg("Failed to load config") + } cfg, err := vc.Translate() if err != nil { log.Fatal().Err(err).Msg("Failed to load config") } - cfg.Path, _ = cmd.Flags().GetString("config") - detector := detect.NewDetector(cfg) + // start timer start := time.Now() + // Setup detector + detector := detect.NewDetector(cfg) detector.Config.Path, err = cmd.Flags().GetString("config") if err != nil { log.Fatal().Err(err) } - source, err := cmd.Flags().GetString("source") if err != nil { log.Fatal().Err(err) } - - exitCode, err := cmd.Flags().GetInt("exit-code") - if err != nil { - log.Fatal().Err(err) - } - // if config path is not set, then use the {source}/.gitleaks.toml path. // note that there may not be a `{source}/.gitleaks.toml` file, this is ok. if detector.Config.Path == "" { detector.Config.Path = filepath.Join(source, ".gitleaks.toml") } - // set verbose flag if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil { log.Fatal().Err(err) } - // set redact flag if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil { log.Fatal().Err(err) } + // set exit code + exitCode, err := cmd.Flags().GetInt("exit-code") + if err != nil { + log.Fatal().Err(err) + } + + // determine what type of scan: + // - git: scan the history of the repo + // - no-git: scan files by treating the repo as a plain directory noGit, err := cmd.Flags().GetBool("no-git") if err != nil { log.Fatal().Err(err) } + // start the detector scan if noGit { findings, err = detector.DetectFiles(source) if err != nil { @@ -93,25 +98,28 @@ func runDetect(cmd *cobra.Command, args []string) { if err != nil { log.Fatal().Err(err) } - findings, err = detector.DetectGit(source, logOpts) + findings, err = detector.DetectGit(source, logOpts, detect.DetectType) if err != nil { // don't exit on error, just log it log.Error().Err(err) } } + // log info about the scan log.Info().Msgf("scan completed in %s", time.Since(start)) - if len(findings) != 0 { log.Warn().Msgf("leaks found: %d", len(findings)) } else { log.Info().Msg("no leaks found") } + // write report if desired reportPath, _ := cmd.Flags().GetString("report-path") ext, _ := cmd.Flags().GetString("report-format") if reportPath != "" { - report.Write(findings, cfg, ext, reportPath) + if err = report.Write(findings, cfg, ext, reportPath); err != nil { + log.Fatal().Err(err) + } } if len(findings) != 0 { diff --git a/cmd/protect.go b/cmd/protect.go index 7bd6c943..3229e7e6 100644 --- a/cmd/protect.go +++ b/cmd/protect.go @@ -1,11 +1,17 @@ package cmd import ( + "os" + "path/filepath" + "time" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/zricethezav/gitleaks/v8/config" + "github.com/zricethezav/gitleaks/v8/detect" + "github.com/zricethezav/gitleaks/v8/report" ) func init() { @@ -23,43 +29,77 @@ func runProtect(cmd *cobra.Command, args []string) { initConfig() var vc config.ViperConfig - viper.Unmarshal(&vc) + if err := viper.Unmarshal(&vc); err != nil { + log.Fatal().Err(err).Msg("Failed to load config") + } cfg, err := vc.Translate() if err != nil { log.Fatal().Err(err).Msg("Failed to load config") } cfg.Path, _ = cmd.Flags().GetString("config") - // source, _ := cmd.Flags().GetString("source") - // verbose, _ := cmd.Flags().GetBool("verbose") - // redact, _ := cmd.Flags().GetBool("redact") - // exitCode, _ := cmd.Flags().GetInt("exit-code") - // staged, _ := cmd.Flags().GetBool("staged") - // if cfg.Path == "" { - // cfg.Path = filepath.Join(source, ".gitleaks.toml") - // } - // start := time.Now() + exitCode, _ := cmd.Flags().GetInt("exit-code") + staged, _ := cmd.Flags().GetBool("staged") + start := time.Now() - // files, err := git.GitDiff(source, staged) - // if err != nil { - // log.Fatal().Err(err).Msg("Failed to get git log") - // } + // Setup detector + detector := detect.NewDetector(cfg) + detector.Config.Path, err = cmd.Flags().GetString("config") + if err != nil { + log.Fatal().Err(err) + } + source, err := cmd.Flags().GetString("source") + if err != nil { + log.Fatal().Err(err) + } + // if config path is not set, then use the {source}/.gitleaks.toml path. + // note that there may not be a `{source}/.gitleaks.toml` file, this is ok. + if detector.Config.Path == "" { + detector.Config.Path = filepath.Join(source, ".gitleaks.toml") + } + // set verbose flag + if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil { + log.Fatal().Err(err) + } + // set redact flag + if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil { + log.Fatal().Err(err) + } - // findings := detect.FromGit(files, cfg, detect.Options{Verbose: verbose, Redact: redact}) - // if len(findings) != 0 { - // log.Warn().Msgf("leaks found: %d", len(findings)) - // } else { - // log.Info().Msg("no leaks found") - // } + // get log options for git scan + logOpts, err := cmd.Flags().GetString("log-opts") + if err != nil { + log.Fatal().Err(err) + } - // log.Info().Msgf("scan duration: %s", time.Since(start)) + // start git scan + var findings []report.Finding + if staged { + findings, err = detector.DetectGit(source, logOpts, detect.ProtectStagedType) + } else { + findings, err = detector.DetectGit(source, logOpts, detect.ProtectType) + } + if err != nil { + // don't exit on error, just log it + log.Error().Err(err) + } - // reportPath, _ := cmd.Flags().GetString("report-path") - // ext, _ := cmd.Flags().GetString("report-format") - // if reportPath != "" { - // report.Write(findings, cfg, ext, reportPath) - // } - // if len(findings) != 0 { - // os.Exit(exitCode) - // } + // log info about the scan + log.Info().Msgf("scan completed in %s", time.Since(start)) + if len(findings) != 0 { + log.Warn().Msgf("leaks found: %d", len(findings)) + } else { + log.Info().Msg("no leaks found") + } + + reportPath, _ := cmd.Flags().GetString("report-path") + ext, _ := cmd.Flags().GetString("report-format") + if reportPath != "" { + if err = report.Write(findings, cfg, ext, reportPath); err != nil { + log.Fatal().Err(err) + } + } + if len(findings) != 0 { + os.Exit(exitCode) + } } diff --git a/cmd/root.go b/cmd/root.go index 46da82f6..808a4510 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -45,7 +45,10 @@ func init() { rootCmd.PersistentFlags().StringP("log-level", "l", "info", "log level (debug, info, warn, error, fatal)") rootCmd.PersistentFlags().BoolP("verbose", "v", false, "show verbose output from scan") rootCmd.PersistentFlags().Bool("redact", false, "redact secrets from logs and stdout") - viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config")) + err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config")) + if err != nil { + log.Fatal().Msgf("err binding config %s", err.Error()) + } } func initLog() { @@ -71,7 +74,7 @@ func initLog() { } func initConfig() { - fmt.Fprintf(os.Stderr, banner) + fmt.Fprint(os.Stderr, banner) cfgPath, err := rootCmd.Flags().GetString("config") if err != nil { log.Fatal().Msg(err.Error()) @@ -97,14 +100,18 @@ func initConfig() { log.Debug().Msgf("Unable to load gitleaks config from %s since --source=%s is a file, using default config", filepath.Join(source, ".gitleaks.toml"), source) viper.SetConfigType("toml") - viper.ReadConfig(strings.NewReader(config.DefaultConfig)) + if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil { + log.Fatal().Msgf("err reading toml %s", err.Error()) + } return } if _, err := os.Stat(filepath.Join(source, ".gitleaks.toml")); os.IsNotExist(err) { log.Debug().Msgf("No gitleaks config found in path %s, using default gitleaks config", filepath.Join(source, ".gitleaks.toml")) viper.SetConfigType("toml") - viper.ReadConfig(strings.NewReader(config.DefaultConfig)) + if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil { + log.Fatal().Msgf("err reading default config toml %s", err.Error()) + } return } else { log.Debug().Msgf("Using existing gitleaks config %s from `(--source)/.gitleaks.toml`", filepath.Join(source, ".gitleaks.toml")) diff --git a/config/allowlist.go b/config/allowlist.go index 00db78d9..d81c7784 100644 --- a/config/allowlist.go +++ b/config/allowlist.go @@ -22,15 +22,9 @@ func (a *Allowlist) CommitAllowed(c string) bool { } func (a *Allowlist) PathAllowed(path string) bool { - if anyRegexMatch(path, a.Paths) { - return true - } - return false + return anyRegexMatch(path, a.Paths) } func (a *Allowlist) RegexAllowed(s string) bool { - if anyRegexMatch(s, a.Regexes) { - return true - } - return false + return anyRegexMatch(s, a.Regexes) } diff --git a/config/config_test.go b/config/config_test.go index d652f018..cd87f7ae 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -103,7 +103,10 @@ func TestTranslate(t *testing.T) { } var vc ViperConfig - viper.Unmarshal(&vc) + err = viper.Unmarshal(&vc) + if err != nil { + t.Error(err) + } cfg, err := vc.Translate() if tt.wantError != nil { if err == nil { diff --git a/config/rule.go b/config/rule.go index 67c52a07..c6f93f5e 100644 --- a/config/rule.go +++ b/config/rule.go @@ -14,10 +14,3 @@ type Rule struct { Tags []string Allowlist Allowlist } - -func (r *Rule) EntropySet() bool { - if r.Entropy == 0.0 { - return false - } - return true -} diff --git a/config/utils.go b/config/utils.go index 7156281c..ada6ff0f 100644 --- a/config/utils.go +++ b/config/utils.go @@ -1,7 +1,6 @@ package config import ( - "math" "regexp" ) @@ -23,38 +22,3 @@ func regexMatched(f string, re *regexp.Regexp) bool { } return false } - -func containsDigit(s string) bool { - for _, c := range s { - switch c { - case '1', '2', '3', '4', '5', '6', '7', '8', '9': - return true - } - - } - return false -} - -// shannonEntropy calculates the entropy of data using the formula defined here: -// https://en.wiktionary.org/wiki/Shannon_entropy -// Another way to think about what this is doing is calculating the number of bits -// needed to on average encode the data. So, the higher the entropy, the more random the data, the -// more bits needed to encode that data. -func shannonEntropy(data string) (entropy float64) { - if data == "" { - return 0 - } - - charCounts := make(map[rune]int) - for _, char := range data { - charCounts[char]++ - } - - invLength := 1.0 / float64(len(data)) - for _, count := range charCounts { - freq := float64(count) * invLength - entropy -= freq * math.Log2(freq) - } - - return entropy -} diff --git a/detect/detect.go b/detect/detect.go index 352f40d6..a9eb99f7 100644 --- a/detect/detect.go +++ b/detect/detect.go @@ -19,6 +19,14 @@ import ( "github.com/spf13/viper" ) +type ScanType int + +const ( + DetectType ScanType = iota + ProtectType + ProtectStagedType +) + // Detector is the main detector struct type Detector struct { // Config is the configuration for the detector @@ -75,9 +83,15 @@ func NewDetector(cfg config.Config) *Detector { // NewDetectorDefaultConfig creates a new detector with the default config func NewDetectorDefaultConfig() (*Detector, error) { viper.SetConfigType("toml") - viper.ReadConfig(strings.NewReader(config.DefaultConfig)) + err := viper.ReadConfig(strings.NewReader(config.DefaultConfig)) + if err != nil { + return nil, err + } var vc config.ViperConfig - viper.Unmarshal(&vc) + err = viper.Unmarshal(&vc) + if err != nil { + return nil, err + } cfg, err := vc.Translate() if err != nil { return nil, err @@ -172,7 +186,7 @@ func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Fin // check entropy entropy := shannonEntropy(finding.Secret) finding.Entropy = float32(entropy) - if rule.EntropySet() { + if rule.Entropy != 0.0 { if entropy <= rule.Entropy { // entropy is too low, skip this finding continue @@ -199,10 +213,27 @@ func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Fin // GitScan accepts a *gitdiff.File channel which contents a git history generated from // the output of `git log -p ...`. startGitScan will look at each file (patch) in the history // and determine if the patch contains any findings. -func (d *Detector) DetectGit(source string, logOpts string) ([]report.Finding, error) { - history, err := git.GitLog(source, logOpts) - if err != nil { - return d.findings, err +func (d *Detector) DetectGit(source string, logOpts string, scanType ScanType) ([]report.Finding, error) { + var ( + history <-chan *gitdiff.File + err error + ) + switch scanType { + case DetectType: + history, err = git.GitLog(source, logOpts) + if err != nil { + return d.findings, err + } + case ProtectType: + history, err = git.GitDiff(source, false) + if err != nil { + return d.findings, err + } + case ProtectStagedType: + history, err = git.GitDiff(source, true) + if err != nil { + return d.findings, err + } } s := semgroup.NewGroup(context.Background(), 4) diff --git a/detect/detect_test.go b/detect/detect_test.go index 0b19fabf..0b3a0d3c 100644 --- a/detect/detect_test.go +++ b/detect/detect_test.go @@ -198,7 +198,10 @@ func TestDetect(t *testing.T) { } var vc config.ViperConfig - viper.Unmarshal(&vc) + err = viper.Unmarshal(&vc) + if err != nil { + t.Error(err) + } cfg, err := vc.Translate() cfg.Path = filepath.Join(configPath, tt.cfgName+".toml") if tt.wantError != nil { @@ -295,7 +298,11 @@ func TestFromGit(t *testing.T) { if err != nil { t.Fatal(err) } - defer moveDotGit(".git", "dotGit") + defer func() { + if err := moveDotGit(".git", "dotGit"); err != nil { + t.Error(err) + } + }() for _, tt := range tests { @@ -308,10 +315,16 @@ func TestFromGit(t *testing.T) { } var vc config.ViperConfig - viper.Unmarshal(&vc) - cfg, _ := vc.Translate() + err = viper.Unmarshal(&vc) + if err != nil { + t.Error(err) + } + cfg, err := vc.Translate() + if err != nil { + t.Error(err) + } detector := NewDetector(cfg) - findings, err := detector.DetectGit(tt.source, tt.logOpts) + findings, err := detector.DetectGit(tt.source, tt.logOpts, DetectType) if err != nil { t.Error(err) } @@ -380,7 +393,10 @@ func TestFromFiles(t *testing.T) { } var vc config.ViperConfig - viper.Unmarshal(&vc) + err = viper.Unmarshal(&vc) + if err != nil { + t.Error(err) + } cfg, _ := vc.Translate() detector := NewDetector(cfg) findings, err := detector.DetectFiles(tt.source) diff --git a/report/finding.go b/report/finding.go index 6a4d7f34..e5f68023 100644 --- a/report/finding.go +++ b/report/finding.go @@ -1,7 +1,6 @@ package report import ( - "strconv" "strings" ) @@ -43,10 +42,3 @@ func (f *Finding) Redact() { f.Match = strings.Replace(f.Match, f.Secret, "REDACTED", -1) f.Secret = "REDACT" } - -func (f *Finding) Hash() string { - return f.Secret + f.Commit + - strconv.Itoa(f.EndLine) + - strconv.Itoa(f.StartLine) - -} diff --git a/report/report.go b/report/report.go index 42bdac6f..c085c53b 100644 --- a/report/report.go +++ b/report/report.go @@ -21,13 +21,12 @@ func Write(findings []Finding, cfg config.Config, ext string, reportPath string) ext = strings.ToLower(ext) switch ext { case ".json", "json": - writeJson(findings, file) + err = writeJson(findings, file) case ".csv", "csv": - writeCsv(findings, file) + err = writeCsv(findings, file) case ".sarif", "sarif": - writeSarif(cfg, findings, file) - + err = writeSarif(cfg, findings, file) } - return nil + return err } diff --git a/report/sarif_test.go b/report/sarif_test.go index f2fb158f..565bc474 100644 --- a/report/sarif_test.go +++ b/report/sarif_test.go @@ -63,7 +63,11 @@ func TestWriteSarif(t *testing.T) { } var vc config.ViperConfig - viper.Unmarshal(&vc) + err = viper.Unmarshal(&vc) + if err != nil { + t.Error(err) + } + cfg, err := vc.Translate() if err != nil { t.Error(err)