diff --git a/cmd/bd/fs_adapters.go b/cmd/bd/fs_adapters.go index b4a923dce..fa14070ee 100644 --- a/cmd/bd/fs_adapters.go +++ b/cmd/bd/fs_adapters.go @@ -1,6 +1,8 @@ package main import ( + "context" + "github.com/steveyegge/beads/cmd/bd/doctor" "github.com/steveyegge/beads/cmd/bd/setup" "github.com/steveyegge/beads/internal/config" @@ -46,3 +48,29 @@ func newInitFileSystemAdapters(workDir string) domain.BeadsDirFSAdapters { } return adapters } + +// withInitHooks scopes only hook operations; exclude and the other supplied +// callbacks keep their existing provider. Empty paths retain isolated callers. +func withInitHooks(fs domain.BeadsDirFSUseCase, workDir, beadsDir string) (domain.BeadsDirFSUseCase, *initHooksContext, error) { + if workDir == "" { + return fs, nil, nil + } + hooks, err := resolveInitHooksContext(workDir, beadsDir) + if err != nil { + return nil, nil, err + } + return initHooksFileSystem{BeadsDirFSUseCase: fs, hooks: hooks}, hooks, nil +} + +type initHooksFileSystem struct { + domain.BeadsDirFSUseCase + hooks *initHooksContext +} + +func (fs initHooksFileSystem) InstallGitHooks(_ context.Context, p domain.HooksInstallParams) error { + return installHooksWithContext(p.HookNames, p.Force, p.Shared, p.Chain, p.BeadsHooks, fs.hooks) +} + +func (fs initHooksFileSystem) InstallJJHooks(_ context.Context) error { + return installHooksWithContext(jjHookNames, false, false, false, false, fs.hooks) +} diff --git a/cmd/bd/hooks.go b/cmd/bd/hooks.go index 9be51e6e8..63a3e42c4 100644 --- a/cmd/bd/hooks.go +++ b/cmd/bd/hooks.go @@ -516,20 +516,21 @@ type HookStatus struct { // CheckGitHooks checks the status of bd git hooks in .git/hooks/ func CheckGitHooks() []HookStatus { - hooks := []string{"pre-commit", "post-merge", "pre-push", "post-checkout", "prepare-commit-msg"} - statuses := make([]HookStatus, 0, len(hooks)) - - // Get hooks directory from common git dir (hooks are shared across worktrees) hooksDir, err := git.GetGitHooksDir() if err != nil { // Not a git repo - return all hooks as not installed - for _, hookName := range hooks { + statuses := make([]HookStatus, 0, len(managedHookNames)) + for _, hookName := range managedHookNames { statuses = append(statuses, HookStatus{Name: hookName, Installed: false}) } return statuses } + return checkGitHooksAt(hooksDir) +} - for _, hookName := range hooks { +func checkGitHooksAt(hooksDir string) []HookStatus { + statuses := make([]HookStatus, 0, len(managedHookNames)) + for _, hookName := range managedHookNames { status := HookStatus{ Name: hookName, } @@ -818,6 +819,10 @@ var hooksListCmd = &cobra.Command{ // allowTracked exempts shared installs (.beads-hooks/ is deliberately // committed). func guardHookWritePath(hookPath string, allowTracked bool) error { + return guardHookWritePathWithProbe(hookPath, allowTracked, gitTrackedFileContext) +} + +func guardHookWritePathWithProbe(hookPath string, allowTracked bool, tracked func(string) string) error { fi, err := os.Lstat(hookPath) if err != nil { if os.IsNotExist(err) { @@ -841,8 +846,16 @@ func guardHookWritePath(hookPath string, allowTracked bool) error { // foreign tracked file dirties every clone that shares it (the wy-81fnur // incident). A bd-owned hook the user chose to commit (e.g. a team-shared // .beads/hooks/) is bd's to maintain — same policy as shared installs. - if isGitTrackedFile(hookPath) && !isBdOwnedHookFile(hookPath) { - return fmt.Errorf("%s is tracked by git and not a bd-managed hook; bd will not modify committed files it does not own\nUntrack it (git rm --cached) or move hooks to an untracked directory and re-run", hookPath) + if proof := tracked(hookPath); proof != "" && !isBdOwnedHookFile(hookPath) { + // `git rm --cached` only aims at the index that supplied the proof if the + // operator's shell still carries the same routing bd saw, so the inherited + // case names clearing that routing as the remedy instead. Both remediations + // are fixed strings; neither exposes an inherited value. + remediation := "Untrack it (git rm --cached) or move hooks to an untracked directory and re-run" + if proof == trackedProofInheritedIndex { + remediation = "Clear the inherited Git routing environment and re-run, or untrack it (git rm --cached) in the index that routing selects" + } + return fmt.Errorf("%s is tracked by git (%s) and not a bd-managed hook; bd will not modify committed files it does not own\n%s", hookPath, proof, remediation) } return nil } @@ -861,39 +874,86 @@ func isBdOwnedHookFile(path string) bool { return err == nil && versionInfo.IsBdHook } +// Fixed labels naming which index supplied a tracked-file proof. They are +// constants so the refusal can branch on the evidence source without +// reproducing the wording. +const ( + trackedProofContainingIndex = "containing repository index" + trackedProofInheritedIndex = "inherited Git index" +) + // isGitTrackedFile reports whether either the containing repository or the // inherited Git context tracks path. If neither probe succeeds, errors count // as untracked — the guard only blocks writes it can prove are unsafe. +// +// This and isGitTrackedFileWithEnv are test-only conveniences. Production +// callers should use the Context variants, whose label feeds the refusal +// diagnostic; the boolean form discards it. func isGitTrackedFile(path string) bool { + return gitTrackedFileContext(path) != "" +} + +func gitTrackedFileContext(path string) string { + inherited := os.Environ() + return gitTrackedFileContextWithEnv(path, gitenv.ScrubRouting(inherited), inherited) +} + +func isGitTrackedFileWithEnv(path string, clean, inherited []string) bool { + return gitTrackedFileContextWithEnv(path, clean, inherited) != "" +} + +// gitTrackedFileContextWithEnv returns a fixed label for the first successful +// proof. It never includes inherited environment values or Git output. +func gitTrackedFileContextWithEnv(path string, clean, inherited []string) string { dir := filepath.Dir(path) base := filepath.Base(path) - inherited := os.Environ() // Check the containing repository first so inherited routing cannot hide a - // tracked hook. The fallback preserves bare work trees and trusted config. - // Exit 1 is git's "repository reached, path is not tracked" answer and is - // final, so the second probe runs only when the scrubbed environment failed - // for a configuration reason (no reachable repository) rather than spawning - // a second `git ls-files` on every ordinary miss. - for _, env := range [][]string{gitenv.ScrubRouting(inherited), inherited} { + // tracked hook. The fallback preserves bare work trees and trusted config, + // and whichever index answers first is sufficient to refuse the write, even + // if the other view does not track the path. The fallback is reached only + // when the clean probe failed for a configuration reason (no reachable + // repository): exit 1 is git's "repository reached, path is not tracked" + // answer and is final, so a repository that reports the path untracked ends + // the search instead of spawning a second `git ls-files` on every ordinary + // miss. + for index, env := range [][]string{clean, inherited} { // #nosec G204 G702 - fixed "git" command; dir/base come from the hooks // directory bd itself resolved, not user input cmd := exec.Command("git", "-C", dir, "ls-files", "--error-unmatch", "--", base) cmd.Env = env err := cmd.Run() if err == nil { - return true + if index == 0 { + return trackedProofContainingIndex + } + return trackedProofInheritedIndex } if exit, ok := err.(*exec.ExitError); ok && exit.ExitCode() == 1 { - return false + return "" } } - return false + return "" +} + +func installHooksWithOptions(hookNames []string, force bool, shared bool, chain bool, beadsHooks bool) error { + return installHooksWithContext(hookNames, force, shared, chain, beadsHooks, nil) } //nolint:unparam // force and chain kept for CLI flag compatibility; section markers make them no-ops -func installHooksWithOptions(hookNames []string, force bool, shared bool, chain bool, beadsHooks bool) error { +func installHooksWithContext(hookNames []string, force, shared, chain, beadsHooks bool, selected *initHooksContext) error { + if selected != nil && shared { + return fmt.Errorf("shared hooks mode is not supported by selected init") + } var hooksDir string - if beadsHooks { + if selected != nil { + hooksDir = selected.paths.HooksDir + if beadsHooks { + if selected.beadsDir == "" { + return fmt.Errorf("%s", activeWorkspaceNotFoundError()) + } + hooksDir = filepath.Join(selected.beadsDir, "hooks") + } + } else if beadsHooks { // Use .beads/hooks/ directory (preferred for Dolt backend) beadsDir := beads.FindBeadsDir() if beadsDir == "" { @@ -932,13 +992,23 @@ func installHooksWithOptions(hookNames []string, force bool, shared bool, chain // core.hooksPath or the default .git/hooks). Without this, setting a local // core.hooksPath silently shadows the global one and those hooks stop running. if beadsHooks || shared { - preservePreexistingHooks(hooksDir) + if selected == nil { + preservePreexistingHooks(hooksDir) + } else { + preservePreexistingHooksAt(hooksDir, selected.paths.HooksDir, func() string { return selected.paths.MainRepoRoot }) + } } + tracked := gitTrackedFileContext + if selected != nil { + tracked = func(path string) string { + return gitTrackedFileContextWithEnv(path, selected.env, selected.inheritedEnv) + } + } // Refuse the whole install up front if any target is unsafe to write — // stopping midway through the loop would leave hooks half-installed. for _, hookName := range hookNames { - if err := guardHookWritePath(filepath.Join(hooksDir, hookName), shared); err != nil { + if err := guardHookWritePathWithProbe(filepath.Join(hooksDir, hookName), shared, tracked); err != nil { return fmt.Errorf("refusing to install %s hook: %w", hookName, err) } } @@ -1001,8 +1071,12 @@ func installHooksWithOptions(hookNames []string, force bool, shared bool, chain } } - // Configure git to use the hooks directory - if beadsHooks { + // Configure git to use the hooks directory after writing, as in ordinary installs. + if selected != nil && beadsHooks { + if err := selected.configureHooksPath(hooksDir); err != nil { + return fmt.Errorf("failed to configure git hooks path: %w", err) + } + } else if beadsHooks { if err := configureBeadsHooksPath(); err != nil { return fmt.Errorf("failed to configure git hooks path: %w", err) } @@ -1026,6 +1100,16 @@ func preservePreexistingHooks(targetDir string) { return } + preservePreexistingHooksAt(targetDir, currentDir, func() string { + repoRoot, _ := git.GetMainRepoRoot() + if repoRoot == "" { + repoRoot = git.GetRepoRoot() + } + return repoRoot + }) +} + +func preservePreexistingHooksAt(targetDir, currentDir string, mainRoot func() string) { // Resolve to absolute paths for reliable comparison. absTarget, err := filepath.Abs(targetDir) if err != nil { @@ -1037,19 +1121,16 @@ func preservePreexistingHooks(targetDir string) { } // If the current dir is already our target, this is a re-install — skip. - if absTarget == absCurrent { + if utils.PathsEqual(absTarget, absCurrent) { return } // If current dir is already a beads-managed directory, skip. - repoRoot, _ := git.GetMainRepoRoot() - if repoRoot == "" { - repoRoot = git.GetRepoRoot() - } + repoRoot := mainRoot() if repoRoot != "" { absBeadsHooks, _ := filepath.Abs(filepath.Join(repoRoot, ".beads", "hooks")) absSharedHooks, _ := filepath.Abs(filepath.Join(repoRoot, ".beads-hooks")) - if absCurrent == absBeadsHooks || absCurrent == absSharedHooks { + if utils.PathsEqual(absCurrent, absBeadsHooks) || utils.PathsEqual(absCurrent, absSharedHooks) { return } } @@ -1789,6 +1870,8 @@ func hookLinkedWorktreePrimaryRoot(hookRoot string) string { if hookRoot == "" { return "" } + // #nosec G702 - fixed "git" command; args are constant subcommands plus an internal + // hookRoot derived from the hook's own beads dir, never attacker-controlled input. cmd := exec.Command("git", "-C", hookRoot, "rev-parse", "--git-common-dir") // Scrub the inherited GIT_* vars so git describes hookRoot itself rather // than whatever repository GIT_DIR happens to name. diff --git a/cmd/bd/hooks_guard_test.go b/cmd/bd/hooks_guard_test.go index 4297597af..2eb7d54bb 100644 --- a/cmd/bd/hooks_guard_test.go +++ b/cmd/bd/hooks_guard_test.go @@ -10,6 +10,8 @@ import ( "github.com/steveyegge/beads/internal/git" "github.com/steveyegge/beads/internal/gitenv" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/stretchr/testify/require" ) func TestGuardHookWritePathIgnoresInheritedGitRouting(t *testing.T) { @@ -51,6 +53,7 @@ func TestGuardHookWritePathIgnoresInheritedGitRouting(t *testing.T) { name string env map[string]string }{ + {"both", map[string]string{"GIT_DIR": filepath.Join(target, ".git"), "GIT_WORK_TREE": target}}, {"repository", map[string]string{"GIT_DIR": filepath.Join(decoy, ".git")}}, {"worktree", map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy}}, {"index", map[string]string{"GIT_INDEX_FILE": filepath.Join(decoy, ".git", "index")}}, @@ -60,9 +63,16 @@ func TestGuardHookWritePathIgnoresInheritedGitRouting(t *testing.T) { for key, value := range tc.env { t.Setenv(key, value) } + if tc.name == "both" { + probe := exec.Command("git", "-C", hooksDir, "ls-files", "--error-unmatch", "--", "pre-commit") + out, err := probe.CombinedOutput() + require.NoError(t, err, "inherited index must also prove tracking: %s", out) + } if !isGitTrackedFile(foreign) { t.Error("inherited routing hid the tracked hook") } + require.Equal(t, "containing repository index", gitTrackedFileContext(foreign), "clean proof takes precedence, including when both views track it") + require.ErrorContains(t, guardHookWritePath(foreign, false), "tracked by git (containing repository index)") if err := guardHookWritePath(foreign, false); err == nil || !strings.Contains(err.Error(), "tracked by git") { t.Errorf("expected tracked-file refusal, got %v", err) } @@ -78,6 +88,7 @@ func TestGuardHookWritePathIgnoresInheritedGitRouting(t *testing.T) { if isGitTrackedFile(untracked) { t.Error("untracked hook reported as tracked") } + require.Empty(t, gitTrackedFileContext(untracked)) if err := guardHookWritePath(untracked, false); err != nil { t.Errorf("untracked hook refused: %v", err) } @@ -469,3 +480,81 @@ func TestGuardHookWritePathAllowsFileWhenGitUnavailable(t *testing.T) { t.Fatalf("both tracking errors must retain the untracked policy: %v", err) } } + +func TestInitHooksContextGuardPreservesOwnership(t *testing.T) { + for _, name := range []string{"tracked", "bd_owned", "symlink", "captured_fallback"} { + t.Run(name, func(t *testing.T) { + selected, _, _, _ := newInitHooksFixture(t) + storage := filepath.Join(selected, "local-storage") + hooksDir := filepath.Join(storage, "hooks") + if name == "captured_fallback" { + storage = t.TempDir() + hooksDir = filepath.Join(storage, "hooks") + } + require.NoError(t, os.MkdirAll(hooksDir, 0755)) + hook := filepath.Join(hooksDir, "pre-commit") + content := "#!/bin/sh\necho foreign\n" + if name == "bd_owned" { + content = "#!/bin/sh\n" + generateHookSection("pre-commit") + } + if name == "symlink" { + target := filepath.Join(t.TempDir(), "foreign hook") + require.NoError(t, os.WriteFile(target, []byte(content), 0755)) + if err := os.Symlink(target, hook); err != nil { + t.Skipf("symlink capability unavailable: %v", err) + } + } else { + require.NoError(t, os.WriteFile(hook, []byte(content), 0755)) + if name == "captured_fallback" { + bare := t.TempDir() + initExcludeGit(t, bare, "init", "--bare", "--quiet") + initExcludeGit(t, storage, "--git-dir", bare, "--work-tree", storage, "add", "hooks/pre-commit") + t.Setenv("GIT_DIR", bare) + t.Setenv("GIT_WORK_TREE", storage) + t.Setenv("GIT_INDEX_FILE", filepath.Join(bare, "index")) + } else { + initExcludeGit(t, selected, "add", "--force", "--", hook) + } + } + fs, hooks, err := withInitHooks(nil, selected, storage) + require.NoError(t, err) + if name == "captured_fallback" { + require.False(t, isGitTrackedFileWithEnv(hook, hooks.env, hooks.env), "clean view must not supply the proof") + require.True(t, isGitTrackedFileWithEnv(hook, hooks.env, hooks.inheritedEnv), "inherited view must prove tracking") + } + t.Setenv("GIT_DIR", filepath.Join(t.TempDir(), "missing")) + err = fs.InstallGitHooks(t.Context(), domain.HooksInstallParams{HookNames: managedHookNames, BeadsHooks: true}) + if name == "bd_owned" { + require.NoError(t, err) + require.Contains(t, string(readInitHooksFile(t, hook)), hookSectionBeginPrefix) + } else { + want := "tracked by git" + if name == "symlink" { + want = "symlink" + } + require.ErrorContains(t, err, want) + if name == "captured_fallback" { + require.ErrorContains(t, err, "tracked by git (inherited Git index)") + // The remediation follows the proof: `git rm --cached` from the + // operator's shell aims at whichever index that shell routes to, + // so the inherited case has to name clearing the routing instead. + require.ErrorContains(t, err, "Clear the inherited Git routing environment and re-run") + for _, entry := range hooks.inheritedEnv { + if strings.HasPrefix(entry, "GIT_DIR=") { + require.NotContains(t, err.Error(), strings.TrimPrefix(entry, "GIT_DIR=")) + } + } + } else if name == "tracked" { + require.ErrorContains(t, err, "tracked by git (containing repository index)") + require.ErrorContains(t, err, "Untrack it (git rm --cached) or move hooks to an untracked directory") + require.NotContains(t, err.Error(), "Clear the inherited Git routing environment") + } + require.Equal(t, content, string(readInitHooksFile(t, hook))) + for _, other := range []string{"post-merge", "pre-commit.backup"} { + _, err := os.Lstat(filepath.Join(hooksDir, other)) + require.ErrorIs(t, err, os.ErrNotExist) + } + } + }) + } +} diff --git a/cmd/bd/hooks_worktree_test.go b/cmd/bd/hooks_worktree_test.go index 60f9b9477..0be23661a 100644 --- a/cmd/bd/hooks_worktree_test.go +++ b/cmd/bd/hooks_worktree_test.go @@ -4,10 +4,13 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/stretchr/testify/require" ) func TestConfigureBeadsHooksPath_WorktreeUsesMainRepo(t *testing.T) { @@ -339,3 +342,145 @@ func TestConfigureBeadsHooksPath_NormalRepoUnchanged(t *testing.T) { t.Errorf("core.hooksPath = %q, want %q", hooksPath, expected) } } + +// newInitHooksFixture keeps the selected worktree, ambient repository and +// storage physically distinct. Git's default HOME is owned by the parent helper. +func newInitHooksFixture(t *testing.T) (selected, decoy, storage, common string) { + t.Helper() + selected, decoy, exclude, _ := newInitExcludeRepos(t) + common = filepath.Dir(filepath.Dir(exclude)) + storage = filepath.Join(t.TempDir(), "separate storage") + require.NoError(t, os.Mkdir(storage, 0755)) + require.NoError(t, os.WriteFile(filepath.Join(decoy, "seed"), []byte("decoy\n"), 0600)) + initExcludeGit(t, decoy, "add", "seed") + initExcludeGit(t, selected, "config", "beads.role", "contributor") + t.Setenv("BEADS_DIR", filepath.Join(decoy, ".beads")) + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + t.Setenv("GIT_WORK_TREE", decoy) + t.Setenv("GIT_INDEX_FILE", filepath.Join(decoy, ".git", "index")) + git.ResetCaches() + t.Cleanup(git.ResetCaches) + return selected, decoy, storage, common +} + +func readInitHooksFile(t *testing.T, path string) []byte { + t.Helper() + data, err := os.ReadFile(path) + require.NoError(t, err) + return data +} + +func TestInitHooksPreservesManagedDirectoryAliases(t *testing.T) { + for _, managed := range []string{".beads/hooks", ".beads-hooks"} { + t.Run(managed, func(t *testing.T) { + selected, _, storage, common := newInitHooksFixture(t) + root := filepath.Dir(common) + source := filepath.Join(root, managed) + require.NoError(t, os.MkdirAll(source, 0755)) + const content = "#!/bin/sh\necho existing managed-directory hook\n" + require.NoError(t, os.WriteFile(filepath.Join(source, "post-rewrite"), []byte(content), 0755)) + alias := filepath.Join(t.TempDir(), "repository alias") + if err := os.Symlink(root, alias); err != nil { + if runtime.GOOS == "windows" { + t.Skipf("directory symlink capability unavailable: %v", err) + } + t.Fatal(err) + } + initExcludeGit(t, selected, "config", "--local", "core.hooksPath", filepath.Join(alias, managed)) + fs, _, err := withInitHooks(nil, selected, storage) + require.NoError(t, err) + require.NoError(t, fs.InstallGitHooks(t.Context(), domain.HooksInstallParams{HookNames: managedHookNames, BeadsHooks: true})) + _, err = os.Stat(filepath.Join(storage, "hooks", "post-rewrite")) + require.ErrorIs(t, err, os.ErrNotExist, "an existing managed hooks directory must not be copied through an alias") + require.Equal(t, content, string(readInitHooksFile(t, filepath.Join(source, "post-rewrite")))) + }) + } +} + +func TestInitHooksRefusesSharedMode(t *testing.T) { + selected, _, storage, common := newInitHooksFixture(t) + fs, _, err := withInitHooks(nil, selected, storage) + require.NoError(t, err) + require.ErrorContains(t, fs.InstallGitHooks(t.Context(), domain.HooksInstallParams{HookNames: managedHookNames, Shared: true}), "shared hooks mode") + for _, path := range []string{filepath.Join(storage, "hooks"), filepath.Join(filepath.Dir(common), ".beads-hooks")} { + _, err := os.Stat(path) + require.ErrorIs(t, err, os.ErrNotExist) + } +} + +func TestInitHooksContextPreservesSelectedPaths(t *testing.T) { + for _, name := range []string{"foreign", "global", "private", "config_lock"} { + t.Run(name, func(t *testing.T) { + selected, decoy, storage, common := newInitHooksFixture(t) + current := t.TempDir() + const foreign = "#!/bin/sh\necho selected hook\n" + for _, hook := range []string{"pre-commit", "post-rewrite"} { + require.NoError(t, os.WriteFile(filepath.Join(current, hook), []byte(foreign), 0755)) + } + initExcludeGit(t, selected, "config", "--local", "core.hooksPath", current) + if name == "global" { + initExcludeGit(t, selected, "config", "--local", "--unset", "core.hooksPath") + initExcludeGit(t, selected, "config", "--global", "core.hooksPath", current) + } + preserved := map[string][]byte{} + if name == "private" { + initExcludeGit(t, selected, "config", "extensions.worktreeConfig", "true") + initExcludeGit(t, selected, "config", "--worktree", "core.hooksPath", current) + path := filepath.Join(initExcludeGit(t, selected, "rev-parse", "--absolute-git-dir"), "config.worktree") + preserved[path] = readInitHooksFile(t, path) + } + for _, path := range []string{filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "index")} { + preserved[path] = readInitHooksFile(t, path) + } + if name == "global" { + path := filepath.Join(os.Getenv("HOME"), ".gitconfig") + preserved[path] = readInitHooksFile(t, path) + } + fs, hooks, err := withInitHooks(nil, selected, storage) + require.NoError(t, err) + require.False(t, hooks.installed()) + if name == "config_lock" { + require.NoError(t, os.WriteFile(filepath.Join(common, "config.lock"), []byte("owned lock"), 0600)) + preserved[filepath.Join(common, "config")] = readInitHooksFile(t, filepath.Join(common, "config")) + } + // Later ambient routing must not rebind the captured hook operation. + t.Setenv("GIT_DIR", filepath.Join(t.TempDir(), "missing")) + t.Setenv("GIT_CONFIG_COUNT", "1") + t.Setenv("GIT_CONFIG_KEY_0", "core.hooksPath") + t.Setenv("GIT_CONFIG_VALUE_0", filepath.Join(decoy, "wrong hooks")) + env := os.Environ() + destination := filepath.Join(storage, "hooks") + for range 2 { + err := fs.InstallGitHooks(t.Context(), domain.HooksInstallParams{HookNames: managedHookNames, BeadsHooks: true}) + if name == "config_lock" { + require.ErrorContains(t, err, "failed to configure git hooks path") + } else { + require.NoError(t, err) + got := initExcludeGit(t, selected, "config", "--file", filepath.Join(common, "config"), "--get", "core.hooksPath") + gotInfo, err := os.Stat(got) + require.NoError(t, err) + wantInfo, err := os.Stat(destination) + require.NoError(t, err) + require.True(t, os.SameFile(gotInfo, wantInfo), "common config must name the installed storage hooks") + } + installed := string(readInitHooksFile(t, filepath.Join(destination, "pre-commit"))) + require.Contains(t, installed, foreign) + require.Equal(t, 1, strings.Count(installed, hookSectionBeginPrefix)) + require.Equal(t, foreign, string(readInitHooksFile(t, filepath.Join(destination, "pre-commit.backup")))) + require.Equal(t, foreign, string(readInitHooksFile(t, filepath.Join(destination, "post-rewrite")))) + } + for path, before := range preserved { + require.Equal(t, before, readInitHooksFile(t, path), "changed %s", path) + } + for _, hook := range []string{"pre-commit", "post-rewrite"} { + require.Equal(t, foreign, string(readInitHooksFile(t, filepath.Join(current, hook)))) + } + if name == "private" { + paths, err := git.ResolveHooksContext(selected, hooks.env) + require.NoError(t, err) + require.Equal(t, current, paths.HooksDir, "private override remains effective") + } + require.Equal(t, env, os.Environ()) + }) + } +} diff --git a/cmd/bd/init_git_hooks.go b/cmd/bd/init_git_hooks.go index 409d70a31..8e711b607 100644 --- a/cmd/bd/init_git_hooks.go +++ b/cmd/bd/init_git_hooks.go @@ -3,11 +3,13 @@ package main import ( "fmt" "os" + "os/exec" "path/filepath" "regexp" "strings" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/ui" ) @@ -22,6 +24,10 @@ func hooksInstalled() bool { if err != nil { return false } + return hooksInstalledAt(hooksDir) +} + +func hooksInstalledAt(hooksDir string) bool { preCommit := filepath.Join(hooksDir, "pre-commit") postMerge := filepath.Join(hooksDir, "post-merge") @@ -80,7 +86,11 @@ func hooksInstalled() bool { // Delegates to CheckGitHooks() which handles version comparison, shim detection, // and inline hook detection consistently. func hooksNeedUpdate() bool { - for _, s := range CheckGitHooks() { + return hookStatusesNeedUpdate(CheckGitHooks()) +} + +func hookStatusesNeedUpdate(statuses []HookStatus) bool { + for _, s := range statuses { if s.Outdated { return true } @@ -261,12 +271,13 @@ func buildPostMergeHook(chainHooks bool, existingHooks []hookInfo) string { return "#!/bin/sh\n" + section } +// jjHookNames is the shared inventory for standalone and selected init adapters. +var jjHookNames = []string{"pre-commit", "post-merge"} + // installJJHooks installs marker-managed hooks for colocated jujutsu+git repos. // This path intentionally avoids .old sidecar chaining and uses the same section // injection behavior as regular hook installs. func installJJHooks() error { - // jj only needs pre-commit and post-merge hooks - jjHookNames := []string{"pre-commit", "post-merge"} return installHooksWithOptions(jjHookNames, false, false, false, false) } @@ -310,3 +321,64 @@ func printJJAliasInstructions() { fmt.Printf("\nThen use %s instead of %s\n\n", ui.RenderAccent("jj push"), ui.RenderAccent("jj git push")) fmt.Printf("For more details, see: https://github.com/gastownhall/beads/blob/main/docs/reference/git-integration.md#branchless-workflows-jujutsu--jj\n\n") } + +// initHooksContext keeps the selected Git project separate from Beads storage. +// Its paths and both environments are captured once; tracking fallback supplies +// refusal evidence only, never a destination for writing hooks or configuration. +type initHooksContext struct { + workDir, beadsDir string + paths git.HooksContext + env, inheritedEnv []string +} + +func resolveInitHooksContext(workDir, beadsDir string) (*initHooksContext, error) { + workDir, err := filepath.Abs(workDir) + if err != nil { + return nil, err + } + inherited := os.Environ() + env := gitenv.ScrubRouting(inherited) + paths, err := git.ResolveHooksContext(workDir, env) + if err != nil { + // A repository whose work tree does not resolve -- a bare repository, or + // a directory such as /.git that Git answers from -- has no work + // tree to anchor, but it does have a hooks directory, and bd installed + // into it before this resolver existed. Resolving that shape here keeps + // the selected, scrubbed context instead of turning a supported + // repository into a warning and no install at all. Any other failure is + // still a failure: the work-tree-less resolver rejects non-repositories + // and directories inside a work tree. + workTreeless, workTreelessErr := git.ResolveWorkTreelessHooksContext(workDir, env) + if workTreelessErr != nil { + return nil, err + } + paths = workTreeless + } + if beadsDir != "" && !filepath.IsAbs(beadsDir) { + beadsDir = filepath.Join(workDir, beadsDir) + } + return &initHooksContext{workDir: workDir, beadsDir: beadsDir, paths: paths, env: env, inheritedEnv: inherited}, nil +} + +func (c *initHooksContext) installed() bool { + if c == nil { + return hooksInstalled() + } + return hooksInstalledAt(c.paths.HooksDir) +} + +func (c *initHooksContext) needsUpdate() bool { + if c == nil { + return hooksNeedUpdate() + } + return hookStatusesNeedUpdate(checkGitHooksAt(c.paths.HooksDir)) +} + +func (c *initHooksContext) configureHooksPath(hooksDir string) error { + cmd := exec.Command("git", "--git-dir", c.paths.CommonDir, "config", "--local", "core.hooksPath", hooksDir) + cmd.Dir, cmd.Env = c.workDir, c.env + if output, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("git config failed: %w (output: %s)", err, string(output)) + } + return nil +} diff --git a/cmd/bd/init_proxied_server.go b/cmd/bd/init_proxied_server.go index d0cf6674e..2d101e51f 100644 --- a/cmd/bd/init_proxied_server.go +++ b/cmd/bd/init_proxied_server.go @@ -580,33 +580,41 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr } } - if !in.skipHooks && (!hooksInstalled() || hooksNeedUpdate()) { - if hooksInstalled() && !in.quiet { - fmt.Printf(" Updating hooks to version %s...\n", Version) - } + if !in.skipHooks { isJJ := gitUC.IsJujutsuRepo(ctx) isColocated := gitUC.IsColocatedJJGit(ctx) switch { case isJJ && !isColocated: - if !in.quiet { + // The install arm below took over the hook-status gate that used to + // wrap this whole switch. Keep it here too, or a pure-JJ repo with + // current hooks starts re-printing the alias hint on every init. + if !in.quiet && (!hooksInstalled() || hooksNeedUpdate()) { printJJAliasInstructions() } - case isColocated: - if err := t.fsUseCase.InstallJJHooks(ctx); err != nil && !in.quiet { - fmt.Fprintf(os.Stderr, "\n%s Failed to install jj hooks: %v\n", ui.RenderWarn("⚠"), err) - } else if !in.quiet { - fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n") - } - default: - if isRepo { - hooksParams := domain.HooksInstallParams{ - HookNames: managedHookNames, - BeadsHooks: true, + case isColocated || isRepo: + // Resolve only an eligible Git branch, never skip/pure-JJ/nonrepo paths. + hookFS, hooks, err := withInitHooks(t.fsUseCase, t.workDir, t.beadsDir) + if err != nil { + if !in.quiet { + fmt.Fprintf(os.Stderr, "\n%s Failed to resolve git hooks: %v\n", ui.RenderWarn("⚠"), err) } - if err := t.fsUseCase.InstallGitHooks(ctx, hooksParams); err != nil && !in.quiet { - fmt.Fprintf(os.Stderr, "\n%s Failed to install git hooks to .beads/hooks/: %v\n", ui.RenderWarn("⚠"), err) - } else if !in.quiet { - fmt.Printf(" Hooks installed to: .beads/hooks/\n") + } else if !hooks.installed() || hooks.needsUpdate() { + if hooks.installed() && !in.quiet { + fmt.Printf(" Updating hooks to version %s...\n", Version) + } + if isColocated { + if err := hookFS.InstallJJHooks(ctx); err != nil && !in.quiet { + fmt.Fprintf(os.Stderr, "\n%s Failed to install jj hooks: %v\n", ui.RenderWarn("⚠"), err) + } else if !in.quiet { + fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n") + } + } else { + hooksParams := domain.HooksInstallParams{HookNames: managedHookNames, BeadsHooks: true} + if err := hookFS.InstallGitHooks(ctx, hooksParams); err != nil && !in.quiet { + fmt.Fprintf(os.Stderr, "\n%s Failed to install git hooks to .beads/hooks/: %v\n", ui.RenderWarn("⚠"), err) + } else if !in.quiet { + fmt.Printf(" Hooks installed to: .beads/hooks/\n") + } } } } diff --git a/cmd/bd/init_proxied_server_test.go b/cmd/bd/init_proxied_server_test.go index 1c4c6060f..df567f04c 100644 --- a/cmd/bd/init_proxied_server_test.go +++ b/cmd/bd/init_proxied_server_test.go @@ -572,3 +572,122 @@ func TestProxiedInitExcludeUsesSelectedDirectory(t *testing.T) { }) } } + +func TestProxiedInitHooksUseSelectedContext(t *testing.T) { + for _, name := range []string{"normal", "missing", "outdated", "current", "skip", "nonrepo", "pure_jj", "colocated", "bare", "git_dir_cwd", "config_lock", "quiet_config_lock"} { + t.Run(name, func(t *testing.T) { + selected, decoy, storage, common := newInitHooksFixture(t) + // Repository shapes whose common directory resolves while no work tree + // does; both must still install, as bd did before the hooks resolver. + workTreeless := name == "bare" || name == "git_dir_cwd" + if name == "normal" { + selected = filepath.Dir(common) + } + if name == "bare" { + selected = t.TempDir() + initExcludeGit(t, selected, "init", "--bare", "--quiet") + } + if name == "git_dir_cwd" { + // Standing in a non-bare repository's own .git directory: rev-parse + // --git-dir answers, so the repository arm runs, but --show-toplevel + // fails and --is-bare-repository reports false. + repo := t.TempDir() + initExcludeGit(t, repo, "init", "--quiet") + selected = filepath.Join(repo, ".git") + } + current, ambient := t.TempDir(), t.TempDir() + initExcludeGit(t, selected, "config", "core.hooksPath", current) + initExcludeGit(t, decoy, "config", "core.hooksPath", ambient) + writeHooks := func(dir string, outdated bool) { + for _, hook := range []string{"pre-commit", "post-merge"} { + text := "#!/bin/sh\n" + generateHookSection(hook) + if outdated { + text = "#!/bin/sh\n# bd (beads) " + hook + " hook\n# Version: obsolete\n" + } + require.NoError(t, os.WriteFile(filepath.Join(dir, hook), []byte(text), 0755)) + } + } + if name == "current" || name == "outdated" { + writeHooks(current, name == "outdated") + } + if name != "current" { + writeHooks(ambient, false) + } + // Filesystems without executable mode bits retain the existing reinstall policy. + currentReady := false + if name == "current" { + info, err := os.Stat(filepath.Join(current, "pre-commit")) + require.NoError(t, err) + currentReady = info.Mode().Perm()&0111 != 0 + if runtime.GOOS != "windows" { + require.True(t, currentReady, "POSIX current-status fixture requires executable hooks") + } + } + preserved := map[string][]byte{} + for _, path := range []string{filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "index")} { + preserved[path] = readInitHooksFile(t, path) + } + if name == "nonrepo" || name == "pure_jj" { + selected = t.TempDir() + } + if name == "pure_jj" || name == "colocated" { + require.NoError(t, os.Mkdir(filepath.Join(selected, ".jj"), 0755)) + } + locked := name == "config_lock" || name == "quiet_config_lock" + if locked { + require.NoError(t, os.WriteFile(filepath.Join(common, "config.lock"), []byte("owned lock"), 0600)) + } + fs := storagefs.NewFileSystemProvider(selected, newBeadsDirTemplates(), newInitFileSystemAdapters(selected)).BeadsDirFSUseCase() + cmd := &cobra.Command{} + cmd.Flags().Bool("setup-exclude", true, "") + in := initProxiedServerInput{skipHooks: name == "skip", quiet: name == "quiet_config_lock", skipAgents: true, nonInteractive: true} + env := os.Environ() + stderr := captureStderr(t, func() { + require.NoError(t, runInitProxiedServerTail(cmd, t.Context(), in, runInitTailContext{workDir: selected, beadsDir: storage, remoteURL: "file:///unused-hooks-fixture-remote", fsUseCase: fs, gitUC: storagegit.NewGitProvider(selected).GitUseCase()})) + }) + if name == "config_lock" { + require.Contains(t, stderr, "Failed to install git hooks") + } else if name != "nonrepo" && name != "pure_jj" { + require.Empty(t, stderr) + } + require.NotContains(t, stderr, "Failed to resolve git hooks") + wantInstall := name == "normal" || name == "missing" || name == "outdated" || name == "colocated" || workTreeless || locked || (name == "current" && !currentReady) + path := filepath.Join(storage, "hooks", "pre-commit") + if name == "colocated" { + path = filepath.Join(current, "pre-commit") + } + if wantInstall { + require.Contains(t, string(readInitHooksFile(t, path)), hookSectionBeginPrefix) + } else { + _, err := os.Stat(path) + require.ErrorIs(t, err, os.ErrNotExist, "ambient status must not trigger an install") + } + if workTreeless { + // These resolve through the work-tree-less hooks context, so the + // install must still land in the selected storage and configure the + // selected repository -- not the inherited one this fixture routes to. + require.Equal(t, filepath.Join(storage, "hooks"), initExcludeGit(t, selected, "config", "--local", "--get", "core.hooksPath")) + } + if name != "nonrepo" && name != "pure_jj" { + excludeRoot := common + if workTreeless { + excludeRoot = selected // a work-tree-less selection is its own common directory + } + exclude := readInitHooksFile(t, filepath.Join(excludeRoot, "info", "exclude")) + require.Contains(t, string(exclude), ".beads/", "selected exclude callback lost") + } + for path, before := range preserved { + require.Equal(t, before, readInitHooksFile(t, path), "changed %s", path) + } + require.Equal(t, env, os.Environ()) + }) + } +} + +func TestInitHooksEmptyPathRetainsUseCase(t *testing.T) { + supplied := &initTailForkObservation{} + fs, hooks, err := withInitHooks(supplied, "", "unused storage") + require.NoError(t, err) + require.Same(t, supplied, fs) + require.Nil(t, hooks) +} diff --git a/cmd/bd/worktree.go b/cmd/bd/worktree.go index 20baf1b07..73e80f3a8 100644 --- a/cmd/bd/worktree.go +++ b/cmd/bd/worktree.go @@ -19,6 +19,8 @@ func isGitWorktree() bool { // gitRevParse runs git rev-parse with the given flag and returns the trimmed output. // This is a helper for CLI utilities that need git command execution. func gitRevParse(flag string) string { + // #nosec G702 - fixed "git" command; flag is a constant rev-parse switch chosen by + // the caller in this package, never attacker-controlled input. out, err := exec.Command("git", "rev-parse", flag).Output() if err != nil { return "" diff --git a/cmd/bd/worktree_cmd.go b/cmd/bd/worktree_cmd.go index 74a09ca99..d4b123f5e 100644 --- a/cmd/bd/worktree_cmd.go +++ b/cmd/bd/worktree_cmd.go @@ -688,12 +688,14 @@ func scrubWorktreeRemovalGitEnvForOS(env []string, goos string) []string { // ScrubRoutingForOS returns a fresh slice, so filtering it in place is safe. result := cleaned[:0] for _, entry := range cleaned { + // One shared subprocess key identity: execenv mirrors os/exec's fold, so + // this drops exactly the entries a child process would treat as these two + // variables -- an independent fold here would diverge from that rule. + // ToUpper is not that rule; the two disagree in both directions for + // non-ASCII keys on Windows: ToUpper leaves GİT_OPTIONAL_LOCKS unmatched + // although Git honors it, and folds GIT_OPTIONAL_LOCKſ onto the literal + // although os/exec keeps it distinct. key := worktreeGitEnvKey(entry) - // Key identity is the subprocess lookup rule (execenv), not ToUpper. - // The two disagree in both directions for non-ASCII keys on Windows: - // ToUpper leaves GİT_OPTIONAL_LOCKS unmatched although Git honors it, - // and folds GIT_OPTIONAL_LOCKſ onto the literal although os/exec keeps - // it distinct. if execenv.KeyEqualForOS(key, "GIT_NO_REPLACE_OBJECTS", goos) || execenv.KeyEqualForOS(key, "GIT_OPTIONAL_LOCKS", goos) { continue diff --git a/docs/reference/worktrees.md b/docs/reference/worktrees.md index 2adc406ee..03d63a352 100644 --- a/docs/reference/worktrees.md +++ b/docs/reference/worktrees.md @@ -15,15 +15,21 @@ override discovery with `BEADS_DIR`. Startup *config* discovery — the `rev-parse` probe in `internal/config`'s `gitDirsForRepo`, which locates a linked worktree's shared `.beads` config — scrubs inherited Git routing variables such as `GIT_DIR` and `GIT_WORK_TREE` -from its subprocess environment whenever it runs. The scrub is unconditional for -that probe, but the probe is a fallback, not a per-command step: it runs only -when nothing earlier in startup has already resolved a config path -(`internal/config/config.go`), so an ancestor `.beads/config.yaml` or an -explicit `BEADS_DIR` short-circuits it. Other startup Git probes still honor -inherited routing, including `internal/git`'s process-cached repository context -and the `.beads` database discovery probes in `internal/beads`, so those -variables can still select which workspace `bd` opens. Clearing those variables -from the `bd` process environment applies only to `bd worktree` commands. +from its subprocess environment whenever it runs, so a routed environment cannot +point that one lookup at another repository. The scrub is unconditional for that +probe, but the probe is a fallback, not a per-command step: it runs only when +nothing earlier in startup has already resolved a config path +(`internal/config/config.go`), so an ancestor `.beads/config.yaml` or an explicit +`BEADS_DIR` short-circuits it. It is a single probe, not a general guarantee: +other startup Git probes still honor inherited routing, including `internal/git`'s +process-cached repository context backing repository-root and hooks-directory +lookups and the `.beads` database discovery probes in `internal/beads`, so those +variables can still select which workspace `bd` opens. Scrubbing also drops any +inherited `GIT_CEILING_DIRECTORIES`, which *widens* upward discovery rather than +narrowing it: the explicit working directory fixes where that probe's search +starts, not where it stops, so the probe can select a containing parent +repository above that directory. Clearing those variables from the `bd` process +environment applies only to `bd worktree` commands. `GIT_CEILING_DIRECTORIES` is scrubbed along with the redirects. That removes a *bound* rather than a redirect, so discovery from the working directory is diff --git a/internal/config/config.go b/internal/config/config.go index d3c0a12a9..f6d5379f6 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -436,7 +436,13 @@ func gitDirsForRepo(repoPath string) (gitDir, commonDir string, ok bool) { cmd := exec.Command("git", "-C", repoPath, "rev-parse", "--git-dir", "--git-common-dir") // repoPath is the authority for this probe. Inherited Git routing such as // GIT_DIR overrides -C and can make startup read another repository's - // shared-worktree config before command dispatch has begun. + // shared-worktree config before command dispatch has begun. Scrubbing also + // drops an inherited GIT_CEILING_DIRECTORIES, which widens rather than + // narrows discovery: -C repoPath fixes where the search starts, not where it + // stops, so dropping discovery ceilings can select a containing parent + // repository above repoPath. That is the intended trade, and it applies here + // too -- repoPath is the process working directory, not a proven repository + // root. cmd.Env = gitenv.ScrubRouting(os.Environ()) output, err := cmd.Output() if err != nil { diff --git a/internal/config/git_routing_test.go b/internal/config/git_routing_test.go index 2f56defa7..e2b6fb59c 100644 --- a/internal/config/git_routing_test.go +++ b/internal/config/git_routing_test.go @@ -129,6 +129,56 @@ func TestSecretGitTrackingIgnoresInheritedGitRouting(t *testing.T) { } } +// A checkout reachable only through inherited Git routing is the case a +// scrubbed-only probe cannot see at all: it finds no repository, reports +// "untracked", and the fail-open guard writes the secret into a tracked +// config.yaml. The inherited fallback is what keeps the refusal working there. +func TestSecretGitTrackingHonorsLegitimateGitRouting(t *testing.T) { + gitDir, work := t.TempDir(), t.TempDir() + routedGit := func(args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = work + cmd.Env = append(gitenv.ScrubRouting(os.Environ()), "GIT_DIR="+gitDir, "GIT_WORK_TREE="+work) + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("routed git %v: %v\n%s", args, err, output) + } + } + routedGit("init", "--quiet") + tracked := filepath.Join(work, "config.yaml") + untracked := filepath.Join(work, "untracked.yaml") + for _, path := range []string{tracked, untracked} { + if err := os.WriteFile(path, []byte("json: false\n"), 0o600); err != nil { + t.Fatal(err) + } + } + routedGit("add", "--", tracked) + + // The work tree holds no .git entry, so the scrubbed probe must fail here. + // Without this precondition the inherited fallback could pass vacuously. + scrubbed := exec.Command("git", "ls-files", "--error-unmatch", tracked) + scrubbed.Dir = work + scrubbed.Env = gitenv.ScrubRouting(os.Environ()) + if scrubbed.Run() == nil { + t.Fatal("scrubbed probe already resolves the routed checkout; fixture proves nothing") + } + + t.Setenv("GIT_DIR", gitDir) + t.Setenv("GIT_WORK_TREE", work) + if !isGitTracked(tracked) { + t.Error("legitimate routing hid the tracked file from the secret guard") + } + if isGitTracked(untracked) { + t.Error("untracked file reported as tracked") + } + if err := checkSecretGitTracked(tracked, "linear.api_key"); err == nil || !strings.Contains(err.Error(), "refusing to write secret key") { + t.Errorf("tracked secret refusal = %v", err) + } + if err := checkSecretGitTracked(untracked, "linear.api_key"); err != nil { + t.Errorf("untracked secret refused: %v", err) + } +} + // A bare repository whose work tree is named only by GIT_DIR/GIT_WORK_TREE is // invisible to the scrubbed probe — it is reachable through the inherited // routing alone. The secret guard must still refuse a write into the tracked diff --git a/internal/git/gitdir.go b/internal/git/gitdir.go index 5e1825f75..681b2c035 100644 --- a/internal/git/gitdir.go +++ b/internal/git/gitdir.go @@ -120,6 +120,30 @@ type HooksContext struct { HooksDir, CommonDir, RepoRoot, MainRepoRoot string } +// normalizeHooksWorkDir anchors workDir and normalizes its symlinks and case +// once. Every HooksContext producer shares it so they cannot drift into emitting +// different spellings of the same directory: worktree code string-compares these +// paths (GH#880). +// The caller-supplied directory must resolve before it can select a repo: +// unlike the discovered repoRoot spelling in loadGitContext, it is an input +// to Git. +func normalizeHooksWorkDir(workDir string) (string, error) { + workDir, err := filepath.Abs(workDir) + if err != nil { + return "", err + } + // This caller-supplied directory must resolve before it can select a repo. + // Unlike the discovered repoRoot spelling, it is an input to Git. + workDir, err = filepath.EvalSymlinks(workDir) + if err != nil { + return "", fmt.Errorf("resolve hooks working directory: %w", err) + } + if canonical := canonicalizeCase(workDir); canonical != "" { + workDir = canonical + } + return workDir, nil +} + // ResolveHooksContext reads fresh paths without changing the legacy cache. // workDir must be nonempty and is anchored and symlink/case-normalized once; // bare/non-repositories error. Configured absolute hook paths retain their spelling. @@ -132,26 +156,15 @@ type HooksContext struct { // // This is the explicit-context sibling of GetGitHooksDir. It returns a struct // instead of following this file's GetXFrom(startDir) convention because all -// four paths must come from one resolution of one directory. The first in-repo -// caller arrives with GH#6440, so at this commit only tests exercise the -// contract above. +// four paths must come from one resolution of one directory. func ResolveHooksContext(workDir string, env []string) (HooksContext, error) { if workDir == "" { return HooksContext{}, fmt.Errorf("hooks context requires a working directory") } - workDir, err := filepath.Abs(workDir) + workDir, err := normalizeHooksWorkDir(workDir) if err != nil { return HooksContext{}, err } - // This caller-supplied directory must resolve before it can select a repo. - // Unlike the discovered repoRoot spelling above, it is an input to Git. - workDir, err = filepath.EvalSymlinks(workDir) - if err != nil { - return HooksContext{}, fmt.Errorf("resolve hooks working directory: %w", err) - } - if canonical := canonicalizeCase(workDir); canonical != "" { - workDir = canonical - } ctx := loadGitContext(workDir, env) if ctx.err != nil { return HooksContext{}, ctx.err @@ -166,6 +179,58 @@ func ResolveHooksContext(workDir string, env []string) (HooksContext, error) { RepoRoot: ctx.repoRoot, MainRepoRoot: ctx.mainRepoRoot()}, nil } +// ResolveWorkTreelessHooksContext resolves hook paths for a repository whose +// common directory resolves but whose work tree does not: a bare repository, or +// a directory such as a repository's own .git that Git answers from while +// reporting no work tree. ResolveHooksContext requires one, because it cannot +// honor its RepoRoot contract without it; this is the explicit counterpart, so a +// caller opts into the weaker shape instead of silently receiving one. RepoRoot +// and MainRepoRoot are empty — there is no work-tree root — and a relative +// core.hooksPath is anchored to the common directory, which is where Git runs +// hooks without a work tree. +// It fails for non-repositories and for directories inside a work tree alike, so +// callers can use it as a fallback after ResolveHooksContext without widening +// that call's failure contract. workDir and env are handled exactly as +// ResolveHooksContext handles them, anchoring and normalization included. +func ResolveWorkTreelessHooksContext(workDir string, env []string) (HooksContext, error) { + if workDir == "" { + return HooksContext{}, fmt.Errorf("hooks context requires a working directory") + } + workDir, err := normalizeHooksWorkDir(workDir) + if err != nil { + return HooksContext{}, err + } + probe := exec.Command("git", "rev-parse", "--is-inside-work-tree", "--git-common-dir") + probe.Dir, probe.Env = workDir, env + output, err := probe.Output() + if err != nil { + return HooksContext{}, fmt.Errorf("resolve work-tree-less Git repository: %w", err) + } + lines := strings.Split(strings.TrimSpace(string(output)), "\n") + if len(lines) < 2 { + return HooksContext{}, fmt.Errorf("unexpected git rev-parse output: got %d lines, expected 2", len(lines)) + } + // A work tree resolves here, so ResolveHooksContext's stronger contract is + // the one that applies and its error is the one the caller should surface. + if strings.TrimSpace(lines[0]) == "true" { + return HooksContext{}, fmt.Errorf("%s is inside a Git work tree", workDir) + } + commonDir, err := absoluteGitPath(workDir, strings.TrimSpace(lines[1])) + if err != nil { + return HooksContext{}, fmt.Errorf("failed to resolve common dir path: %w", err) + } + cmd := exec.Command("git", "config", "--get", "core.hooksPath") + cmd.Dir, cmd.Env = workDir, env + // Without a work tree Git runs hooks in the common directory, so it anchors a + // relative core.hooksPath in place of the absent work-tree root. + ctx := gitContext{gitDirRaw: commonDir, commonDir: commonDir, repoRoot: commonDir} + hooksDir, err := gitHooksDir(cmd, func() (*gitContext, error) { return &ctx, nil }) + if err != nil { + return HooksContext{}, err + } + return HooksContext{HooksDir: hooksDir, CommonDir: commonDir}, nil +} + // getGitContext returns the cached git context, initializing it if needed. func getGitContext() (*gitContext, error) { gitCtxOnce.Do(initGitContext) diff --git a/internal/gitenv/routing.go b/internal/gitenv/routing.go index 44951645e..c54cf25a8 100644 --- a/internal/gitenv/routing.go +++ b/internal/gitenv/routing.go @@ -59,7 +59,10 @@ func EntryKey(entry string) string { // repository the caller is standing in, which is the same loss of working- // directory authority. Removing it therefore widens the upward search as well, // so a caller whose working directory is not itself a repository can resolve a -// containing one. +// containing one. That is the intended trade, and pinning an explicit working +// directory does not opt out of it: -C or cmd.Dir fixes where the search +// starts, not where it stops, so once the ceiling is gone the walk above that +// directory is unbounded. func IsRoutingKeyForOS(key, goos string) bool { keys := routingKeys prefix := "GIT_CONFIG" diff --git a/internal/storage/domain/git/git.go b/internal/storage/domain/git/git.go index 2cbc4a9fa..145bb0488 100644 --- a/internal/storage/domain/git/git.go +++ b/internal/storage/domain/git/git.go @@ -129,7 +129,13 @@ func (r *gitRepositoryImpl) GetConfig(ctx context.Context, key string) (string, return "", false, fmt.Errorf("git: GetConfig: key must not be empty") } cmd := r.gitCmd(ctx, "config", "--get", key) - if key == domain.BeadsRoleConfigKey { + // Git config key names are case-insensitive, so match its rule: a caller + // spelling "Beads.Role" reads the same key and must take the same + // role-authority environment, not slip through on the inherited one. ToLower + // rather than EqualFold, following execenv.keyIdentityForWindows: EqualFold + // also collapses Unicode near-collisions such as s and ſ, while git folds + // ASCII only and rejects beadſ.role as an invalid key. + if strings.ToLower(key) == domain.BeadsRoleConfigKey { cmd.Env = r.roleAuthorityEnv() } out, err := cmd.Output() @@ -156,7 +162,10 @@ func (r *gitRepositoryImpl) SetConfig(ctx context.Context, key, value string) er return fmt.Errorf("git: SetConfig: key must not be empty") } cmd := r.gitCmd(ctx, "config", key, value) - if key == domain.BeadsRoleConfigKey { + // Case-insensitive for the same reason as GetConfig, and with the same + // ToLower rule: git resolves key names case-insensitively over ASCII, so + // every spelling must take the role-authority environment. + if strings.ToLower(key) == domain.BeadsRoleConfigKey { cmd.Env = r.roleAuthorityEnv() } out, err := cmd.CombinedOutput() diff --git a/internal/storage/domain/git/git_test.go b/internal/storage/domain/git/git_test.go index 87a719a26..5d5c1bb85 100644 --- a/internal/storage/domain/git/git_test.go +++ b/internal/storage/domain/git/git_test.go @@ -116,20 +116,40 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() { s.Require().NoError(roleErr) s.False(found) } - if tc.name == "invalid_routing_boolean" { - // The same poison that fails the read above cannot reach beads.role, - // which resolves as absent rather than as a preserved read failure. - role, roleFound, roleErr := s.repo.GetConfig(s.Ctx(), "beads.role") - s.Require().NoError(roleErr) - s.False(roleFound) - s.Empty(role) - _, _, useCaseErr := domain.NewGitUseCase(s.tmpDir, s.repo).BeadsRole(s.Ctx()) - s.Require().NoError(useCaseErr) - } }) } } +// TestConfig_ReadFailuresAreNotMissing's "invalid_routing_boolean" row used to +// poison GIT_CONFIG_NOSYSTEM and expect the beads.role read to fail. beads.role +// reads now scrub inherited suppression, so that poison never reaches git for +// this key; that row therefore reads a key which still inherits it (core.bare) +// and asserts the role read's immunity alongside. This test covers the half that +// row cannot: under the same poison, the role read returns the value it was +// given rather than merely resolving as absent. +func (s *testSuite) TestConfig_BeadsRoleScrubsInheritedRoutingEnv() { + s.gitInit() + s.Require().NoError(s.repo.SetConfig(s.Ctx(), "beads.role", "maintainer")) + s.T().Setenv("GIT_CONFIG_NOSYSTEM", "not-a-boolean") + + // beads.role is read with routing scrubbed, so the poisoned value is gone + // before git parses its environment. + value, found, err := s.repo.GetConfig(s.Ctx(), "beads.role") + s.Require().NoError(err) + s.True(found) + s.Equal("maintainer", value) + + // Keys outside that scrub keep the inherited environment, so the same poison + // still surfaces as a read error rather than as an absent key. + value, found, err = s.repo.GetConfig(s.Ctx(), "user.name") + s.Require().Error(err) + s.False(found) + s.Empty(value) + var exitErr *exec.ExitError + s.Require().ErrorAs(err, &exitErr) + s.Equal(128, exitErr.ExitCode()) +} + // Regression guard: pre-canceled contexts already propagated before the config fix. func (s *testSuite) TestConfig_CancellationIsNotMissing() { ctx, cancel := context.WithCancel(s.Ctx()) @@ -402,6 +422,56 @@ func TestRoleConfigIgnoresInheritedGitRouting(t *testing.T) { } } +// TestRoleConfigKeySpellingTakesScrubbedPath pins the case-insensitive key +// match. Git resolves config key names case-insensitively, so every spelling of +// beads.role must take the scrubbed path; a byte-exact compare would let +// "Beads.Role" read and write whichever repository inherited routing selects. +func TestRoleConfigKeySpellingTakesScrubbedPath(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + require.NoError(t, os.Unsetenv(key)) + } + } + home := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + runGit := func(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ()) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "fixture git %v: %s", args, out) + return strings.TrimSpace(string(out)) + } + // The canonical spelling is the control: it takes the scrubbed path under + // either comparator, so it proves the fixture routes as intended rather than + // the assertions passing vacuously. + for _, key := range []string{"beads.role", "Beads.Role", "BEADS.ROLE"} { + t.Run(key, func(t *testing.T) { + target, decoy := t.TempDir(), t.TempDir() + for _, dir := range []string{target, decoy} { + runGit(t, dir, "init", "--quiet") + } + runGit(t, target, "config", "--local", "beads.role", "target-role") + runGit(t, decoy, "config", "--local", "beads.role", "decoy-role") + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + t.Setenv("GIT_WORK_TREE", decoy) + repo := NewGitRepository(target) + got, found, err := repo.GetConfig(t.Context(), key) + require.NoError(t, err) + require.True(t, found) + require.Equal(t, "target-role", got, "%s read through inherited routing", key) + require.NoError(t, repo.SetConfig(t.Context(), key, "written-role")) + require.Equal(t, "written-role", runGit(t, target, "config", "--local", "--get", "beads.role")) + require.Equal(t, "decoy-role", runGit(t, decoy, "config", "--local", "--get", "beads.role"), + "%s write escaped to the inherited repository", key) + }) + } +} + func TestInitGitRepositoryUsesSelectedDirectory(t *testing.T) { for _, entry := range os.Environ() { key := gitenv.EntryKey(entry) @@ -473,12 +543,18 @@ func TestInitGitRepositoryUsesSelectedDirectory(t *testing.T) { for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { t.Setenv(key, changedHome) } + // gastownhall/beads#6477 made the reader propagate Git's exit + // error instead of mapping it to absence, so the generic + // constructor now surfaces the changed HOME's broken .gitconfig + // rather than reporting the key missing. changedHome is the only + // HOME here holding a .gitconfig, so Git's refusal to parse that + // file is itself the proof that generic role reads still use the + // current caller environment rather than a captured one. role, found, err := inherited.GetConfig(t.Context(), "beads.role") - // changedHome is the only HOME here holding a .gitconfig, so Git's - // refusal to parse that file is what proves the generic reader used - // the current caller environment rather than a captured one. The - // reader surfaces such read failures instead of reporting absence. require.Error(t, err, "generic role reads still use the current caller environment") + var inheritedExit *exec.ExitError + require.ErrorAs(t, err, &inheritedExit) + require.Equal(t, 128, inheritedExit.ExitCode()) require.ErrorContains(t, err, ".gitconfig") require.False(t, found) require.Empty(t, role)