mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-28 20:24:22 +01:00
Archive support (#1872)
* Start Files Source
* Keep cmd the same for now
* Get tests to pass
* s.MaxTargetMegaBytes -> s.MaxFileSize
* Tweak some log messages & use q semgroup for files
* Just call yield inside the semgroup
* Refactor a check and revert some log lines
* Move mg && misc tuning
* Add `make profile`
(Benchmark results are only added if tools are installed)
Example output:
```
========================================================================
generating profile data
------------------------------------------------------------------------
- mode: dir
benchmark:
tool: hyperfine
path: profile/1748019612/dir/benchmark.json
results:
mean: 1.12852930166
stddev: 0.12163775966037399
median: 1.07242928416
user: 3.9699382799999996
system: 0.04382341999999999
min: 1.03207673016
max: 1.3913475181600001
profile:
- mode: cpu
path: profile/1748019612/dir/cpu.pprof
view: go tool pprof -http=localhost: ./gitleaks profile/1748019612/dir/cpu.pprof
- mode: mem
path: profile/1748019612/dir/mem.pprof
view: go tool pprof -http=localhost: ./gitleaks profile/1748019612/dir/mem.pprof
- mode: trace
path: profile/1748019612/dir/trace.out
view: go tool trace profile/1748019612/dir/trace.out
- mode: git
...snip...
```
* Archive support for File based sources
* Move Git to Source interface
* Scan archives in git
* Misc linter fixes
* Exclude certain diffs: --diff-filter=tuxdb
* Add git archives tests
* Log error instead of fatal
* Fix spacing in test config
* Refine source comments/wording
* Make MB conversions more readable
* Format cmd
* Adjust DetectSource logging
* MiB -> MB in logs
* Add testdata/repos/archives/dotGit/refs/.gitkeep
Without it the refs folder gets deleted and the
and then it isn't detected as a git repo ¯\_(ツ)_/¯
So then the test starts scanning the whole gitleaks
repo instead :D
* Handle finding links for archives
* Working on archive depth
* Fixes from failfast test
* cmd max-archive-depth
* added comments, fixed warnings
* removed test print
* Update README.md
* Set archive depth for DetectFiles
* Tweak logs & pass max archive for readers
* Pass ctx to Fragments
* Add make lint target and address some issues
* Fix compat issue
* Report path in fragment errors
* Apply PR suggestions & misc changes
- Update blobReader.Close() to discard the buffer
- Misc logger issues & uses
- Tweak .golangci.yaml to default to none
- Discard remaining blobReader data on close
- Undo a De Morgan's Law suggestion (and disable QF1001)
* Add http mode for diagnostics
gitleaks --diagnostics=http ...
-----
From the net/http/pprof docs:
Use the pprof tool to look at the heap profile:
```
go tool pprof http://localhost:6060/debug/pprof/heap
```
Or to look at a 30-second CPU profile:
```
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
```
Or to look at the goroutine blocking profile, after calling runtime.SetBlockProfileRate in your program:
```
go tool pprof http://localhost:6060/debug/pprof/block
```
Or to look at the holders of contended mutexes, after calling runtime.SetMutexProfileFraction in your program:
```
go tool pprof http://localhost:6060/debug/pprof/mutex
```
(For more info see https://pkg.go.dev/net/http/pprof)
---------
Co-authored-by: Alex Layne <alayne@redhat.com>
This commit is contained in:
1 parent
489d13c14e
commit
782f310478
77 files changed
+2975
-777
No files matched your search
+301
-2
@@ -2,15 +2,24 @@ package sources
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/semgroup"
|
||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/scm"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
@@ -21,6 +30,33 @@ type GitCmd struct {
|
||||
cmd *exec.Cmd
|
||||
diffFilesCh <-chan *gitdiff.File
|
||||
errCh <-chan error
|
||||
repoPath string
|
||||
}
|
||||
|
||||
// blobReader provides a ReadCloser interface git cat-file blob to fetch
|
||||
// a blob from a repo
|
||||
type blobReader struct {
|
||||
io.ReadCloser
|
||||
cmd *exec.Cmd
|
||||
}
|
||||
|
||||
// Close closes the underlying reader and then waits for the command to complete,
|
||||
// releasing its resources.
|
||||
func (br *blobReader) Close() error {
|
||||
// Discard the remaining data from the pipe to avoid blocking
|
||||
_, drainErr := io.Copy(io.Discard, br)
|
||||
// Close the pipe (should signal the command to stop if it hasn't already)
|
||||
closeErr := br.ReadCloser.Close()
|
||||
// Wait to prevent zombie processes.
|
||||
waitErr := br.cmd.Wait()
|
||||
// Return the first error encountered
|
||||
if drainErr != nil {
|
||||
return drainErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
return waitErr
|
||||
}
|
||||
|
||||
// NewGitLogCmd returns `*DiffFilesCmd` with two channels: `<-chan *gitdiff.File` and `<-chan error`.
|
||||
@@ -49,7 +85,7 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
|
||||
cmd = exec.Command("git", args...)
|
||||
} else {
|
||||
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0",
|
||||
"--full-history", "--all")
|
||||
"--full-history", "--all", "--diff-filter=tuxdb")
|
||||
}
|
||||
|
||||
logging.Debug().Msgf("executing: %s", cmd.String())
|
||||
@@ -78,6 +114,7 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
|
||||
cmd: cmd,
|
||||
diffFilesCh: gitdiffFiles,
|
||||
errCh: errCh,
|
||||
repoPath: sourceClean,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -118,6 +155,7 @@ func NewGitDiffCmd(source string, staged bool) (*GitCmd, error) {
|
||||
cmd: cmd,
|
||||
diffFilesCh: gitdiffFiles,
|
||||
errCh: errCh,
|
||||
repoPath: sourceClean,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -135,10 +173,31 @@ func (c *GitCmd) ErrCh() <-chan error {
|
||||
// stdin or copying from stdout or stderr to complete.
|
||||
//
|
||||
// Wait also closes underlying stdout and stderr.
|
||||
func (c *GitCmd) Wait() (err error) {
|
||||
func (c *GitCmd) Wait() error {
|
||||
return c.cmd.Wait()
|
||||
}
|
||||
|
||||
// NewBlobReader returns an io.ReadCloser that can be used to read a blob
|
||||
// within the git repo used to create the GitCmd.
|
||||
//
|
||||
// The caller is responsible for closing the reader.
|
||||
func (c *GitCmd) NewBlobReader(commit, path string) (io.ReadCloser, error) {
|
||||
gitArgs := []string{"-C", c.repoPath, "cat-file", "blob", commit + ":" + path}
|
||||
cmd := exec.Command("git", gitArgs...)
|
||||
cmd.Stderr = io.Discard
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get stdout pipe: %w", err)
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, fmt.Errorf("failed to start git command: %w", err)
|
||||
}
|
||||
return &blobReader{
|
||||
ReadCloser: stdout,
|
||||
cmd: cmd,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// listenForStdErr listens for stderr output from git, prints it to stdout,
|
||||
// sends to errCh and closes it.
|
||||
func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
|
||||
@@ -187,3 +246,243 @@ func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// RemoteInfo provides the info needed for reconstructing links from findings
|
||||
type RemoteInfo struct {
|
||||
Platform scm.Platform
|
||||
Url string
|
||||
}
|
||||
|
||||
// Git is a source for yielding fragments from a git repo
|
||||
type Git struct {
|
||||
Cmd *GitCmd
|
||||
Config *config.Config
|
||||
Remote *RemoteInfo
|
||||
Sema *semgroup.Group
|
||||
MaxArchiveDepth int
|
||||
}
|
||||
|
||||
// CommitInfo captures metadata about the commit
|
||||
type CommitInfo struct {
|
||||
AuthorEmail string
|
||||
AuthorName string
|
||||
Date string
|
||||
Message string
|
||||
Remote *RemoteInfo
|
||||
SHA string
|
||||
}
|
||||
|
||||
// Fragments yields fragments from a git repo
|
||||
func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
||||
defer func() {
|
||||
_ = s.Cmd.Wait()
|
||||
}()
|
||||
|
||||
var (
|
||||
diffFilesCh = s.Cmd.DiffFilesCh()
|
||||
errCh = s.Cmd.ErrCh()
|
||||
wg sync.WaitGroup
|
||||
)
|
||||
|
||||
// loop to range over both DiffFiles (stdout) and ErrCh (stderr)
|
||||
for diffFilesCh != nil || errCh != nil {
|
||||
select {
|
||||
case gitdiffFile, open := <-diffFilesCh:
|
||||
if !open {
|
||||
diffFilesCh = nil
|
||||
break
|
||||
}
|
||||
|
||||
if gitdiffFile.IsDelete {
|
||||
continue
|
||||
}
|
||||
|
||||
// skip non-archive binary files
|
||||
yieldAsArchive := false
|
||||
if gitdiffFile.IsBinary {
|
||||
if !isArchive(ctx, gitdiffFile.NewName) {
|
||||
continue
|
||||
}
|
||||
yieldAsArchive = true
|
||||
}
|
||||
|
||||
// Check if commit is allowed
|
||||
commitSHA := ""
|
||||
var commitInfo *CommitInfo
|
||||
if gitdiffFile.PatchHeader != nil {
|
||||
commitSHA = gitdiffFile.PatchHeader.SHA
|
||||
for _, a := range s.Config.Allowlists {
|
||||
if ok, c := a.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
|
||||
logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
commitInfo = &CommitInfo{
|
||||
Date: gitdiffFile.PatchHeader.AuthorDate.UTC().Format(time.RFC3339),
|
||||
Message: gitdiffFile.PatchHeader.Message(),
|
||||
Remote: s.Remote,
|
||||
SHA: commitSHA,
|
||||
}
|
||||
|
||||
if gitdiffFile.PatchHeader.Author != nil {
|
||||
commitInfo.AuthorName = gitdiffFile.PatchHeader.Author.Name
|
||||
commitInfo.AuthorEmail = gitdiffFile.PatchHeader.Author.Email
|
||||
}
|
||||
}
|
||||
|
||||
wg.Add(1)
|
||||
s.Sema.Go(func() error {
|
||||
defer wg.Done()
|
||||
|
||||
if yieldAsArchive {
|
||||
blob, err := s.Cmd.NewBlobReader(commitSHA, gitdiffFile.NewName)
|
||||
if err != nil {
|
||||
logging.Error().Err(err).Msg("could not read archive blob")
|
||||
return nil
|
||||
}
|
||||
|
||||
file := File{
|
||||
Content: blob,
|
||||
Path: gitdiffFile.NewName,
|
||||
MaxArchiveDepth: s.MaxArchiveDepth,
|
||||
Config: s.Config,
|
||||
}
|
||||
|
||||
// enrich and yield fragments
|
||||
err = file.Fragments(ctx, func(fragment Fragment, err error) error {
|
||||
fragment.CommitSHA = commitSHA
|
||||
fragment.CommitInfo = commitInfo
|
||||
return yield(fragment, err)
|
||||
})
|
||||
|
||||
// Close the blob reader and log any issues
|
||||
if err := blob.Close(); err != nil {
|
||||
logging.Debug().Err(err).Msg("blobReader.Close() returned an error")
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
for _, textFragment := range gitdiffFile.TextFragments {
|
||||
if textFragment == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
fragment := Fragment{
|
||||
CommitSHA: commitSHA,
|
||||
FilePath: gitdiffFile.NewName,
|
||||
Raw: textFragment.Raw(gitdiff.OpAdd),
|
||||
StartLine: int(textFragment.NewPosition),
|
||||
CommitInfo: commitInfo,
|
||||
}
|
||||
|
||||
if err := yield(fragment, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
case err, open := <-errCh:
|
||||
if !open {
|
||||
errCh = nil
|
||||
break
|
||||
}
|
||||
|
||||
return yield(Fragment{}, err)
|
||||
}
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewRemoteInfo builds a new RemoteInfo for generating finding links
|
||||
func NewRemoteInfo(platform scm.Platform, source string) *RemoteInfo {
|
||||
if platform == scm.NoPlatform {
|
||||
return &RemoteInfo{Platform: platform}
|
||||
}
|
||||
|
||||
remoteUrl, err := getRemoteUrl(source)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "No remote configured") {
|
||||
logging.Debug().Msg("skipping finding links: repository has no configured remote.")
|
||||
platform = scm.NoPlatform
|
||||
} else {
|
||||
logging.Error().Err(err).Msg("skipping finding links: unable to parse remote URL")
|
||||
}
|
||||
goto End
|
||||
}
|
||||
|
||||
if platform == scm.UnknownPlatform {
|
||||
platform = platformFromHost(remoteUrl)
|
||||
if platform == scm.UnknownPlatform {
|
||||
logging.Info().
|
||||
Str("host", remoteUrl.Hostname()).
|
||||
Msg("Unknown SCM platform. Use --platform to include links in findings.")
|
||||
} else {
|
||||
logging.Debug().
|
||||
Str("host", remoteUrl.Hostname()).
|
||||
Str("platform", platform.String()).
|
||||
Msg("SCM platform parsed from host")
|
||||
}
|
||||
}
|
||||
|
||||
End:
|
||||
var rUrl string
|
||||
if remoteUrl != nil {
|
||||
rUrl = remoteUrl.String()
|
||||
}
|
||||
return &RemoteInfo{
|
||||
Platform: platform,
|
||||
Url: rUrl,
|
||||
}
|
||||
}
|
||||
|
||||
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):([\w/.-]+?)(?:\.git)?$`)
|
||||
|
||||
func getRemoteUrl(source string) (*url.URL, error) {
|
||||
// This will return the first remote — typically, "origin".
|
||||
cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
|
||||
if source != "." {
|
||||
cmd.Dir = source
|
||||
}
|
||||
|
||||
stdout, err := cmd.Output()
|
||||
if err != nil {
|
||||
var exitError *exec.ExitError
|
||||
if errors.As(err, &exitError) {
|
||||
return nil, fmt.Errorf("command failed (%d): %w, stderr: %s", exitError.ExitCode(), err, string(bytes.TrimSpace(exitError.Stderr)))
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
remoteUrl := string(bytes.TrimSpace(stdout))
|
||||
if matches := sshUrlpat.FindStringSubmatch(remoteUrl); matches != nil {
|
||||
remoteUrl = fmt.Sprintf("https://%s/%s", matches[1], matches[2])
|
||||
}
|
||||
remoteUrl = strings.TrimSuffix(remoteUrl, ".git")
|
||||
|
||||
parsedUrl, err := url.Parse(remoteUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to parse remote URL: %w", err)
|
||||
}
|
||||
|
||||
// Remove any user info.
|
||||
parsedUrl.User = nil
|
||||
return parsedUrl, nil
|
||||
}
|
||||
|
||||
func platformFromHost(u *url.URL) scm.Platform {
|
||||
switch strings.ToLower(u.Hostname()) {
|
||||
case "github.com":
|
||||
return scm.GitHubPlatform
|
||||
case "gitlab.com":
|
||||
return scm.GitLabPlatform
|
||||
case "dev.azure.com", "visualstudio.com":
|
||||
return scm.AzureDevOpsPlatform
|
||||
default:
|
||||
return scm.UnknownPlatform
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user