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:
bplaxcoandAlex Layne authored and GitHub committed 2025-06-01 11:29:34 -05:00
1 parent 489d13c14e
commit 782f310478
77 files changed
+2975 -777

No files matched your search

+40 -21
View File
@@ -19,13 +19,13 @@
package cmd
import (
"context"
"os"
"time"
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
@@ -51,15 +51,15 @@ var detectCmd = &cobra.Command{
func runDetect(cmd *cobra.Command, args []string) {
// start timer
start := time.Now()
source := mustGetStringFlag(cmd, "source")
sourcePath := mustGetStringFlag(cmd, "source")
// setup config (aka, the thing that defines rules)
initConfig(source)
initConfig(sourcePath)
initDiagnostics()
cfg := Config(cmd)
// create detector
detector := Detector(cmd, cfg, source)
detector := Detector(cmd, cfg, sourcePath)
// parse flags
detector.FollowSymlinks = mustGetBoolFlag(cmd, "follow-symlinks")
@@ -71,46 +71,65 @@ func runDetect(cmd *cobra.Command, args []string) {
// - git: scan the history of the repo
// - no-git: scan files by treating the repo as a plain directory
var (
findings []report.Finding
err error
findings []report.Finding
ctx = context.Background()
)
if noGit {
paths, err := sources.DirectoryTargets(
source,
detector.Sema,
detector.FollowSymlinks,
detector.Config.Allowlists,
findings, err = detector.DetectSource(
ctx, &sources.Files{
Config: &cfg,
FollowSymlinks: detector.FollowSymlinks,
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
Path: sourcePath,
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
logging.Fatal().Err(err).Send()
}
if findings, err = detector.DetectFiles(paths); err != nil {
if err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed scan directory")
logging.Error().Err(err).Msg("failed to scan directory")
}
} else if fromPipe {
if findings, err = detector.DetectReader(os.Stdin, 10); err != nil {
findings, err = detector.DetectSource(
ctx, &sources.File{
Content: os.Stdin,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
// log fatal to exit, no need to continue since a report
// will not be generated when scanning from a pipe...for now
logging.Fatal().Err(err).Msg("failed scan input from stdin")
}
} else {
var (
logOpts = mustGetStringFlag(cmd, "log-opts")
gitCmd *sources.GitCmd
scmPlatform scm.Platform
remote *detect.RemoteInfo
)
if gitCmd, err = sources.NewGitLogCmd(source, logOpts); err != nil {
logOpts := mustGetStringFlag(cmd, "log-opts")
if gitCmd, err = sources.NewGitLogCmd(sourcePath, logOpts); err != nil {
logging.Fatal().Err(err).Msg("could not create Git cmd")
}
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
logging.Fatal().Err(err).Send()
}
remote = detect.NewRemoteInfo(scmPlatform, source)
if findings, err = detector.DetectGit(gitCmd, remote); err != nil {
findings, err = detector.DetectSource(
ctx, &sources.Git{
Cmd: gitCmd,
Config: &detector.Config,
Remote: sources.NewRemoteInfo(scmPlatform, sourcePath),
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed to scan Git repository")
}
+30
View File
@@ -1,7 +1,10 @@
package cmd
import (
"errors"
"fmt"
"net/http"
_ "net/http/pprof"
"os"
"path/filepath"
"runtime"
@@ -34,6 +37,14 @@ func NewDiagnosticsManager(diagnosticsFlag string, diagnosticsDir string) (*Diag
OutputDir: diagnosticsDir,
}
if diagnosticsFlag == "http" {
if len(diagnosticsDir) != 0 {
return nil, errors.New("the diagnostics directory should not be set in http mode")
}
return dm, nil
}
// If no output directory is specified, use the current directory
if dm.OutputDir == "" {
var err error
@@ -87,6 +98,10 @@ func (dm *DiagnosticsManager) StartDiagnostics() error {
if err = dm.StartTraceProfile(); err != nil {
return err
}
case "http":
if err = dm.StartHttpHandler(); err != nil {
return err
}
default:
logging.Warn().Msgf("Unknown diagnostics type: %s", diagType)
}
@@ -112,10 +127,25 @@ func (dm *DiagnosticsManager) StopDiagnostics() {
dm.WriteMemoryProfile()
case "trace":
dm.StopTraceProfile()
case "http":
// No need to stop the http one
}
}
}
func (dm *DiagnosticsManager) StartHttpHandler() error {
if len(dm.DiagTypes) > 1 {
return errors.New("other diagnostics modes should not be enabled when http mode is enabled")
}
go func() {
logging.Error().Err(http.ListenAndServe("localhost:6060", nil)).Send()
}()
logging.Info().Str("url", "http://localhost:6060/debug/pprof/").Msg("Diagnostics server started")
return nil
}
// StartCPUProfile starts CPU profiling
func (dm *DiagnosticsManager) StartCPUProfile() error {
cpuProfilePath := filepath.Join(dm.OutputDir, "cpu.pprof")
+14 -18
View File
@@ -1,12 +1,12 @@
package cmd
import (
"context"
"time"
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
@@ -34,11 +34,7 @@ func runDirectory(cmd *cobra.Command, args []string) {
initConfig(source)
initDiagnostics()
var (
findings []report.Finding
err error
)
var err error
// setup config (aka, the thing that defines rules)
cfg := Config(cmd)
@@ -50,28 +46,28 @@ func runDirectory(cmd *cobra.Command, args []string) {
// set follow symlinks flag
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
// set exit code
exitCode, err := cmd.Flags().GetInt("exit-code")
if err != nil {
logging.Fatal().Err(err).Msg("could not get exit code")
}
var paths <-chan sources.ScanTarget
paths, err = sources.DirectoryTargets(
source,
detector.Sema,
detector.FollowSymlinks,
detector.Config.Allowlists,
findings, err := detector.DetectSource(
context.Background(),
&sources.Files{
Config: &cfg,
FollowSymlinks: detector.FollowSymlinks,
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
Path: source,
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
logging.Fatal().Err(err)
}
findings, err = detector.DetectFiles(paths)
if err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed scan directory")
}
+4 -2
View File
@@ -66,7 +66,7 @@ func CreateGlobalConfig() config.Config {
// ----------- Documents and media -----------
regexp.MustCompile(`(?i)\.(?:bmp|gif|jpe?g|png|svg|tiff?)$`), // Images
regexp.MustCompile(`(?i)\.(?:eot|[ot]tf|woff2?)$`), // Fonts
regexp.MustCompile(`(?i)\.(?:docx?|xlsx?|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf|zip)$`),
regexp.MustCompile(`(?i)\.(?:docx?|xlsx?|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$`),
// ----------- Golang files -----------
regexp.MustCompile(`go\.(?:mod|sum|work(?:\.sum)?)$`),
@@ -105,7 +105,9 @@ func CreateGlobalConfig() config.Config {
// Misc
regexp.MustCompile(`verification-metadata\.xml`),
regexp.MustCompile(`Database.refactorlog`),
// regexp.MustCompile(`vendor`),
// ----------- Git files ------------
regexp.MustCompile(`(?:^|/)\.git$`),
},
StopWords: []string{
"abcdefghijklmnopqrstuvwxyz", // character range
+1 -2
View File
@@ -2,10 +2,9 @@ package main
import (
"os"
"slices"
"text/template"
"golang.org/x/exp/slices"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/rules"
"github.com/zricethezav/gitleaks/v8/config"
+1 -1
View File
@@ -79,7 +79,7 @@ func GenericCredential() *config.Rule {
// Token
`|(?:csrf)[_.-]?token` +
`|(?:io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)` + // Maven library coordinats. (e.g., https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt)
`|(?:io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)` + // Maven library coordinates. (e.g., https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt)
// General
`|(?:api|credentials|token)[_.-]?(?:endpoint|ur[il])` +
+2 -4
View File
@@ -1,8 +1,6 @@
package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
@@ -50,7 +48,7 @@ func PlaidAccessToken() *config.Rule {
RuleID: "plaid-api-token",
Description: "Discovered a Plaid API Token, potentially compromising financial data aggregation and banking services.",
Regex: utils.GenerateSemiGenericRegex([]string{"plaid"},
fmt.Sprintf("access-(?:sandbox|development|production)-%s", utils.Hex8_4_4_4_12()), true),
"access-(?:sandbox|development|production)-"+utils.Hex8_4_4_4_12(), true),
Keywords: []string{
"plaid",
@@ -58,6 +56,6 @@ func PlaidAccessToken() *config.Rule {
}
// validate
tps := utils.GenerateSampleSecrets("plaid", secrets.NewSecret(fmt.Sprintf("access-(?:sandbox|development|production)-%s", utils.Hex8_4_4_4_12())))
tps := utils.GenerateSampleSecrets("plaid", secrets.NewSecret("access-(?:sandbox|development|production)-"+utils.Hex8_4_4_4_12()))
return utils.Validate(r, tps, nil)
}
+16 -8
View File
@@ -1,12 +1,12 @@
package cmd
import (
"context"
"time"
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
@@ -56,19 +56,18 @@ func runGit(cmd *cobra.Command, args []string) {
preCommit := mustGetBoolFlag(cmd, "pre-commit")
var (
findings []report.Finding
err error
findings []report.Finding
err error
gitCmd *sources.GitCmd
scmPlatform scm.Platform
remote *detect.RemoteInfo
)
if preCommit || staged {
if gitCmd, err = sources.NewGitDiffCmd(source, staged); err != nil {
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
}
// Remote info + links are irrelevant for staged changes.
remote = &detect.RemoteInfo{Platform: scm.NoPlatform}
scmPlatform = scm.NoPlatform
} else {
if gitCmd, err = sources.NewGitLogCmd(source, logOpts); err != nil {
logging.Fatal().Err(err).Msg("could not create Git log cmd")
@@ -76,10 +75,19 @@ func runGit(cmd *cobra.Command, args []string) {
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
logging.Fatal().Err(err).Send()
}
remote = detect.NewRemoteInfo(scmPlatform, source)
}
findings, err = detector.DetectGit(gitCmd, remote)
findings, err = detector.DetectSource(
context.Background(),
&sources.Git{
Cmd: gitCmd,
Config: &detector.Config,
Remote: sources.NewRemoteInfo(scmPlatform, source),
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed to scan Git repository")
+14 -9
View File
@@ -76,10 +76,11 @@ func init() {
rootCmd.PersistentFlags().StringSlice("enable-rule", []string{}, "only enable specific rules by id")
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-archive-depth", 0, "allow scanning into nested archives up to this depth (default \"0\", no archive traversal is done)")
// Add diagnostics flags
rootCmd.PersistentFlags().String("diagnostics", "", "enable diagnostics (comma-separated list: cpu,mem,trace). cpu=CPU profiling, mem=memory profiling, trace=execution tracing")
rootCmd.PersistentFlags().String("diagnostics-dir", "", "directory to store diagnostics output files (defaults to current directory)")
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-dir", "", "directory to store diagnostics output files when not using http mode (defaults to current directory)")
err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
if err != nil {
@@ -237,12 +238,16 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
detector := detect.NewDetector(cfg)
if detector.MaxDecodeDepth, err = cmd.Flags().GetInt("max-decode-depth"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
if detector.MaxArchiveDepth, err = cmd.Flags().GetInt("max-archive-depth"); err != nil {
logging.Fatal().Err(err).Send()
}
// set color flag at first
if detector.NoColor, err = cmd.Flags().GetBool("no-color"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
// also init logger again without color
if detector.NoColor {
@@ -253,7 +258,7 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
}
detector.Config.Path, err = cmd.Flags().GetString("config")
if err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
// if config path is not set, then use the {source}/.gitleaks.toml path.
@@ -263,18 +268,18 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
}
// set verbose flag
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
// set redact flag
if detector.Redact, err = cmd.Flags().GetUint("redact"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
if detector.MaxTargetMegaBytes, err = cmd.Flags().GetInt("max-target-megabytes"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
// set ignore gitleaks:allow flag
if detector.IgnoreGitleaksAllow, err = cmd.Flags().GetBool("ignore-gitleaks-allow"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
gitleaksIgnorePath, err := cmd.Flags().GetString("gitleaks-ignore-path")
+12 -3
View File
@@ -1,12 +1,14 @@
package cmd
import (
"context"
"os"
"time"
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/sources"
)
func init() {
@@ -35,10 +37,17 @@ func runStdIn(cmd *cobra.Command, _ []string) {
// parse flag(s)
exitCode := mustGetIntFlag(cmd, "exit-code")
findings, err := detector.DetectReader(os.Stdin, 10)
findings, err := detector.DetectSource(
context.Background(),
&sources.File{
Content: os.Stdin,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
// log fatal to exit, no need to continue since a report
// will not be generated when scanning from a pipe...for now
// log fatal to exit, no need to continue since a report will not be
// generated when scanning from a pipe...for now
logging.Fatal().Err(err).Msg("failed scan input from stdin")
}