mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-30 13:14:22 +01:00
Respect contexts with timeouts (#1948)
rh-pre-commit.version: 2.3.2 rh-pre-commit.check-secrets: ENABLED
This commit is contained in:
1 parent
3821f30b06
commit
c5ccbb9468
12 files changed
+153
-48
No files matched your search
@@ -142,10 +142,13 @@ Detect hardcoded secrets................................................Skipped
|
|||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```
|
```
|
||||||
|
Gitleaks scans code, past or present, for secrets
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
gitleaks [command]
|
gitleaks [command]
|
||||||
|
|
||||||
Available Commands:
|
Available Commands:
|
||||||
|
completion Generate the autocompletion script for the specified shell
|
||||||
dir scan directories or files for secrets
|
dir scan directories or files for secrets
|
||||||
git scan git repositories for secrets
|
git scan git repositories for secrets
|
||||||
help Help about any command
|
help Help about any command
|
||||||
@@ -161,16 +164,16 @@ Flags:
|
|||||||
3. env var GITLEAKS_CONFIG_TOML with the file content
|
3. env var GITLEAKS_CONFIG_TOML with the file content
|
||||||
4. (target path)/.gitleaks.toml
|
4. (target path)/.gitleaks.toml
|
||||||
If none of the four options are used, then gitleaks will use the default config
|
If none of the four options are used, then gitleaks will use the default config
|
||||||
--diagnostics string enable diagnostics (comma-separated list: cpu,mem,trace). cpu=CPU profiling, mem=memory profiling, trace=execution tracing
|
--diagnostics string enable diagnostics (http OR comma-separated list: cpu,mem,trace). cpu=CPU prof, mem=memory prof, trace=exec tracing, http=serve via net/http/pprof
|
||||||
--diagnostics-dir string directory to store diagnostics output files (defaults to current directory)
|
--diagnostics-dir string directory to store diagnostics output files when not using http mode (defaults to current directory)
|
||||||
--enable-rule strings only enable specific rules by id
|
--enable-rule strings only enable specific rules by id
|
||||||
--exit-code int exit code when leaks have been encountered (default 1)
|
--exit-code int exit code when leaks have been encountered (default 1)
|
||||||
-i, --gitleaks-ignore-path string path to .gitleaksignore file or folder containing one (default ".")
|
-i, --gitleaks-ignore-path string path to .gitleaksignore file or folder containing one (default ".")
|
||||||
-h, --help help for gitleaks
|
-h, --help help for gitleaks
|
||||||
--ignore-gitleaks-allow ignore gitleaks:allow comments
|
--ignore-gitleaks-allow ignore gitleaks:allow comments
|
||||||
-l, --log-level string log level (trace, debug, info, warn, error, fatal) (default "info")
|
-l, --log-level string log level (trace, debug, info, warn, error, fatal) (default "info")
|
||||||
--max-decode-depth int allow recursive decoding up to this depth (default "0", no decoding is done)
|
|
||||||
--max-archive-depth int allow scanning into nested archives up to this depth (default "0", no archive traversal is done)
|
--max-archive-depth int allow scanning into nested archives up to this depth (default "0", no archive traversal is done)
|
||||||
|
--max-decode-depth int allow recursive decoding up to this depth (default "0", no decoding is done)
|
||||||
--max-target-megabytes int files larger than this will be skipped
|
--max-target-megabytes int files larger than this will be skipped
|
||||||
--no-banner suppress banner
|
--no-banner suppress banner
|
||||||
--no-color turn off color for verbose output
|
--no-color turn off color for verbose output
|
||||||
@@ -178,6 +181,7 @@ Flags:
|
|||||||
-f, --report-format string output format (json, csv, junit, sarif, template)
|
-f, --report-format string output format (json, csv, junit, sarif, template)
|
||||||
-r, --report-path string report file
|
-r, --report-path string report file
|
||||||
--report-template string template file used to generate the report (implies --report-format=template)
|
--report-template string template file used to generate the report (implies --report-format=template)
|
||||||
|
--timeout int set a timeout for gitleaks commands in seconds (default "0", no timeout is set)
|
||||||
-v, --verbose show verbose output from scan
|
-v, --verbose show verbose output from scan
|
||||||
--version version for gitleaks
|
--version version for gitleaks
|
||||||
|
|
||||||
|
|||||||
+5
-8
@@ -19,7 +19,6 @@
|
|||||||
package cmd
|
package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -66,18 +65,16 @@ func runDetect(cmd *cobra.Command, args []string) {
|
|||||||
exitCode := mustGetIntFlag(cmd, "exit-code")
|
exitCode := mustGetIntFlag(cmd, "exit-code")
|
||||||
noGit := mustGetBoolFlag(cmd, "no-git")
|
noGit := mustGetBoolFlag(cmd, "no-git")
|
||||||
fromPipe := mustGetBoolFlag(cmd, "pipe")
|
fromPipe := mustGetBoolFlag(cmd, "pipe")
|
||||||
|
|
||||||
// determine what type of scan:
|
// determine what type of scan:
|
||||||
// - git: scan the history of the repo
|
// - git: scan the history of the repo
|
||||||
// - no-git: scan files by treating the repo as a plain directory
|
// - no-git: scan files by treating the repo as a plain directory
|
||||||
var (
|
var (
|
||||||
err error
|
err error
|
||||||
findings []report.Finding
|
findings []report.Finding
|
||||||
ctx = context.Background()
|
|
||||||
)
|
)
|
||||||
if noGit {
|
if noGit {
|
||||||
findings, err = detector.DetectSource(
|
findings, err = detector.DetectSource(
|
||||||
ctx, &sources.Files{
|
cmd.Context(), &sources.Files{
|
||||||
Config: &cfg,
|
Config: &cfg,
|
||||||
FollowSymlinks: detector.FollowSymlinks,
|
FollowSymlinks: detector.FollowSymlinks,
|
||||||
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
|
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
|
||||||
@@ -93,7 +90,7 @@ func runDetect(cmd *cobra.Command, args []string) {
|
|||||||
}
|
}
|
||||||
} else if fromPipe {
|
} else if fromPipe {
|
||||||
findings, err = detector.DetectSource(
|
findings, err = detector.DetectSource(
|
||||||
ctx, &sources.File{
|
cmd.Context(), &sources.File{
|
||||||
Content: os.Stdin,
|
Content: os.Stdin,
|
||||||
MaxArchiveDepth: detector.MaxArchiveDepth,
|
MaxArchiveDepth: detector.MaxArchiveDepth,
|
||||||
},
|
},
|
||||||
@@ -111,7 +108,7 @@ func runDetect(cmd *cobra.Command, args []string) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
logOpts := mustGetStringFlag(cmd, "log-opts")
|
logOpts := mustGetStringFlag(cmd, "log-opts")
|
||||||
if gitCmd, err = sources.NewGitLogCmd(sourcePath, logOpts); err != nil {
|
if gitCmd, err = sources.NewGitLogCmdContext(cmd.Context(), sourcePath, logOpts); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("could not create Git cmd")
|
logging.Fatal().Err(err).Msg("could not create Git cmd")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,10 +117,10 @@ func runDetect(cmd *cobra.Command, args []string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
findings, err = detector.DetectSource(
|
findings, err = detector.DetectSource(
|
||||||
ctx, &sources.Git{
|
cmd.Context(), &sources.Git{
|
||||||
Cmd: gitCmd,
|
Cmd: gitCmd,
|
||||||
Config: &detector.Config,
|
Config: &detector.Config,
|
||||||
Remote: sources.NewRemoteInfo(scmPlatform, sourcePath),
|
Remote: sources.NewRemoteInfoContext(cmd.Context(), scmPlatform, sourcePath),
|
||||||
Sema: detector.Sema,
|
Sema: detector.Sema,
|
||||||
MaxArchiveDepth: detector.MaxArchiveDepth,
|
MaxArchiveDepth: detector.MaxArchiveDepth,
|
||||||
},
|
},
|
||||||
|
|||||||
+1
-2
@@ -1,7 +1,6 @@
|
|||||||
package cmd
|
package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
@@ -56,7 +55,7 @@ func runDirectory(cmd *cobra.Command, args []string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
findings, err := detector.DetectSource(
|
findings, err := detector.DetectSource(
|
||||||
context.Background(),
|
cmd.Context(),
|
||||||
&sources.Files{
|
&sources.Files{
|
||||||
Config: &cfg,
|
Config: &cfg,
|
||||||
FollowSymlinks: detector.FollowSymlinks,
|
FollowSymlinks: detector.FollowSymlinks,
|
||||||
|
|||||||
+4
-5
@@ -1,7 +1,6 @@
|
|||||||
package cmd
|
package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
@@ -63,13 +62,13 @@ func runGit(cmd *cobra.Command, args []string) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
if preCommit || staged {
|
if preCommit || staged {
|
||||||
if gitCmd, err = sources.NewGitDiffCmd(source, staged); err != nil {
|
if gitCmd, err = sources.NewGitDiffCmdContext(cmd.Context(), source, staged); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
|
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
|
||||||
}
|
}
|
||||||
// Remote info + links are irrelevant for staged changes.
|
// Remote info + links are irrelevant for staged changes.
|
||||||
scmPlatform = scm.NoPlatform
|
scmPlatform = scm.NoPlatform
|
||||||
} else {
|
} else {
|
||||||
if gitCmd, err = sources.NewGitLogCmd(source, logOpts); err != nil {
|
if gitCmd, err = sources.NewGitLogCmdContext(cmd.Context(), source, logOpts); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("could not create Git log cmd")
|
logging.Fatal().Err(err).Msg("could not create Git log cmd")
|
||||||
}
|
}
|
||||||
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
|
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
|
||||||
@@ -78,11 +77,11 @@ func runGit(cmd *cobra.Command, args []string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
findings, err = detector.DetectSource(
|
findings, err = detector.DetectSource(
|
||||||
context.Background(),
|
cmd.Context(),
|
||||||
&sources.Git{
|
&sources.Git{
|
||||||
Cmd: gitCmd,
|
Cmd: gitCmd,
|
||||||
Config: &detector.Config,
|
Config: &detector.Config,
|
||||||
Remote: sources.NewRemoteInfo(scmPlatform, source),
|
Remote: sources.NewRemoteInfoContext(cmd.Context(), scmPlatform, source),
|
||||||
Sema: detector.Sema,
|
Sema: detector.Sema,
|
||||||
MaxArchiveDepth: detector.MaxArchiveDepth,
|
MaxArchiveDepth: detector.MaxArchiveDepth,
|
||||||
},
|
},
|
||||||
|
|||||||
+1
-1
@@ -53,7 +53,7 @@ func runProtect(cmd *cobra.Command, args []string) {
|
|||||||
remote *detect.RemoteInfo
|
remote *detect.RemoteInfo
|
||||||
)
|
)
|
||||||
|
|
||||||
if gitCmd, err = sources.NewGitDiffCmd(source, staged); err != nil {
|
if gitCmd, err = sources.NewGitDiffCmdContext(cmd.Context(), source, staged); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
|
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
|
||||||
}
|
}
|
||||||
remote = &detect.RemoteInfo{Platform: scm.NoPlatform}
|
remote = &detect.RemoteInfo{Platform: scm.NoPlatform}
|
||||||
|
|||||||
+14
-1
@@ -2,6 +2,7 @@ package cmd
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
@@ -44,6 +45,17 @@ var (
|
|||||||
Use: "gitleaks",
|
Use: "gitleaks",
|
||||||
Short: "Gitleaks scans code, past or present, for secrets",
|
Short: "Gitleaks scans code, past or present, for secrets",
|
||||||
Version: version.Version,
|
Version: version.Version,
|
||||||
|
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
// Set the timeout for all the commands
|
||||||
|
if timeout, err := cmd.Flags().GetInt("timeout"); err != nil {
|
||||||
|
return err
|
||||||
|
} else if timeout > 0 {
|
||||||
|
ctx, cancel := context.WithTimeout(cmd.Context(), time.Duration(timeout)*time.Second)
|
||||||
|
cmd.SetContext(ctx)
|
||||||
|
cobra.OnFinalize(cancel)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// diagnostics manager is global to ensure it can be started before a scan begins
|
// diagnostics manager is global to ensure it can be started before a scan begins
|
||||||
@@ -78,6 +90,7 @@ func init() {
|
|||||||
rootCmd.PersistentFlags().StringP("gitleaks-ignore-path", "i", ".", "path to .gitleaksignore file or folder containing one")
|
rootCmd.PersistentFlags().StringP("gitleaks-ignore-path", "i", ".", "path to .gitleaksignore file or folder containing one")
|
||||||
rootCmd.PersistentFlags().Int("max-decode-depth", 0, "allow recursive decoding up to this depth (default \"0\", no decoding is done)")
|
rootCmd.PersistentFlags().Int("max-decode-depth", 0, "allow recursive decoding up to this depth (default \"0\", no decoding is done)")
|
||||||
rootCmd.PersistentFlags().Int("max-archive-depth", 0, "allow scanning into nested archives up to this depth (default \"0\", no archive traversal is done)")
|
rootCmd.PersistentFlags().Int("max-archive-depth", 0, "allow scanning into nested archives up to this depth (default \"0\", no archive traversal is done)")
|
||||||
|
rootCmd.PersistentFlags().Int("timeout", 0, "set a timeout for gitleaks commands in seconds (default \"0\", no timeout is set)")
|
||||||
|
|
||||||
// Add diagnostics flags
|
// Add diagnostics flags
|
||||||
rootCmd.PersistentFlags().String("diagnostics", "", "enable diagnostics (http OR comma-separated list: cpu,mem,trace). cpu=CPU prof, mem=memory prof, trace=exec tracing, http=serve via net/http/pprof")
|
rootCmd.PersistentFlags().String("diagnostics", "", "enable diagnostics (http OR comma-separated list: cpu,mem,trace). cpu=CPU prof, mem=memory prof, trace=exec tracing, http=serve via net/http/pprof")
|
||||||
@@ -237,7 +250,7 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
|
|||||||
var err error
|
var err error
|
||||||
|
|
||||||
// Setup common detector
|
// Setup common detector
|
||||||
detector := detect.NewDetector(cfg)
|
detector := detect.NewDetectorContext(cmd.Context(), cfg)
|
||||||
|
|
||||||
if detector.MaxDecodeDepth, err = cmd.Flags().GetInt("max-decode-depth"); err != nil {
|
if detector.MaxDecodeDepth, err = cmd.Flags().GetInt("max-decode-depth"); err != nil {
|
||||||
logging.Fatal().Err(err).Send()
|
logging.Fatal().Err(err).Send()
|
||||||
|
|||||||
+1
-2
@@ -1,7 +1,6 @@
|
|||||||
package cmd
|
package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -38,7 +37,7 @@ func runStdIn(cmd *cobra.Command, _ []string) {
|
|||||||
exitCode := mustGetIntFlag(cmd, "exit-code")
|
exitCode := mustGetIntFlag(cmd, "exit-code")
|
||||||
|
|
||||||
findings, err := detector.DetectSource(
|
findings, err := detector.DetectSource(
|
||||||
context.Background(),
|
cmd.Context(),
|
||||||
&sources.File{
|
&sources.File{
|
||||||
Content: os.Stdin,
|
Content: os.Stdin,
|
||||||
MaxArchiveDepth: detector.MaxArchiveDepth,
|
MaxArchiveDepth: detector.MaxArchiveDepth,
|
||||||
|
|||||||
+28
-5
@@ -113,6 +113,12 @@ type Fragment sources.Fragment
|
|||||||
|
|
||||||
// NewDetector creates a new detector with the given config
|
// NewDetector creates a new detector with the given config
|
||||||
func NewDetector(cfg config.Config) *Detector {
|
func NewDetector(cfg config.Config) *Detector {
|
||||||
|
return NewDetectorContext(context.Background(), cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDetectorContext is the same as NewDetector but supports passing in a
|
||||||
|
// context to use for timeouts
|
||||||
|
func NewDetectorContext(ctx context.Context, cfg config.Config) *Detector {
|
||||||
return &Detector{
|
return &Detector{
|
||||||
commitMap: make(map[string]bool),
|
commitMap: make(map[string]bool),
|
||||||
gitleaksIgnore: make(map[string]struct{}),
|
gitleaksIgnore: make(map[string]struct{}),
|
||||||
@@ -121,7 +127,7 @@ func NewDetector(cfg config.Config) *Detector {
|
|||||||
findings: make([]report.Finding, 0),
|
findings: make([]report.Finding, 0),
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
prefilter: *ahocorasick.NewTrieBuilder().AddStrings(maps.Keys(cfg.Keywords)).Build(),
|
prefilter: *ahocorasick.NewTrieBuilder().AddStrings(maps.Keys(cfg.Keywords)).Build(),
|
||||||
Sema: semgroup.NewGroup(context.Background(), 40),
|
Sema: semgroup.NewGroup(ctx, 40),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -240,7 +246,7 @@ func (d *Detector) DetectSource(ctx context.Context, source sources.Source) ([]r
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, finding := range d.Detect(Fragment(fragment)) {
|
for _, finding := range d.DetectContext(ctx, Fragment(fragment)) {
|
||||||
d.AddFinding(finding)
|
d.AddFinding(finding)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,6 +268,12 @@ func (d *Detector) DetectSource(ctx context.Context, source sources.Source) ([]r
|
|||||||
|
|
||||||
// Detect scans the given fragment and returns a list of findings
|
// Detect scans the given fragment and returns a list of findings
|
||||||
func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
||||||
|
return d.DetectContext(context.Background(), fragment)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DetectContext is the same as Detect but supports passing in a
|
||||||
|
// context to use for timeouts
|
||||||
|
func (d *Detector) DetectContext(ctx context.Context, fragment Fragment) []report.Finding {
|
||||||
if fragment.Bytes == nil {
|
if fragment.Bytes == nil {
|
||||||
d.TotalBytes.Add(uint64(len(fragment.Raw)))
|
d.TotalBytes.Add(uint64(len(fragment.Raw)))
|
||||||
}
|
}
|
||||||
@@ -298,7 +310,12 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
|||||||
currentDecodeDepth := 0
|
currentDecodeDepth := 0
|
||||||
decoder := codec.NewDecoder()
|
decoder := codec.NewDecoder()
|
||||||
|
|
||||||
|
ScanLoop:
|
||||||
for {
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
break ScanLoop
|
||||||
|
default:
|
||||||
// build keyword map for prefiltering rules
|
// build keyword map for prefiltering rules
|
||||||
keywords := make(map[string]bool)
|
keywords := make(map[string]bool)
|
||||||
normalizedRaw := strings.ToLower(currentRaw)
|
normalizedRaw := strings.ToLower(currentRaw)
|
||||||
@@ -308,6 +325,10 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, rule := range d.Config.Rules {
|
for _, rule := range d.Config.Rules {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
break ScanLoop
|
||||||
|
default:
|
||||||
if len(rule.Keywords) == 0 {
|
if len(rule.Keywords) == 0 {
|
||||||
// if no keywords are associated with the rule always scan the
|
// if no keywords are associated with the rule always scan the
|
||||||
// fragment using the rule
|
// fragment using the rule
|
||||||
@@ -323,13 +344,14 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// increment the depth by 1 as we start our decoding pass
|
// increment the depth by 1 as we start our decoding pass
|
||||||
currentDecodeDepth++
|
currentDecodeDepth++
|
||||||
|
|
||||||
// stop the loop if we've hit our max decoding depth
|
// stop the loop if we've hit our max decoding depth
|
||||||
if currentDecodeDepth > d.MaxDecodeDepth {
|
if currentDecodeDepth > d.MaxDecodeDepth {
|
||||||
break
|
break ScanLoop
|
||||||
}
|
}
|
||||||
|
|
||||||
// decode the currentRaw for the next pass
|
// decode the currentRaw for the next pass
|
||||||
@@ -337,7 +359,8 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
|||||||
|
|
||||||
// stop the loop when there's nothing else to decode
|
// stop the loop when there's nothing else to decode
|
||||||
if len(encodedSegments) == 0 {
|
if len(encodedSegments) == 0 {
|
||||||
break
|
break ScanLoop
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -357,7 +380,7 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
|
|||||||
}()
|
}()
|
||||||
)
|
)
|
||||||
|
|
||||||
if r.SkipReport == true && !fragment.InheritedFromFinding {
|
if r.SkipReport && !fragment.InheritedFromFinding {
|
||||||
return findings
|
return findings
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+20
-3
@@ -1530,6 +1530,7 @@ func TestDetectWithArchives(t *testing.T) {
|
|||||||
tests := []struct {
|
tests := []struct {
|
||||||
cfgName string
|
cfgName string
|
||||||
source string
|
source string
|
||||||
|
expireContext bool
|
||||||
expectedFindings []report.Finding
|
expectedFindings []report.Finding
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
@@ -2059,6 +2060,12 @@ func TestDetectWithArchives(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
source: filepath.Join(archivesBasePath, "nested.tar.gz"),
|
||||||
|
cfgName: "archives",
|
||||||
|
expireContext: true,
|
||||||
|
expectedFindings: []report.Finding{},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
@@ -2073,13 +2080,17 @@ func TestDetectWithArchives(t *testing.T) {
|
|||||||
err = viper.Unmarshal(&vc)
|
err = viper.Unmarshal(&vc)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
if tt.expireContext {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
|
||||||
cfg, _ := vc.Translate()
|
cfg, _ := vc.Translate()
|
||||||
detector := NewDetector(cfg)
|
detector := NewDetectorContext(ctx, cfg)
|
||||||
detector.MaxArchiveDepth = 8
|
detector.MaxArchiveDepth = 8
|
||||||
|
|
||||||
findings, err := detector.DetectSource(
|
findings, err := detector.DetectSource(
|
||||||
context.Background(),
|
ctx, &sources.Files{
|
||||||
&sources.Files{
|
|
||||||
Path: tt.source,
|
Path: tt.source,
|
||||||
Sema: detector.Sema,
|
Sema: detector.Sema,
|
||||||
Config: &cfg,
|
Config: &cfg,
|
||||||
@@ -2087,7 +2098,13 @@ func TestDetectWithArchives(t *testing.T) {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if tt.expireContext {
|
||||||
|
require.EqualError(t, err, "context canceled")
|
||||||
|
} else {
|
||||||
|
cancel()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: Temporary mitigation.
|
// TODO: Temporary mitigation.
|
||||||
// https://github.com/gitleaks/gitleaks/issues/1641
|
// https://github.com/gitleaks/gitleaks/issues/1641
|
||||||
normalizedFindings := make([]report.Finding, len(findings))
|
normalizedFindings := make([]report.Finding, len(findings))
|
||||||
|
|||||||
+10
-5
@@ -70,12 +70,12 @@ func (s *File) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
|||||||
return s.extractorFragments(ctx, extractor, s.Content, yield)
|
return s.extractorFragments(ctx, extractor, s.Content, yield)
|
||||||
}
|
}
|
||||||
if decompressor, ok := format.(archives.Decompressor); ok {
|
if decompressor, ok := format.(archives.Decompressor); ok {
|
||||||
return s.decompressorFragments(decompressor, s.Content, yield)
|
return s.decompressorFragments(ctx, decompressor, s.Content, yield)
|
||||||
}
|
}
|
||||||
logging.Warn().Str("path", s.FullPath()).Msg("skipping unknown archive type")
|
logging.Warn().Str("path", s.FullPath()).Msg("skipping unknown archive type")
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.fileFragments(bufio.NewReader(s.Content), yield)
|
return s.fileFragments(ctx, bufio.NewReader(s.Content), yield)
|
||||||
}
|
}
|
||||||
|
|
||||||
// extractorFragments recursively crawls archives and yields fragments
|
// extractorFragments recursively crawls archives and yields fragments
|
||||||
@@ -139,14 +139,14 @@ func (s *File) extractorFragments(ctx context.Context, extractor archives.Extrac
|
|||||||
}
|
}
|
||||||
|
|
||||||
// decompressorFragments recursively crawls archives and yields fragments
|
// decompressorFragments recursively crawls archives and yields fragments
|
||||||
func (s *File) decompressorFragments(decompressor archives.Decompressor, reader io.Reader, yield FragmentsFunc) error {
|
func (s *File) decompressorFragments(ctx context.Context, decompressor archives.Decompressor, reader io.Reader, yield FragmentsFunc) error {
|
||||||
innerReader, err := decompressor.OpenReader(reader)
|
innerReader, err := decompressor.OpenReader(reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Error().Str("path", s.FullPath()).Msg("could read compressed file")
|
logging.Error().Str("path", s.FullPath()).Msg("could read compressed file")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := s.fileFragments(bufio.NewReader(innerReader), yield); err != nil {
|
if err := s.fileFragments(ctx, bufio.NewReader(innerReader), yield); err != nil {
|
||||||
_ = innerReader.Close()
|
_ = innerReader.Close()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -156,7 +156,7 @@ func (s *File) decompressorFragments(decompressor archives.Decompressor, reader
|
|||||||
}
|
}
|
||||||
|
|
||||||
// fileFragments reads the file into fragments to yield
|
// fileFragments reads the file into fragments to yield
|
||||||
func (s *File) fileFragments(reader *bufio.Reader, yield FragmentsFunc) error {
|
func (s *File) fileFragments(ctx context.Context, reader *bufio.Reader, yield FragmentsFunc) error {
|
||||||
// Create a buffer if the caller hasn't provided one
|
// Create a buffer if the caller hasn't provided one
|
||||||
if s.Buffer == nil {
|
if s.Buffer == nil {
|
||||||
s.Buffer = make([]byte, defaultBufferSize)
|
s.Buffer = make([]byte, defaultBufferSize)
|
||||||
@@ -164,6 +164,10 @@ func (s *File) fileFragments(reader *bufio.Reader, yield FragmentsFunc) error {
|
|||||||
|
|
||||||
totalLines := 0
|
totalLines := 0
|
||||||
for {
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
default:
|
||||||
fragment := Fragment{
|
fragment := Fragment{
|
||||||
FilePath: s.FullPath(),
|
FilePath: s.FullPath(),
|
||||||
}
|
}
|
||||||
@@ -236,6 +240,7 @@ func (s *File) fileFragments(reader *bufio.Reader, yield FragmentsFunc) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// FullPath returns the File.Path with any preceding outer paths
|
// FullPath returns the File.Path with any preceding outer paths
|
||||||
func (s *File) FullPath() string {
|
func (s *File) FullPath() string {
|
||||||
|
|||||||
+14
-3
@@ -34,7 +34,8 @@ func DirectoryTargets(sourcePath string, s *semgroup.Group, followSymlinks bool,
|
|||||||
}
|
}
|
||||||
|
|
||||||
s.Go(func() error {
|
s.Go(func() error {
|
||||||
err := files.scanTargets(func(scanTarget ScanTarget, err error) error {
|
ctx := context.Background()
|
||||||
|
err := files.scanTargets(ctx, func(scanTarget ScanTarget, err error) error {
|
||||||
paths <- scanTarget
|
paths <- scanTarget
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -56,7 +57,7 @@ type Files struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// scanTargets yields scan targets to a callback func
|
// scanTargets yields scan targets to a callback func
|
||||||
func (s *Files) scanTargets(yield func(ScanTarget, error) error) error {
|
func (s *Files) scanTargets(ctx context.Context, yield func(ScanTarget, error) error) error {
|
||||||
return filepath.WalkDir(s.Path, func(path string, d fs.DirEntry, err error) error {
|
return filepath.WalkDir(s.Path, func(path string, d fs.DirEntry, err error) error {
|
||||||
scanTarget := ScanTarget{Path: path}
|
scanTarget := ScanTarget{Path: path}
|
||||||
logger := logging.With().Str("path", path).Logger()
|
logger := logging.With().Str("path", path).Logger()
|
||||||
@@ -141,7 +142,11 @@ func (s *Files) scanTargets(yield func(ScanTarget, error) error) error {
|
|||||||
func (s *Files) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
func (s *Files) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
|
|
||||||
err := s.scanTargets(func(scanTarget ScanTarget, err error) error {
|
err := s.scanTargets(ctx, func(scanTarget ScanTarget, err error) error {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
default:
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
s.Sema.Go(func() error {
|
s.Sema.Go(func() error {
|
||||||
logger := logging.With().Str("path", scanTarget.Path).Logger()
|
logger := logging.With().Str("path", scanTarget.Path).Logger()
|
||||||
@@ -173,8 +178,14 @@ func (s *Files) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
|||||||
})
|
})
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
default:
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
+48
-10
@@ -63,6 +63,12 @@ func (br *blobReader) Close() error {
|
|||||||
// Caller should read everything from channels until receiving a signal about their closure and call
|
// Caller should read everything from channels until receiving a signal about their closure and call
|
||||||
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
|
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
|
||||||
func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
|
func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
|
||||||
|
return NewGitLogCmdContext(context.Background(), source, logOpts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewGitLogCmdContext is the same as NewGitLogCmd but supports passing in a
|
||||||
|
// context to use for timeouts
|
||||||
|
func NewGitLogCmdContext(ctx context.Context, source string, logOpts string) (*GitCmd, error) {
|
||||||
sourceClean := filepath.Clean(source)
|
sourceClean := filepath.Clean(source)
|
||||||
var cmd *exec.Cmd
|
var cmd *exec.Cmd
|
||||||
if logOpts != "" {
|
if logOpts != "" {
|
||||||
@@ -82,9 +88,9 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
args = append(args, userArgs...)
|
args = append(args, userArgs...)
|
||||||
cmd = exec.Command("git", args...)
|
cmd = exec.CommandContext(ctx, "git", args...)
|
||||||
} else {
|
} else {
|
||||||
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0",
|
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "log", "-p", "-U0",
|
||||||
"--full-history", "--all", "--diff-filter=tuxdb")
|
"--full-history", "--all", "--diff-filter=tuxdb")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,11 +128,17 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
|
|||||||
// Caller should read everything from channels until receiving a signal about their closure and call
|
// Caller should read everything from channels until receiving a signal about their closure and call
|
||||||
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
|
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
|
||||||
func NewGitDiffCmd(source string, staged bool) (*GitCmd, error) {
|
func NewGitDiffCmd(source string, staged bool) (*GitCmd, error) {
|
||||||
|
return NewGitDiffCmdContext(context.Background(), source, staged)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewGitDiffCmdContext is the same as NewGitDiffCmd but supports passing in a
|
||||||
|
// context to use for timeouts
|
||||||
|
func NewGitDiffCmdContext(ctx context.Context, source string, staged bool) (*GitCmd, error) {
|
||||||
sourceClean := filepath.Clean(source)
|
sourceClean := filepath.Clean(source)
|
||||||
var cmd *exec.Cmd
|
var cmd *exec.Cmd
|
||||||
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff", ".")
|
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff", ".")
|
||||||
if staged {
|
if staged {
|
||||||
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff",
|
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff",
|
||||||
"--staged", ".")
|
"--staged", ".")
|
||||||
}
|
}
|
||||||
logging.Debug().Msgf("executing: %s", cmd.String())
|
logging.Debug().Msgf("executing: %s", cmd.String())
|
||||||
@@ -177,13 +189,24 @@ func (c *GitCmd) Wait() error {
|
|||||||
return c.cmd.Wait()
|
return c.cmd.Wait()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// String displays the command used for GitCmd
|
||||||
|
func (c *GitCmd) String() string {
|
||||||
|
return c.cmd.String()
|
||||||
|
}
|
||||||
|
|
||||||
// NewBlobReader returns an io.ReadCloser that can be used to read a blob
|
// NewBlobReader returns an io.ReadCloser that can be used to read a blob
|
||||||
// within the git repo used to create the GitCmd.
|
// within the git repo used to create the GitCmd.
|
||||||
//
|
//
|
||||||
// The caller is responsible for closing the reader.
|
// The caller is responsible for closing the reader.
|
||||||
func (c *GitCmd) NewBlobReader(commit, path string) (io.ReadCloser, error) {
|
func (c *GitCmd) NewBlobReader(commit, path string) (io.ReadCloser, error) {
|
||||||
|
return c.NewBlobReaderContext(context.Background(), commit, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewBlobReaderContext is the same as NewBlobReader but supports passing in a
|
||||||
|
// context to use for timeouts
|
||||||
|
func (c *GitCmd) NewBlobReaderContext(ctx context.Context, commit, path string) (io.ReadCloser, error) {
|
||||||
gitArgs := []string{"-C", c.repoPath, "cat-file", "blob", commit + ":" + path}
|
gitArgs := []string{"-C", c.repoPath, "cat-file", "blob", commit + ":" + path}
|
||||||
cmd := exec.Command("git", gitArgs...)
|
cmd := exec.CommandContext(ctx, "git", gitArgs...)
|
||||||
cmd.Stderr = io.Discard
|
cmd.Stderr = io.Discard
|
||||||
stdout, err := cmd.StdoutPipe()
|
stdout, err := cmd.StdoutPipe()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -275,7 +298,9 @@ type CommitInfo struct {
|
|||||||
// Fragments yields fragments from a git repo
|
// Fragments yields fragments from a git repo
|
||||||
func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
||||||
defer func() {
|
defer func() {
|
||||||
_ = s.Cmd.Wait()
|
if err := s.Cmd.Wait(); err != nil {
|
||||||
|
logging.Debug().Err(err).Str("cmd", s.Cmd.String()).Msg("command aborted")
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -287,6 +312,8 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
|||||||
// loop to range over both DiffFiles (stdout) and ErrCh (stderr)
|
// loop to range over both DiffFiles (stdout) and ErrCh (stderr)
|
||||||
for diffFilesCh != nil || errCh != nil {
|
for diffFilesCh != nil || errCh != nil {
|
||||||
select {
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
case gitdiffFile, open := <-diffFilesCh:
|
case gitdiffFile, open := <-diffFilesCh:
|
||||||
if !open {
|
if !open {
|
||||||
diffFilesCh = nil
|
diffFilesCh = nil
|
||||||
@@ -336,7 +363,7 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
|||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
|
|
||||||
if yieldAsArchive {
|
if yieldAsArchive {
|
||||||
blob, err := s.Cmd.NewBlobReader(commitSHA, gitdiffFile.NewName)
|
blob, err := s.Cmd.NewBlobReaderContext(ctx, commitSHA, gitdiffFile.NewName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Error().Err(err).Msg("could not read archive blob")
|
logging.Error().Err(err).Msg("could not read archive blob")
|
||||||
return nil
|
return nil
|
||||||
@@ -394,17 +421,28 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
default:
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// NewRemoteInfo builds a new RemoteInfo for generating finding links
|
// NewRemoteInfo builds a new RemoteInfo for generating finding links
|
||||||
func NewRemoteInfo(platform scm.Platform, source string) *RemoteInfo {
|
func NewRemoteInfo(platform scm.Platform, source string) *RemoteInfo {
|
||||||
|
return NewRemoteInfoContext(context.Background(), platform, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRemoteInfoContext is the same as NewRemoteInfo but supports passing in a
|
||||||
|
// context to use for timeouts
|
||||||
|
func NewRemoteInfoContext(ctx context.Context, platform scm.Platform, source string) *RemoteInfo {
|
||||||
if platform == scm.NoPlatform {
|
if platform == scm.NoPlatform {
|
||||||
return &RemoteInfo{Platform: platform}
|
return &RemoteInfo{Platform: platform}
|
||||||
}
|
}
|
||||||
|
|
||||||
remoteUrl, err := getRemoteUrl(source)
|
remoteUrl, err := getRemoteUrl(ctx, source)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if strings.Contains(err.Error(), "No remote configured") {
|
if strings.Contains(err.Error(), "No remote configured") {
|
||||||
logging.Debug().Msg("skipping finding links: repository has no configured remote.")
|
logging.Debug().Msg("skipping finding links: repository has no configured remote.")
|
||||||
@@ -442,9 +480,9 @@ End:
|
|||||||
|
|
||||||
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):(?:\d{1,5}/)?([\w/.-]+?)(?:\.git)?$`)
|
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):(?:\d{1,5}/)?([\w/.-]+?)(?:\.git)?$`)
|
||||||
|
|
||||||
func getRemoteUrl(source string) (*url.URL, error) {
|
func getRemoteUrl(ctx context.Context, source string) (*url.URL, error) {
|
||||||
// This will return the first remote — typically, "origin".
|
// This will return the first remote — typically, "origin".
|
||||||
cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
|
cmd := exec.CommandContext(ctx, "git", "ls-remote", "--quiet", "--get-url")
|
||||||
if source != "." {
|
if source != "." {
|
||||||
cmd.Dir = source
|
cmd.Dir = source
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user