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
)
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 {
+69 -29
View File
@@ -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)
}
}
+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().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"))
+2 -8
View File
@@ -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)
}
+4 -1
View File
@@ -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 {
-7
View File
@@ -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
}
-36
View File
@@ -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
}
+38 -7
View File
@@ -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)
+22 -6
View File
@@ -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)
-8
View File
@@ -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)
}
+4 -5
View File
@@ -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
}
+5 -1
View File
@@ -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)