directory.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package sources
  2. import (
  3. "io/fs"
  4. "os"
  5. "path/filepath"
  6. "runtime"
  7. "github.com/fatih/semgroup"
  8. "github.com/zricethezav/gitleaks/v8/logging"
  9. )
  10. type ScanTarget struct {
  11. Path string
  12. Symlink string
  13. }
  14. var isWindows = runtime.GOOS == "windows"
  15. func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool, shouldSkip func(string) bool) (<-chan ScanTarget, error) {
  16. paths := make(chan ScanTarget)
  17. s.Go(func() error {
  18. defer close(paths)
  19. return filepath.Walk(source,
  20. func(path string, fInfo os.FileInfo, err error) error {
  21. logger := logging.With().Str("path", path).Logger()
  22. if err != nil {
  23. if os.IsPermission(err) {
  24. // This seems to only fail on directories at this stage.
  25. logger.Warn().Msg("Skipping directory: permission denied")
  26. return filepath.SkipDir
  27. }
  28. return err
  29. }
  30. // Empty; nothing to do here.
  31. if fInfo.Size() == 0 {
  32. return nil
  33. }
  34. // Unwrap symlinks, if |followSymlinks| is set.
  35. scanTarget := ScanTarget{
  36. Path: path,
  37. }
  38. if fInfo.Mode().Type() == fs.ModeSymlink {
  39. if !followSymlinks {
  40. logger.Debug().Msg("Skipping symlink")
  41. return nil
  42. }
  43. realPath, err := filepath.EvalSymlinks(path)
  44. if err != nil {
  45. return err
  46. }
  47. realPathFileInfo, _ := os.Stat(realPath)
  48. if realPathFileInfo.IsDir() {
  49. logger.Warn().Str("target", realPath).Msg("Skipping symlinked directory")
  50. return nil
  51. }
  52. scanTarget.Path = realPath
  53. scanTarget.Symlink = path
  54. }
  55. // TODO: Also run this check against the resolved symlink?
  56. skip := shouldSkip(path) ||
  57. // TODO: Remove this in v9.
  58. // This is an awkward hack to mitigate https://github.com/gitleaks/gitleaks/issues/1641.
  59. (isWindows && shouldSkip(filepath.ToSlash(path)))
  60. if fInfo.IsDir() {
  61. // Directory
  62. if skip {
  63. logger.Debug().Msg("Skipping directory due to global allowlist")
  64. return filepath.SkipDir
  65. }
  66. if fInfo.Name() == ".git" {
  67. // Don't scan .git directories.
  68. // TODO: Add this to the config allowlist, instead of hard-coding it.
  69. return filepath.SkipDir
  70. }
  71. } else {
  72. // File
  73. if skip {
  74. logger.Debug().Msg("Skipping file due to global allowlist")
  75. return nil
  76. }
  77. paths <- scanTarget
  78. }
  79. return nil
  80. })
  81. })
  82. return paths, nil
  83. }