diff --git a/config/rule.go b/config/rule.go index 78bca124..67c52a07 100644 --- a/config/rule.go +++ b/config/rule.go @@ -2,7 +2,6 @@ package config import ( "regexp" - "strings" ) type Rule struct { @@ -16,27 +15,6 @@ type Rule struct { Allowlist Allowlist } -func (r *Rule) IncludeEntropy(secret string) (bool, float64) { - // NOTE: this is a goofy hack to get around the fact there golang's regex engine - // does not support positive lookaheads. Ideally we would want to add a - // restriction on generic rules regex that requires the secret match group - // contains both numbers and alphabetical characters. What this bit of code does is - // check if the ruleid is prepended with "generic" and enforces the - // secret contains both digits and alphabetical characters. - if strings.HasPrefix(r.RuleID, "generic") { - if !containsDigit(secret) { - return false, 0.0 - } - } - // group = 0 will check the entropy of the whole regex match - e := shannonEntropy(secret) - if e > r.Entropy { - return true, e - } - - return false, e -} - func (r *Rule) EntropySet() bool { if r.Entropy == 0.0 { return false diff --git a/detect/detect.go b/detect/detect.go index cfdc82bd..4f34c461 100644 --- a/detect/detect.go +++ b/detect/detect.go @@ -1,144 +1,376 @@ package detect import ( - "encoding/json" + "context" "fmt" + "math" + "os" + "path/filepath" "regexp" "strings" + "sync" - "github.com/rs/zerolog/log" - + "github.com/fatih/semgroup" + "github.com/gitleaks/go-gitdiff/gitdiff" + "github.com/spf13/cobra" "github.com/zricethezav/gitleaks/v8/config" + "github.com/zricethezav/gitleaks/v8/detect/git" "github.com/zricethezav/gitleaks/v8/report" ) -type Options struct { - Verbose bool - Redact bool +// Detector is the main detector struct +type Detector struct { + // cfg is the configuration for the detector + cfg config.Config + + redact bool + + verbose bool + + // maybe use cmd? + + // commitMap is used to keep track of commits that have been scanned. + // This is only used for logging purposes and git scans. + commitMap map[string]bool + + // findingMutex is to prevent concurrent access to the + // findings slice when adding findings. + findingMutex *sync.Mutex + + findings []report.Finding } -const MAXGOROUTINES = 4 +// Fragment contains the data to be scanned. Other names to consider: segment, section, part +type Fragment struct { + // Raw is the raw content of the fragment + Raw string -func DetectFindings(cfg config.Config, b []byte, filePath string, commit string) []report.Finding { + // FilePath is the path to the file + FilePath string + + // CommitSHA is the SHA of the commit + CommitSHA string + + // RuleID is the ID of the rule that is to be used. If no RuleID is set then the entire + // rule set will be used + RuleID string + + newlineIndices [][]int +} + +func NewDetector(cfg config.Config) *Detector { + return &Detector{ + cfg: cfg, + } +} + +func NewDetectorDefaultConfig() *Detector { + // TODO load default config + // return NewDetector() + return nil +} + +// Start is called from cmd +func (d *Detector) Start(cmd *cobra.Command) ([]report.Finding, error) { + var ( + findings []report.Finding + err error + ) + + d.cfg.Path, err = cmd.Flags().GetString("config") + if err != nil { + return findings, err + } + + source, err := cmd.Flags().GetString("source") + if err != nil { + return findings, 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 d.cfg.Path == "" { + d.cfg.Path = filepath.Join(source, ".gitleaks.toml") + } + + if d.verbose, err = cmd.Flags().GetBool("verbose"); err != nil { + return findings, err + } + if d.redact, err = cmd.Flags().GetBool("redact"); err != nil { + return findings, err + } + noGit, err := cmd.Flags().GetBool("no-git") + if err != nil { + return findings, err + } + + if noGit { + // TODO treat the repo as a directory + } else { + // TODO scan git history + logOpts, err := cmd.Flags().GetString("log-opts") + if err != nil { + return findings, err + } + // TODO abstract git log to "producer" or "pipe" + history, err := git.GitLog(d.cfg.Path, logOpts) + if err != nil { + return findings, err + } + findings = d.startGitScan(history) + } + + // TODO generate report, check exit code, etc + exitCode, err := cmd.Flags().GetInt("exit-code") + + return findings, nil +} + +// DetectBytes scans the given bytes and returns a list of findings +func (d *Detector) DetectBytes(content []byte) []report.Finding { + return d.DetectString(string(content)) +} + +// DetectString scans the given string and returns a list of findings +func (d *Detector) DetectString(content string) []report.Finding { + return d.Detect(Fragment{ + Raw: content, + }) +} + +// Detect scans the given fragment and returns a list of findings +func (d *Detector) Detect(fragment Fragment) []report.Finding { var findings []report.Finding - linePairs := regexp.MustCompile("\n").FindAllIndex(b, -1) - // check if we should skip file based on the global allowlist or if the file is the same as the gitleaks config - if cfg.Allowlist.PathAllowed(filePath) || filePath == cfg.Path { + // check if filepath is allowed + if d.cfg.Allowlist.PathAllowed(fragment.FilePath) || + fragment.FilePath == d.cfg.Path { return findings } - for _, r := range cfg.Rules { - pathSkip := false - if r.Allowlist.CommitAllowed(commit) { - continue - } - if r.Allowlist.PathAllowed(filePath) { - continue - } + // add newline indices for location calculation in detectRule + fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1) - // Check if path should be considered - if r.Path != nil { - if r.Path.Match([]byte(filePath)) { - if r.Regex == nil { - // This is a path only rule - f := report.Finding{ - Description: r.Description, - File: filePath, - RuleID: r.RuleID, - Match: fmt.Sprintf("file detected: %s", filePath), - Tags: r.Tags, - } - findings = append(findings, f) - pathSkip = true - } - } else { - pathSkip = true + for _, rule := range d.cfg.Rules { + findings = append(findings, d.detectRule(fragment, rule)...) + } + return findings +} + +func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Finding { + var findings []report.Finding + + // check if filepath or commit is allowed for this rule + if rule.Allowlist.CommitAllowed(fragment.CommitSHA) || + rule.Allowlist.PathAllowed(fragment.FilePath) { + return findings + } + + if rule.Path != nil && rule.Regex == nil { + // Path _only_ rule + if rule.Path.Match([]byte(fragment.FilePath)) { + finding := report.Finding{ + Description: rule.Description, + File: fragment.FilePath, + RuleID: rule.RuleID, + Match: fmt.Sprintf("file detected: %s", fragment.FilePath), + Tags: rule.Tags, } + return append(findings, finding) } - if pathSkip { + } else if rule.Path != nil { + // if path is set _and_ a regex is set, then we need to check both + // so if the path does not match, then we should return early and not + // consider the regex + if !rule.Path.Match([]byte(fragment.FilePath)) { + return findings + } + } + + matchIndices := rule.Regex.FindAllStringIndex(fragment.Raw, -1) + for _, matchIndex := range matchIndices { + // extract secret from match + secret := strings.Trim(fragment.Raw[matchIndex[0]:matchIndex[1]], " \n") + + // determine location of match. Note that the location + // in the finding will be the line/column numbers of the _match_ + // not the _secret_, which will be different if the secretGroup + // value is set for this rule + loc := location(fragment, matchIndex) + + finding := report.Finding{ + Description: rule.Description, + File: fragment.FilePath, + RuleID: rule.RuleID, + StartLine: loc.startLine, + EndLine: loc.endLine, + StartColumn: loc.startColumn, + EndColumn: loc.endColumn, + Secret: secret, + Match: secret, + Tags: rule.Tags, + } + + // check if the secret is in the allowlist + if rule.Allowlist.RegexAllowed(finding.Secret) || + d.cfg.Allowlist.RegexAllowed(finding.Secret) { continue } - matchIndices := r.Regex.FindAllIndex(b, -1) - for _, m := range matchIndices { - location := getLocation(linePairs, m[0], m[1]) - secret := strings.Trim(string(b[m[0]:m[1]]), "\n") - f := report.Finding{ - Description: r.Description, - File: filePath, - RuleID: r.RuleID, - StartLine: location.startLine, - EndLine: location.endLine, - StartColumn: location.startColumn, - EndColumn: location.endColumn, - Secret: secret, - Match: secret, - Tags: r.Tags, + // extract secret from secret group if set + if rule.SecretGroup != 0 { + groups := rule.Regex.FindStringSubmatch(secret) + if len(groups) <= rule.SecretGroup || len(groups) == 0 { + // Config validation should prevent this + break } + secret = groups[rule.SecretGroup] + finding.Secret = secret + } - if r.Allowlist.RegexAllowed(f.Secret) || cfg.Allowlist.RegexAllowed(f.Secret) { + // check entropy + finding.Entropy = float32(shannonEntropy(secret)) + if rule.EntropySet() && finding.Entropy < float32(rule.Entropy) { + return findings + } + } + return findings +} + +func (d *Detector) startGitScan(gitdiffFiles <-chan *gitdiff.File) []report.Finding { + var findings []report.Finding + + s := semgroup.NewGroup(context.Background(), 4) + + for f := range gitdiffFiles { + f := f + + // skip binary files + if f.IsBinary || f.IsDelete { + continue + } + + // Check if commit is allowed + commitSHA := "" + if f.PatchHeader != nil { + commitSHA = f.PatchHeader.SHA + if d.cfg.Allowlist.CommitAllowed(f.PatchHeader.SHA) { continue } - - // extract secret from secret group if set - if r.SecretGroup != 0 { - groups := r.Regex.FindStringSubmatch(secret) - if len(groups) <= r.SecretGroup || len(groups) == 0 { - // Config validation should prevent this - break - } - secret = groups[r.SecretGroup] - f.Secret = secret - } - - // extract secret from secret group if set - if r.EntropySet() { - include, entropy := r.IncludeEntropy(secret) - if include { - f.Entropy = float32(entropy) - findings = append(findings, f) - } - } else { - findings = append(findings, f) - } } + d.addCommit(commitSHA) + + s.Go(func() error { + for _, textFragment := range f.TextFragments { + if textFragment == nil { + return nil + } + + fragment := Fragment{ + Raw: textFragment.Raw(gitdiff.OpAdd), + CommitSHA: commitSHA, + FilePath: f.NewName, + } + + for _, finding := range d.Detect(fragment) { + d.addFinding(augmentFinding(finding, textFragment, d.redact)) + } + } + return nil + }) + } - return dedupe(findings) + return findings } -func printFinding(f report.Finding) { - var b []byte - b, _ = json.MarshalIndent(f, "", " ") - fmt.Println(string(b)) -} - -func dedupe(findings []report.Finding) []report.Finding { - var retFindings []report.Finding - for _, f := range findings { - include := true - if strings.Contains(strings.ToLower(f.RuleID), "generic") { - for _, fPrime := range findings { - if f.StartLine == fPrime.StartLine && - f.EndLine == fPrime.EndLine && - f.Commit == fPrime.Commit && - f.RuleID != fPrime.RuleID && - strings.Contains(fPrime.Secret, f.Secret) && - !strings.Contains(strings.ToLower(fPrime.RuleID), "generic") { - - genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1) - betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1) - log.Debug().Msgf("skipping %s finding (%s), %s rule takes precendence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch) - include = false - break +func (d *Detector) startFileScan(source string) []report.Finding { + var findings []report.Finding + s := semgroup.NewGroup(context.Background(), 4) + paths := make(chan string) + s.Go(func() error { + defer close(paths) + return filepath.Walk(source, + func(path string, fInfo os.FileInfo, err error) error { + if err != nil { + return err } + if fInfo.Name() == ".git" { + return filepath.SkipDir + } + if fInfo.Mode().IsRegular() { + paths <- path + } + return nil + }) + return nil + }) + for pa := range paths { + p := pa + s.Go(func() error { + b, err := os.ReadFile(p) + if err != nil { + return err } - } - if include { - retFindings = append(retFindings, f) - } + fragment := Fragment{ + Raw: string(b), + FilePath: p, + } + d.Detect(fragment) + + return nil + }) } - return retFindings + return findings +} + +func (d *Detector) addFinding(finding report.Finding) { + d.findingMutex.Lock() + d.findings = append(d.findings, finding) + d.findingMutex.Unlock() +} + +func (d *Detector) addCommit(commit string) { + d.commitMap[commit] = true +} + +func augmentFinding(finding report.Finding, textFragment *gitdiff.TextFragment, redact bool) report.Finding { + if !strings.HasPrefix(finding.Match, "file detected") { + finding.StartLine += int(textFragment.NewPosition) + finding.EndLine += int(textFragment.NewPosition) + } + + // TODO handle redact + + return finding +} + +// filter inspects each finding and removes the findings that are allowed (whether that be by the rule allowlist or global allowlist) +func (d *Detector) filter(findings []report.Finding) []report.Finding { + return findings +} + +// 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/files.go b/detect/files.go deleted file mode 100644 index 3ab1b6ae..00000000 --- a/detect/files.go +++ /dev/null @@ -1,77 +0,0 @@ -package detect - -import ( - "context" - "os" - "path/filepath" - "sync" - - "golang.org/x/sync/errgroup" - - "github.com/zricethezav/gitleaks/v8/config" - "github.com/zricethezav/gitleaks/v8/report" -) - -// FromFiles opens the directory or file specified in source and checks each file against the rules -// from the configuration. If any secrets are found, they are added to the list of findings. -func FromFiles(source string, cfg config.Config, outputOptions Options) ([]report.Finding, error) { - var ( - findings []report.Finding - mu sync.Mutex - ) - concurrentGoroutines := make(chan struct{}, MAXGOROUTINES) - g, _ := errgroup.WithContext(context.Background()) - paths := make(chan string) - g.Go(func() error { - defer close(paths) - return filepath.Walk(source, - func(path string, fInfo os.FileInfo, err error) error { - if err != nil { - return err - } - if fInfo.Name() == ".git" { - return filepath.SkipDir - } - if fInfo.Mode().IsRegular() { - paths <- path - } - return nil - }) - }) - for pa := range paths { - p := pa - concurrentGoroutines <- struct{}{} - g.Go(func() error { - defer func() { - <-concurrentGoroutines - }() - b, err := os.ReadFile(p) - if err != nil { - return err - } - fis := DetectFindings(cfg, b, p, "") - for _, fi := range fis { - // need to add 1 since line counting starts at 1 - fi.StartLine++ - fi.EndLine++ - - if outputOptions.Redact { - fi.Redact() - } - if outputOptions.Verbose { - printFinding(fi) - } - mu.Lock() - findings = append(findings, fi) - mu.Unlock() - } - return nil - }) - } - - if err := g.Wait(); err != nil { - return findings, err - } - - return findings, nil -} diff --git a/detect/files_test.go b/detect/files_test.go deleted file mode 100644 index 34e3e4d0..00000000 --- a/detect/files_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package detect - -import ( - "path/filepath" - "testing" - - "github.com/spf13/viper" - "github.com/stretchr/testify/assert" - - "github.com/zricethezav/gitleaks/v8/config" - "github.com/zricethezav/gitleaks/v8/report" -) - -// TestFromGit tests the FromGit function -func TestFromFiles(t *testing.T) { - tests := []struct { - cfgName string - opts Options - source string - expectedFindings []report.Finding - }{ - { - source: filepath.Join(repoBasePath, "nogit"), - cfgName: "simple", - expectedFindings: []report.Finding{ - { - Description: "AWS Access Key", - StartLine: 20, - EndLine: 20, - StartColumn: 16, - EndColumn: 35, - Match: "AKIALALEMEL33243OLIA", - Secret: "AKIALALEMEL33243OLIA", - File: "../testdata/repos/nogit/main.go", - RuleID: "aws-access-key", - Tags: []string{"key", "AWS"}, - }, - }, - }, - { - source: filepath.Join(repoBasePath, "nogit", "main.go"), - cfgName: "simple", - expectedFindings: []report.Finding{ - { - Description: "AWS Access Key", - StartLine: 20, - EndLine: 20, - StartColumn: 16, - EndColumn: 35, - Match: "AKIALALEMEL33243OLIA", - Secret: "AKIALALEMEL33243OLIA", - File: "../testdata/repos/nogit/main.go", - RuleID: "aws-access-key", - Tags: []string{"key", "AWS"}, - }, - }, - }, - } - - for _, tt := range tests { - viper.AddConfigPath(configPath) - viper.SetConfigName("simple") - viper.SetConfigType("toml") - err := viper.ReadInConfig() - if err != nil { - t.Error(err) - } - - var vc config.ViperConfig - viper.Unmarshal(&vc) - cfg, _ := vc.Translate() - - findings, err := FromFiles(tt.source, cfg, tt.opts) - if err != nil { - t.Error(err) - } - - assert.ElementsMatch(t, tt.expectedFindings, findings) - } -} diff --git a/detect/git.go b/detect/git.go deleted file mode 100644 index 69ae0840..00000000 --- a/detect/git.go +++ /dev/null @@ -1,95 +0,0 @@ -package detect - -import ( - "strings" - "sync" - "time" - - "github.com/gitleaks/go-gitdiff/gitdiff" - "github.com/rs/zerolog/log" - "github.com/zricethezav/gitleaks/v8/config" - "github.com/zricethezav/gitleaks/v8/report" -) - -// FromGit accepts a gitdiff.File channel (structure output from `git log -p`) and a configuration -// struct. Files from the gitdiff.File channel are then checked against each rule in the configuration to -// check for secrets. If any secrets are found, they are added to the list of findings. -func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Options) []report.Finding { - var findings []report.Finding - mu := sync.Mutex{} - wg := sync.WaitGroup{} - concurrentGoroutines := make(chan struct{}, MAXGOROUTINES) - commitMap := make(map[string]bool) - for f := range files { - // keep track of commits for logging - if f.PatchHeader != nil { - commitMap[f.PatchHeader.SHA] = true - } - wg.Add(1) - concurrentGoroutines <- struct{}{} - go func(f *gitdiff.File) { - defer func() { - wg.Done() - <-concurrentGoroutines - }() - if f.IsBinary { - return - } - - if f.IsDelete { - return - } - - commitSHA := "" - - // Check if commit is allowed - if f.PatchHeader != nil { - commitSHA = f.PatchHeader.SHA - if cfg.Allowlist.CommitAllowed(f.PatchHeader.SHA) { - return - } - } - - for _, tf := range f.TextFragments { - if f.TextFragments == nil { - // TODO fix this in gitleaks gitdiff fork - // https://github.com/gitleaks/gitleaks/issues/11 - continue - } - - for _, fi := range DetectFindings(cfg, []byte(tf.Raw(gitdiff.OpAdd)), f.NewName, commitSHA) { - // don't add to start/end lines if finding is from a file only rule - if !strings.HasPrefix(fi.Match, "file detected") { - fi.StartLine += int(tf.NewPosition) - fi.EndLine += int(tf.NewPosition) - } - if f.PatchHeader != nil { - fi.Commit = f.PatchHeader.SHA - fi.Message = f.PatchHeader.Message() - if f.PatchHeader.Author != nil { - fi.Author = f.PatchHeader.Author.Name - fi.Email = f.PatchHeader.Author.Email - } - fi.Date = f.PatchHeader.AuthorDate.UTC().Format(time.RFC3339) - } - - if outputOptions.Redact { - fi.Redact() - } - - if outputOptions.Verbose { - printFinding(fi) - } - mu.Lock() - findings = append(findings, fi) - mu.Unlock() - - } - } - }(f) - } - - wg.Wait() - log.Debug().Msgf("%d commits scanned. Note: this number might be smaller than expected due to commits with no additions", len(commitMap)) - return findings -} diff --git a/git/git.go b/detect/git/git.go similarity index 100% rename from git/git.go rename to detect/git/git.go diff --git a/detect/git_test.go b/detect/git_test.go deleted file mode 100644 index 6f191ac9..00000000 --- a/detect/git_test.go +++ /dev/null @@ -1,160 +0,0 @@ -package detect - -import ( - "fmt" - "os" - "path/filepath" - "testing" - - "github.com/spf13/viper" - "github.com/stretchr/testify/assert" - - "github.com/zricethezav/gitleaks/v8/config" - "github.com/zricethezav/gitleaks/v8/git" - "github.com/zricethezav/gitleaks/v8/report" -) - -const repoBasePath = "../testdata/repos/" -const expectPath = "../testdata/expected/" -const configPath = "../testdata/config/" - -// TestFromGit tests the FromGit function -func TestFromGit(t *testing.T) { - tests := []struct { - cfgName string - opts Options - source string - logOpts string - expected string - expectedFindings []report.Finding - }{ - { - source: filepath.Join(repoBasePath, "small"), - expected: filepath.Join(expectPath, "git", "small.txt"), - cfgName: "simple", - expectedFindings: []report.Finding{ - { - Description: "AWS Access Key", - StartLine: 20, - EndLine: 20, - StartColumn: 19, - EndColumn: 38, - Secret: "AKIALALEMEL33243OLIA", - Match: "AKIALALEMEL33243OLIA", - File: "main.go", - Date: "2021-11-02T23:37:53Z", - Commit: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587", - Author: "Zachary Rice", - Email: "zricer@protonmail.com", - Message: "Accidentally add a secret", - RuleID: "aws-access-key", - Tags: []string{"key", "AWS"}, - }, - { - Description: "AWS Access Key", - StartLine: 9, - EndLine: 9, - StartColumn: 17, - EndColumn: 36, - Secret: "AKIALALEMEL33243OLIA", - Match: "AKIALALEMEL33243OLIA", - File: "foo/foo.go", - Date: "2021-11-02T23:48:06Z", - Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca", - Author: "Zach Rice", - Email: "zricer@protonmail.com", - Message: "adding foo package with secret", - RuleID: "aws-access-key", - Tags: []string{"key", "AWS"}, - }, - }, - }, - { - source: filepath.Join(repoBasePath, "small"), - expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"), - logOpts: "--all foo...", - cfgName: "simple", - expectedFindings: []report.Finding{ - { - Description: "AWS Access Key", - StartLine: 9, - EndLine: 9, - StartColumn: 17, - EndColumn: 36, - Secret: "AKIALALEMEL33243OLIA", - Match: "AKIALALEMEL33243OLIA", - Date: "2021-11-02T23:48:06Z", - File: "foo/foo.go", - Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca", - Author: "Zach Rice", - Email: "zricer@protonmail.com", - Message: "adding foo package with secret", - RuleID: "aws-access-key", - Tags: []string{"key", "AWS"}, - }, - }, - }, - } - - err := moveDotGit("dotGit", ".git") - if err != nil { - t.Fatal(err) - } - defer moveDotGit(".git", "dotGit") - - for _, tt := range tests { - files, err := git.GitLog(tt.source, tt.logOpts) - if err != nil { - t.Error(err) - } - - viper.AddConfigPath(configPath) - viper.SetConfigName("simple") - viper.SetConfigType("toml") - err = viper.ReadInConfig() - if err != nil { - t.Error(err) - } - - var vc config.ViperConfig - viper.Unmarshal(&vc) - cfg, _ := vc.Translate() - - findings := FromGit(files, cfg, tt.opts) - for _, f := range findings { - f.Match = "" // remove lines cause copying and pasting them has some wack formatting - } - assert.ElementsMatch(t, tt.expectedFindings, findings) - } -} - -func moveDotGit(from, to string) error { - repoDirs, err := os.ReadDir("../testdata/repos") - if err != nil { - return err - } - for _, dir := range repoDirs { - if to == ".git" { - _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit")) - if os.IsNotExist(err) { - // dont want to delete the only copy of .git accidentally - continue - } - os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git")) - } - if !dir.IsDir() { - continue - } - _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from)) - if os.IsNotExist(err) { - continue - } - - err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from), - fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to)) - if err != nil { - return err - } - } - return nil -} diff --git a/detect/location.go b/detect/location.go index 2bd5754f..2ebdf6e2 100644 --- a/detect/location.go +++ b/detect/location.go @@ -10,7 +10,7 @@ type Location struct { endLineIndex int } -func getLocation(linePairs [][]int, start int, end int) Location { +func location(fragment Fragment, matchIndex []int) Location { var ( prevNewLine int location Location @@ -18,7 +18,10 @@ func getLocation(linePairs [][]int, start int, end int) Location { _lineNum int ) - for lineNum, pair := range linePairs { + start := matchIndex[0] + end := matchIndex[1] + + for lineNum, pair := range fragment.newlineIndices { _lineNum = lineNum newLineByteIndex := pair[0] if prevNewLine <= start && start < newLineByteIndex { diff --git a/git/git_test.go b/git/git_test.go deleted file mode 100644 index feb2399b..00000000 --- a/git/git_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package git_test - -import ( - "fmt" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/gitleaks/go-gitdiff/gitdiff" - "github.com/zricethezav/gitleaks/v8/git" -) - -const repoBasePath = "../testdata/repos/" -const expectPath = "../testdata/expected/" - -func TestGitLog(t *testing.T) { - tests := []struct { - source string - logOpts string - expected string - }{ - { - source: filepath.Join(repoBasePath, "small"), - expected: filepath.Join(expectPath, "git", "small.txt"), - }, - { - source: filepath.Join(repoBasePath, "small"), - expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"), - logOpts: "--all foo...", - }, - } - - err := moveDotGit("dotGit", ".git") - if err != nil { - t.Fatal(err) - } - defer moveDotGit(".git", "dotGit") - - for _, tt := range tests { - files, err := git.GitLog(tt.source, tt.logOpts) - if err != nil { - t.Error(err) - } - - var diffSb strings.Builder - for f := range files { - for _, tf := range f.TextFragments { - diffSb.WriteString(tf.Raw(gitdiff.OpAdd)) - } - } - - expectedBytes, err := os.ReadFile(tt.expected) - if err != nil { - t.Error(err) - } - expected := string(expectedBytes) - if expected != diffSb.String() { - // write string builder to .got file using os.Create - err = os.WriteFile(strings.Replace(tt.expected, ".txt", ".got.txt", 1), []byte(diffSb.String()), 0644) - if err != nil { - t.Error(err) - } - t.Error("expected: ", expected, "got: ", diffSb.String()) - } - } -} - -func TestGitDiff(t *testing.T) { - tests := []struct { - source string - expected string - additions string - target string - }{ - { - source: filepath.Join(repoBasePath, "small"), - expected: "this line is added\nand another one", - additions: "this line is added\nand another one", - target: filepath.Join(repoBasePath, "small", "main.go"), - }, - } - - err := moveDotGit("dotGit", ".git") - if err != nil { - t.Fatal(err) - } - defer moveDotGit(".git", "dotGit") - - for _, tt := range tests { - noChanges, err := os.ReadFile(tt.target) - if err != nil { - t.Error(err) - } - err = os.WriteFile(tt.target, []byte(tt.additions), 0644) - if err != nil { - restore(tt.target, noChanges, t) - t.Error(err) - } - - files, err := git.GitDiff(tt.source, false) - if err != nil { - restore(tt.target, noChanges, t) - t.Error(err) - } - - for f := range files { - sb := strings.Builder{} - for _, tf := range f.TextFragments { - sb.WriteString(tf.Raw(gitdiff.OpAdd)) - } - if sb.String() != tt.expected { - restore(tt.target, noChanges, t) - t.Error("expected: ", tt.expected, "got: ", sb.String()) - } - } - restore(tt.target, noChanges, t) - } -} - -func restore(path string, data []byte, t *testing.T) { - err := os.WriteFile(path, data, 0644) - if err != nil { - t.Fatal(err) - } -} - -func moveDotGit(from, to string) error { - repoDirs, err := os.ReadDir("../testdata/repos") - if err != nil { - return err - } - for _, dir := range repoDirs { - if to == ".git" { - _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit")) - if os.IsNotExist(err) { - // dont want to delete the only copy of .git accidentally - continue - } - os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git")) - } - if !dir.IsDir() { - continue - } - _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from)) - if os.IsNotExist(err) { - continue - } - - err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from), - fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to)) - if err != nil { - return err - } - } - return nil -} diff --git a/go.mod b/go.mod index 72f6f30d..4e0dd2cc 100644 --- a/go.mod +++ b/go.mod @@ -13,6 +13,7 @@ require ( require ( github.com/davecgh/go-spew v1.1.1 // indirect + github.com/fatih/semgroup v1.2.0 // indirect github.com/fsnotify/fsnotify v1.4.9 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect diff --git a/go.sum b/go.sum index b50fd90b..61db2106 100644 --- a/go.sum +++ b/go.sum @@ -67,6 +67,8 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.m github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/semgroup v1.2.0 h1:h/OLXwEM+3NNyAdZEpMiH1OzfplU09i2qXPVThGZvyg= +github.com/fatih/semgroup v1.2.0/go.mod h1:1KAD4iIYfXjE4U13B48VM4z9QUwV5Tt8O4rS879kgm8= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=