handle goimports/go vet warnings

This commit is contained in:
Zach Rice committed 2022-03-12 10:44:51 -06:00
1 parent 57d2d345b6
commit 8b70e7fc2f
12 files changed
+178 -127

No files matched your search

+23 -15
View File
@@ -34,53 +34,58 @@ func runDetect(cmd *cobra.Command, args []string) {
err error 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() cfg, err := vc.Translate()
if err != nil { if err != nil {
log.Fatal().Err(err).Msg("Failed to load config") log.Fatal().Err(err).Msg("Failed to load config")
} }
cfg.Path, _ = cmd.Flags().GetString("config") cfg.Path, _ = cmd.Flags().GetString("config")
detector := detect.NewDetector(cfg)
// start timer
start := time.Now() start := time.Now()
// Setup detector
detector := detect.NewDetector(cfg)
detector.Config.Path, err = cmd.Flags().GetString("config") detector.Config.Path, err = cmd.Flags().GetString("config")
if err != nil { if err != nil {
log.Fatal().Err(err) log.Fatal().Err(err)
} }
source, err := cmd.Flags().GetString("source") source, err := cmd.Flags().GetString("source")
if err != nil { if err != nil {
log.Fatal().Err(err) 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. // 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. // note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
if detector.Config.Path == "" { if detector.Config.Path == "" {
detector.Config.Path = filepath.Join(source, ".gitleaks.toml") detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
} }
// set verbose flag // set verbose flag
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil { if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
log.Fatal().Err(err) log.Fatal().Err(err)
} }
// set redact flag // set redact flag
if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil { if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
log.Fatal().Err(err) 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") noGit, err := cmd.Flags().GetBool("no-git")
if err != nil { if err != nil {
log.Fatal().Err(err) log.Fatal().Err(err)
} }
// start the detector scan
if noGit { if noGit {
findings, err = detector.DetectFiles(source) findings, err = detector.DetectFiles(source)
if err != nil { if err != nil {
@@ -93,25 +98,28 @@ func runDetect(cmd *cobra.Command, args []string) {
if err != nil { if err != nil {
log.Fatal().Err(err) log.Fatal().Err(err)
} }
findings, err = detector.DetectGit(source, logOpts) findings, err = detector.DetectGit(source, logOpts, detect.DetectType)
if err != nil { if err != nil {
// don't exit on error, just log it // don't exit on error, just log it
log.Error().Err(err) log.Error().Err(err)
} }
} }
// log info about the scan
log.Info().Msgf("scan completed in %s", time.Since(start)) log.Info().Msgf("scan completed in %s", time.Since(start))
if len(findings) != 0 { if len(findings) != 0 {
log.Warn().Msgf("leaks found: %d", len(findings)) log.Warn().Msgf("leaks found: %d", len(findings))
} else { } else {
log.Info().Msg("no leaks found") log.Info().Msg("no leaks found")
} }
// write report if desired
reportPath, _ := cmd.Flags().GetString("report-path") reportPath, _ := cmd.Flags().GetString("report-path")
ext, _ := cmd.Flags().GetString("report-format") ext, _ := cmd.Flags().GetString("report-format")
if reportPath != "" { 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 { if len(findings) != 0 {
+69 -29
View File
@@ -1,11 +1,17 @@
package cmd package cmd
import ( import (
"os"
"path/filepath"
"time"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/zricethezav/gitleaks/v8/config" "github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/report"
) )
func init() { func init() {
@@ -23,43 +29,77 @@ func runProtect(cmd *cobra.Command, args []string) {
initConfig() initConfig()
var vc config.ViperConfig 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() cfg, err := vc.Translate()
if err != nil { if err != nil {
log.Fatal().Err(err).Msg("Failed to load config") log.Fatal().Err(err).Msg("Failed to load config")
} }
cfg.Path, _ = cmd.Flags().GetString("config") cfg.Path, _ = cmd.Flags().GetString("config")
// source, _ := cmd.Flags().GetString("source") exitCode, _ := cmd.Flags().GetInt("exit-code")
// verbose, _ := cmd.Flags().GetBool("verbose") staged, _ := cmd.Flags().GetBool("staged")
// redact, _ := cmd.Flags().GetBool("redact") start := time.Now()
// exitCode, _ := cmd.Flags().GetInt("exit-code")
// staged, _ := cmd.Flags().GetBool("staged")
// if cfg.Path == "" {
// cfg.Path = filepath.Join(source, ".gitleaks.toml")
// }
// start := time.Now()
// files, err := git.GitDiff(source, staged) // Setup detector
// if err != nil { detector := detect.NewDetector(cfg)
// log.Fatal().Err(err).Msg("Failed to get git log") 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}) // get log options for git scan
// if len(findings) != 0 { logOpts, err := cmd.Flags().GetString("log-opts")
// log.Warn().Msgf("leaks found: %d", len(findings)) if err != nil {
// } else { log.Fatal().Err(err)
// log.Info().Msg("no leaks found") }
// }
// 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") // log info about the scan
// ext, _ := cmd.Flags().GetString("report-format") log.Info().Msgf("scan completed in %s", time.Since(start))
// if reportPath != "" { if len(findings) != 0 {
// report.Write(findings, cfg, ext, reportPath) log.Warn().Msgf("leaks found: %d", len(findings))
// } } else {
// if len(findings) != 0 { log.Info().Msg("no leaks found")
// os.Exit(exitCode) }
// }
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)
}
} }
+11 -4
View File
@@ -45,7 +45,10 @@ func init() {
rootCmd.PersistentFlags().StringP("log-level", "l", "info", "log level (debug, info, warn, error, fatal)") 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().BoolP("verbose", "v", false, "show verbose output from scan")
rootCmd.PersistentFlags().Bool("redact", false, "redact secrets from logs and stdout") 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() { func initLog() {
@@ -71,7 +74,7 @@ func initLog() {
} }
func initConfig() { func initConfig() {
fmt.Fprintf(os.Stderr, banner) fmt.Fprint(os.Stderr, banner)
cfgPath, err := rootCmd.Flags().GetString("config") cfgPath, err := rootCmd.Flags().GetString("config")
if err != nil { if err != nil {
log.Fatal().Msg(err.Error()) 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", 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) filepath.Join(source, ".gitleaks.toml"), source)
viper.SetConfigType("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 toml %s", err.Error())
}
return return
} }
if _, err := os.Stat(filepath.Join(source, ".gitleaks.toml")); os.IsNotExist(err) { 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")) log.Debug().Msgf("No gitleaks config found in path %s, using default gitleaks config", filepath.Join(source, ".gitleaks.toml"))
viper.SetConfigType("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 return
} else { } else {
log.Debug().Msgf("Using existing gitleaks config %s from `(--source)/.gitleaks.toml`", filepath.Join(source, ".gitleaks.toml")) log.Debug().Msgf("Using existing gitleaks config %s from `(--source)/.gitleaks.toml`", filepath.Join(source, ".gitleaks.toml"))
+2 -8
View File
@@ -22,15 +22,9 @@ func (a *Allowlist) CommitAllowed(c string) bool {
} }
func (a *Allowlist) PathAllowed(path string) bool { func (a *Allowlist) PathAllowed(path string) bool {
if anyRegexMatch(path, a.Paths) { return anyRegexMatch(path, a.Paths)
return true
}
return false
} }
func (a *Allowlist) RegexAllowed(s string) bool { func (a *Allowlist) RegexAllowed(s string) bool {
if anyRegexMatch(s, a.Regexes) { return anyRegexMatch(s, a.Regexes)
return true
}
return false
} }
+4 -1
View File
@@ -103,7 +103,10 @@ func TestTranslate(t *testing.T) {
} }
var vc ViperConfig var vc ViperConfig
viper.Unmarshal(&vc) err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, err := vc.Translate() cfg, err := vc.Translate()
if tt.wantError != nil { if tt.wantError != nil {
if err == nil { if err == nil {
-7
View File
@@ -14,10 +14,3 @@ type Rule struct {
Tags []string Tags []string
Allowlist Allowlist Allowlist Allowlist
} }
func (r *Rule) EntropySet() bool {
if r.Entropy == 0.0 {
return false
}
return true
}
-36
View File
@@ -1,7 +1,6 @@
package config package config
import ( import (
"math"
"regexp" "regexp"
) )
@@ -23,38 +22,3 @@ func regexMatched(f string, re *regexp.Regexp) bool {
} }
return false 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
}
+38 -7
View File
@@ -19,6 +19,14 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
) )
type ScanType int
const (
DetectType ScanType = iota
ProtectType
ProtectStagedType
)
// Detector is the main detector struct // Detector is the main detector struct
type Detector struct { type Detector struct {
// Config is the configuration for the detector // 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 // NewDetectorDefaultConfig creates a new detector with the default config
func NewDetectorDefaultConfig() (*Detector, error) { func NewDetectorDefaultConfig() (*Detector, error) {
viper.SetConfigType("toml") 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 var vc config.ViperConfig
viper.Unmarshal(&vc) err = viper.Unmarshal(&vc)
if err != nil {
return nil, err
}
cfg, err := vc.Translate() cfg, err := vc.Translate()
if err != nil { if err != nil {
return nil, err return nil, err
@@ -172,7 +186,7 @@ func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Fin
// check entropy // check entropy
entropy := shannonEntropy(finding.Secret) entropy := shannonEntropy(finding.Secret)
finding.Entropy = float32(entropy) finding.Entropy = float32(entropy)
if rule.EntropySet() { if rule.Entropy != 0.0 {
if entropy <= rule.Entropy { if entropy <= rule.Entropy {
// entropy is too low, skip this finding // entropy is too low, skip this finding
continue 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 // 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 // the output of `git log -p ...`. startGitScan will look at each file (patch) in the history
// and determine if the patch contains any findings. // and determine if the patch contains any findings.
func (d *Detector) DetectGit(source string, logOpts string) ([]report.Finding, error) { func (d *Detector) DetectGit(source string, logOpts string, scanType ScanType) ([]report.Finding, error) {
history, err := git.GitLog(source, logOpts) var (
if err != nil { history <-chan *gitdiff.File
return d.findings, err 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) s := semgroup.NewGroup(context.Background(), 4)
+22 -6
View File
@@ -198,7 +198,10 @@ func TestDetect(t *testing.T) {
} }
var vc config.ViperConfig var vc config.ViperConfig
viper.Unmarshal(&vc) err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, err := vc.Translate() cfg, err := vc.Translate()
cfg.Path = filepath.Join(configPath, tt.cfgName+".toml") cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
if tt.wantError != nil { if tt.wantError != nil {
@@ -295,7 +298,11 @@ func TestFromGit(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer moveDotGit(".git", "dotGit") defer func() {
if err := moveDotGit(".git", "dotGit"); err != nil {
t.Error(err)
}
}()
for _, tt := range tests { for _, tt := range tests {
@@ -308,10 +315,16 @@ func TestFromGit(t *testing.T) {
} }
var vc config.ViperConfig var vc config.ViperConfig
viper.Unmarshal(&vc) err = viper.Unmarshal(&vc)
cfg, _ := vc.Translate() if err != nil {
t.Error(err)
}
cfg, err := vc.Translate()
if err != nil {
t.Error(err)
}
detector := NewDetector(cfg) detector := NewDetector(cfg)
findings, err := detector.DetectGit(tt.source, tt.logOpts) findings, err := detector.DetectGit(tt.source, tt.logOpts, DetectType)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@@ -380,7 +393,10 @@ func TestFromFiles(t *testing.T) {
} }
var vc config.ViperConfig var vc config.ViperConfig
viper.Unmarshal(&vc) err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, _ := vc.Translate() cfg, _ := vc.Translate()
detector := NewDetector(cfg) detector := NewDetector(cfg)
findings, err := detector.DetectFiles(tt.source) findings, err := detector.DetectFiles(tt.source)
-8
View File
@@ -1,7 +1,6 @@
package report package report
import ( import (
"strconv"
"strings" "strings"
) )
@@ -43,10 +42,3 @@ func (f *Finding) Redact() {
f.Match = strings.Replace(f.Match, f.Secret, "REDACTED", -1) f.Match = strings.Replace(f.Match, f.Secret, "REDACTED", -1)
f.Secret = "REDACT" f.Secret = "REDACT"
} }
func (f *Finding) Hash() string {
return f.Secret + f.Commit +
strconv.Itoa(f.EndLine) +
strconv.Itoa(f.StartLine)
}
+4 -5
View File
@@ -21,13 +21,12 @@ func Write(findings []Finding, cfg config.Config, ext string, reportPath string)
ext = strings.ToLower(ext) ext = strings.ToLower(ext)
switch ext { switch ext {
case ".json", "json": case ".json", "json":
writeJson(findings, file) err = writeJson(findings, file)
case ".csv", "csv": case ".csv", "csv":
writeCsv(findings, file) err = writeCsv(findings, file)
case ".sarif", "sarif": case ".sarif", "sarif":
writeSarif(cfg, findings, file) err = writeSarif(cfg, findings, file)
} }
return nil return err
} }
+5 -1
View File
@@ -63,7 +63,11 @@ func TestWriteSarif(t *testing.T) {
} }
var vc config.ViperConfig var vc config.ViperConfig
viper.Unmarshal(&vc) err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, err := vc.Translate() cfg, err := vc.Translate()
if err != nil { if err != nil {
t.Error(err) t.Error(err)