Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
fix: add git worktree support in PrepareRepo (#4690)
Andoni Alonso6f5220357f49
diff --git a/pkg/sources/git/git.go b/pkg/sources/git/git.goindex ccf7980ba..3b3d72f88 100644--- a/pkg/sources/git/git.go+++ b/pkg/sources/git/git.go@@ -678,6 +678,50 @@ func (s *Git) CommitsScanned() uint64 {const gitDirName = ".git"+// resolveGitDir resolves the actual git directory path for a repository.+// In a regular repository, .git is a directory containing the git data.+// In a git worktree, .git is a file containing a "gitdir: <path>" reference+// to the actual git directory location.+// This function handles both cases and returns the path to the actual git directory.+func resolveGitDir(repoPath string) (string, error) {+ gitPath := filepath.Join(repoPath, gitDirName)++ info, err := os.Stat(gitPath)+ if err != nil {+ return "", fmt.Errorf("failed to stat .git: %w", err)+ }++ // If .git is a directory, return it directly+ if info.IsDir() {+ return gitPath, nil+ }++ // .git is a file (worktree) - read and parse the gitdir reference+ content, err := os.ReadFile(gitPath)+ if err != nil {+ return "", fmt.Errorf("failed to read .git file: %w", err)+ }++ // Parse "gitdir: <path>" format+ line := strings.TrimSpace(string(content))+ const gitdirPrefix = "gitdir: "+ if !strings.HasPrefix(line, gitdirPrefix) {+ return "", fmt.Errorf("invalid .git file format: expected 'gitdir: <path>', got %q", line)+ }++ gitdirPath := strings.TrimPrefix(line, gitdirPrefix)++ // The path may be relative to the worktree directory+ if !filepath.IsAbs(gitdirPath) {+ gitdirPath = filepath.Join(repoPath, gitdirPath)+ }++ // Clean the path to resolve any ".." components+ gitdirPath = filepath.Clean(gitdirPath)++ return gitdirPath, nil+}+// getGitDir returns the likely path of the ".git" directory.// If the repository is bare, it will be at the top-level; otherwise, it// exists in the ".git" directory at the root of the working tree.@@ -1428,8 +1472,13 @@ func PrepareRepo(ctx context.Context, uriString, clonePath string, trustLocalGit// Note: To scan **un**staged changes in the future, we'd need to set core.worktree to the original path.uriPath := normalizedURI.Path- originalIndexPath := filepath.Join(uriPath, gitDirName, "index")+ // Resolve the actual git directory (handles both regular repos and worktrees)+ originalGitDir, err := resolveGitDir(uriPath)+ if err != nil {+ return path, remote, fmt.Errorf("failed to resolve git directory: %w", err)+ }+ originalIndexPath := filepath.Join(originalGitDir, "index")clonedIndexPath := filepath.Join(path, gitDirName, "index")indexData, err := os.ReadFile(originalIndexPath)@@ -1439,6 +1488,24 @@ func PrepareRepo(ctx context.Context, uriString, clonePath string, trustLocalGitif err := os.WriteFile(clonedIndexPath, indexData, 0644); err != nil {return path, remote, fmt.Errorf("failed to write index file: %w", err)}++ // Add the source object store as an alternate so staged blobs are accessible.+ // git clone with file:// only transfers reachable objects; staged blobs must+ // be reached via the original object store.+ // For worktrees, the commondir file points to the main repo's git dir+ // which holds the actual shared object store.+ sourceObjectsPath := filepath.Join(originalGitDir, "objects")+ if commondirData, err := os.ReadFile(filepath.Join(originalGitDir, "commondir")); err == nil {+ commondir := strings.TrimSpace(string(commondirData))+ if !filepath.IsAbs(commondir) {+ commondir = filepath.Join(originalGitDir, commondir)+ }+ sourceObjectsPath = filepath.Join(filepath.Clean(commondir), "objects")+ }+ alternatesPath := filepath.Join(path, gitDirName, "objects", "info", "alternates")+ if err := os.MkdirAll(filepath.Dir(alternatesPath), 0755); err == nil {+ _ = os.WriteFile(alternatesPath, []byte(sourceObjectsPath+"\n"), 0644)+ }}}case "http", "https":diff --git a/pkg/sources/git/git_test.go b/pkg/sources/git/git_test.goindex 57ade12a8..ca04ee710 100644--- a/pkg/sources/git/git_test.go+++ b/pkg/sources/git/git_test.go@@ -651,6 +651,7 @@ func setupTestRepo(t *testing.T, repoName string) string {assert.NoError(t, exec.Command("git", "init", repoPath).Run())assert.NoError(t, exec.Command("git", "-C", repoPath, "config", "user.name", "Test User").Run())assert.NoError(t, exec.Command("git", "-C", repoPath, "config", "user.email", "[email protected]").Run())+ assert.NoError(t, exec.Command("git", "-C", repoPath, "config", "commit.gpgsign", "false").Run())return repoPath}@@ -854,6 +855,111 @@ func TestPrepareRepoErrorPaths(t *testing.T) {})}+func TestResolveGitDir(t *testing.T) {+ t.Parallel()++ t.Run("regular repository with .git directory", func(t *testing.T) {+ repoPath := setupTestRepo(t, "regular-repo")+ addTestFileAndCommit(t, repoPath, "test.txt", "test content")++ gitDir, err := resolveGitDir(repoPath)+ assert.NoError(t, err)+ assert.Equal(t, filepath.Join(repoPath, ".git"), gitDir)++ // Verify it's actually a directory+ info, err := os.Stat(gitDir)+ assert.NoError(t, err)+ assert.True(t, info.IsDir())+ })++ t.Run("git worktree with .git file", func(t *testing.T) {+ // Create main repository+ mainRepoPath := setupTestRepo(t, "main-repo")+ addTestFileAndCommit(t, mainRepoPath, "test.txt", "test content")++ // Create a worktree+ worktreePath := filepath.Join(filepath.Dir(mainRepoPath), "worktree")+ err := exec.Command("git", "-C", mainRepoPath, "worktree", "add", worktreePath, "-b", "worktree-branch").Run()+ assert.NoError(t, err)++ // Verify .git is a file in the worktree+ gitPath := filepath.Join(worktreePath, ".git")+ info, err := os.Stat(gitPath)+ assert.NoError(t, err)+ assert.False(t, info.IsDir(), ".git should be a file in a worktree")++ // Test resolveGitDir+ gitDir, err := resolveGitDir(worktreePath)+ assert.NoError(t, err)+ assert.NotEqual(t, gitPath, gitDir, "resolved git dir should be different from .git file path")++ // Verify the resolved path is a valid git directory (should contain index)+ indexPath := filepath.Join(gitDir, "index")+ _, err = os.Stat(indexPath)+ assert.NoError(t, err, "resolved git dir should contain index file")+ })++ t.Run("nonexistent repository", func(t *testing.T) {+ _, err := resolveGitDir("/nonexistent/path")+ assert.Error(t, err)+ assert.Contains(t, err.Error(), "failed to stat .git")+ })++ t.Run("invalid .git file content", func(t *testing.T) {+ tempDir := t.TempDir()+ gitPath := filepath.Join(tempDir, ".git")++ // Create an invalid .git file (not starting with "gitdir: ")+ err := os.WriteFile(gitPath, []byte("invalid content"), 0644)+ assert.NoError(t, err)++ _, err = resolveGitDir(tempDir)+ assert.Error(t, err)+ assert.Contains(t, err.Error(), "invalid .git file format")+ })+}++func TestPrepareRepoWithWorktree(t *testing.T) {+ t.Parallel()+ ctx := context.Background()++ // Create main repository with staged changes+ mainRepoPath := setupTestRepo(t, "main-repo-worktree")+ addTestFileAndCommit(t, mainRepoPath, "test.txt", "initial content")++ // Create a worktree+ worktreePath := filepath.Join(filepath.Dir(mainRepoPath), "test-worktree")+ err := exec.Command("git", "-C", mainRepoPath, "worktree", "add", worktreePath, "-b", "worktree-branch").Run()+ assert.NoError(t, err)++ // Stage some changes in the worktree+ testFile := filepath.Join(worktreePath, "test.txt")+ assert.NoError(t, os.WriteFile(testFile, []byte("modified content in worktree"), 0644))+ assert.NoError(t, exec.Command("git", "-C", worktreePath, "add", "test.txt").Run())++ // Verify staged changes exist in worktree+ output, err := exec.Command("git", "-C", worktreePath, "diff", "--cached").Output()+ assert.NoError(t, err)+ assert.Contains(t, string(output), "modified content in worktree", "Staged changes should exist in worktree")++ t.Run("PrepareRepo should work with git worktree", func(t *testing.T) {+ fileURI := "file://" + worktreePath+ preparedPath, isRemote, err := PrepareRepo(ctx, fileURI, "", false, false)++ assert.NoError(t, err, "PrepareRepo should succeed with git worktree")+ assert.False(t, isRemote)+ assert.NotEmpty(t, preparedPath)++ defer func() { _ = os.RemoveAll(preparedPath) }()++ // Verify the cloned repo has the staged changes preserved+ stagedOutput, err := exec.Command("git", "-C", preparedPath, "diff", "--cached").Output()+ assert.NoError(t, err, "git diff --cached should succeed in prepared repo")+ assert.Contains(t, string(stagedOutput), "modified content in worktree",+ "Staged changes should be preserved when cloning from worktree")+ })+}+func TestNormalizeFileURI(t *testing.T) {tests := []struct {name string