From e0ea9cefde89ae2febe4cf00e73833e74367c902 Mon Sep 17 00:00:00 2001 From: Zach Date: Tue, 13 May 2025 21:39:09 -0500 Subject: [PATCH] one tmp dir to rule them all, I think --- cmd/root.go | 2 ++ detect/archive.go | 20 ++++++++++---------- detect/detect.go | 36 +++++++++++++++--------------------- detect/directory.go | 12 ++++-------- detect/fragment.go | 24 ++++++++++++++++++++++++ detect/git.go | 4 ++-- sources/git.go | 1 + 7 files changed, 58 insertions(+), 41 deletions(-) create mode 100644 detect/fragment.go diff --git a/cmd/root.go b/cmd/root.go index f06e38a9..5cdd132d 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -421,6 +421,8 @@ func findingSummaryAndExit(detector *detect.Detector, findings []report.Finding, diagnosticsManager.StopDiagnostics() } + detector.Cleanup() + totalBytes := detector.TotalBytes.Load() bytesMsg := fmt.Sprintf("scanned ~%d bytes (%s)", totalBytes, bytesConvert(totalBytes)) if err == nil { diff --git a/detect/archive.go b/detect/archive.go index 7f1aef73..fe2bb782 100644 --- a/detect/archive.go +++ b/detect/archive.go @@ -12,10 +12,10 @@ import ( "github.com/zricethezav/gitleaks/v8/sources" ) -// IsArchive asks archives.Identify (with a nil stream, so only the filename) +// isArchive asks archives.Identify (with a nil stream, so only the filename) // whether this file would be handled by an Extractor. If Identify returns // a Format implementing archives.Extractor, we treat it as an archive. -func IsArchive(path string) bool { +func isArchive(path string) bool { format, _, err := archives.Identify(context.Background(), path, nil) if err != nil { // no matching format at all @@ -27,15 +27,15 @@ func IsArchive(path string) bool { // ExtractArchive extracts all files from archivePath into a temp dir. // Returns the list of ScanTargets (with real file paths) and the temp dir for cleanup. -func ExtractArchive(archivePath string) ([]sources.ScanTarget, string, error) { - tmpDir, err := os.MkdirTemp("", "gitleaks-archive-") +func extractArchive(archivePath string) ([]sources.ScanTarget, string, error) { + tmpArchiveDir, err := os.MkdirTemp(tmpDir, "archive-*") if err != nil { - return nil, "", err + return nil, "", fmt.Errorf("creating temp dir for archive: %w", err) } f, err := os.Open(archivePath) if err != nil { - os.RemoveAll(tmpDir) + os.RemoveAll(tmpArchiveDir) return nil, "", err } defer f.Close() @@ -43,13 +43,13 @@ func ExtractArchive(archivePath string) ([]sources.ScanTarget, string, error) { ctx := context.Background() format, stream, err := archives.Identify(ctx, archivePath, f) if err != nil { - os.RemoveAll(tmpDir) + os.RemoveAll(tmpArchiveDir) return nil, "", err } extractor, ok := format.(archives.Extractor) if !ok { - os.RemoveAll(tmpDir) + os.RemoveAll(tmpArchiveDir) return nil, "", fmt.Errorf("format %T is not extractable", format) } @@ -74,7 +74,7 @@ func ExtractArchive(archivePath string) ([]sources.ScanTarget, string, error) { } defer r.Close() - outPath := filepath.Join(tmpDir, file.Name()) + outPath := filepath.Join(tmpArchiveDir, file.Name()) if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil { return err } @@ -92,5 +92,5 @@ func ExtractArchive(archivePath string) ([]sources.ScanTarget, string, error) { return nil }) - return targets, tmpDir, err + return targets, tmpArchiveDir, err } diff --git a/detect/detect.go b/detect/detect.go index 3c2bf65a..3f82a1f5 100644 --- a/detect/detect.go +++ b/detect/detect.go @@ -36,8 +36,17 @@ const ( var ( newLineRegexp = regexp.MustCompile("\n") isWindows = runtime.GOOS == "windows" + tmpDir string ) +func init() { + var err error + tmpDir, err = os.MkdirTemp("", "gitleaks-*") + if err != nil { + logging.Fatal().Err(err).Msg("failed to create temp dir for archive extraction") + } +} + // Detector is the main detector struct type Detector struct { // Config is the configuration for the detector @@ -102,27 +111,12 @@ type Detector struct { TotalBytes atomic.Uint64 } -// Fragment contains the data to be scanned -type Fragment struct { - // Raw is the raw content of the fragment - Raw string - - Bytes []byte - - // FilePath is the path to the file, if applicable. - // The path separator MUST be normalized to `/`. - FilePath string - SymlinkFile string - // WindowsFilePath is the path with the original separator. - // This provides a backwards-compatible solution to https://github.com/gitleaks/gitleaks/issues/1565. - WindowsFilePath string `json:"-"` // TODO: remove this in v9. - - // CommitSHA is the SHA of the commit if applicable - CommitSHA string - - // newlineIndices is a list of indices of newlines in the raw content. - // This is used to calculate the line location of a finding - newlineIndices [][]int +func (d *Detector) Cleanup() { + if tmpDir != "" { + if err := os.RemoveAll(tmpDir); err != nil { + logging.Warn().Err(err).Msg("failed to remove temp dir for archive extraction") + } + } } // NewDetector creates a new detector with the given config diff --git a/detect/directory.go b/detect/directory.go index fa84bfc6..fa93613b 100644 --- a/detect/directory.go +++ b/detect/directory.go @@ -43,10 +43,10 @@ func (d *Detector) detectScanTarget(scanTarget sources.ScanTarget) error { logger.Trace().Msg("Scanning path") // --- Archive branch: extract and reschedule children --- - if IsArchive(scanTarget.Path) { - logger.Info().Msg("Found archive") + if isArchive(scanTarget.Path) { + logger.Debug().Msg("Found archive") - targets, tmpdir, err := ExtractArchive(scanTarget.Path) + targets, tmpArchiveDir, err := extractArchive(scanTarget.Path) if err != nil { logger.Warn().Err(err).Msg("Failed to extract archive") return nil @@ -55,7 +55,7 @@ func (d *Detector) detectScanTarget(scanTarget sources.ScanTarget) error { for _, t := range targets { t := t // compute path INSIDE this archive - rel, rerr := filepath.Rel(tmpdir, t.Path) + rel, rerr := filepath.Rel(tmpArchiveDir, t.Path) if rerr != nil { rel = filepath.Base(t.Path) } @@ -73,10 +73,6 @@ func (d *Detector) detectScanTarget(scanTarget sources.ScanTarget) error { }) } - // cleanup extraction directory - // if err := os.RemoveAll(tmpdir); err != nil { - // logger.Warn().Err(err).Msg("Failed to remove tempdir") - // } return nil } diff --git a/detect/fragment.go b/detect/fragment.go new file mode 100644 index 00000000..5cd1bcd6 --- /dev/null +++ b/detect/fragment.go @@ -0,0 +1,24 @@ +package detect + +// Fragment contains the data to be scanned +type Fragment struct { + // Raw is the raw content of the fragment + Raw string + + Bytes []byte + + // FilePath is the path to the file, if applicable. + // The path separator MUST be normalized to `/`. + FilePath string + SymlinkFile string + // WindowsFilePath is the path with the original separator. + // This provides a backwards-compatible solution to https://github.com/gitleaks/gitleaks/issues/1565. + WindowsFilePath string `json:"-"` // TODO: remove this in v9. + + // CommitSHA is the SHA of the commit if applicable + CommitSHA string + + // newlineIndices is a list of indices of newlines in the raw content. + // This is used to calculate the line location of a finding + newlineIndices [][]int +} diff --git a/detect/git.go b/detect/git.go index 7251e72b..06c16326 100644 --- a/detect/git.go +++ b/detect/git.go @@ -46,7 +46,7 @@ func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report. } } - if IsArchive(gitdiffFile.NewName) { + if isArchive(gitdiffFile.NewName) { // Check if commit is allowed d.Sema.Go(func() error { // Check out the archive blob to disk @@ -57,7 +57,7 @@ func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report. } defer os.Remove(archivePath) - targets, tmpDir, err := ExtractArchive(archivePath) + targets, tmpDir, err := extractArchive(archivePath) if err != nil { os.RemoveAll(tmpDir) logging.Warn().Err(err).Msg("failed to extract archive") diff --git a/sources/git.go b/sources/git.go index 0e76a921..96315e74 100644 --- a/sources/git.go +++ b/sources/git.go @@ -141,6 +141,7 @@ func NewGitDiffCmd(source string, staged bool) (*GitCmd, error) { func (g *GitCmd) CheckoutBlob(commit, filepathInRepo string) (string, error) { // Create a temp file with the same extension as the blob, if possible ext := filepath.Ext(filepathInRepo) + // tmpDir, err := os.MkdirTemp("gitleaks", "archive-*") tmpFile, err := os.CreateTemp("", "gitleaks-blob-*"+ext) if err != nil { return "", fmt.Errorf("creating temp file for blob: %w", err)