diff --git a/cmd/bd/config_show.go b/cmd/bd/config_show.go index 5083a0ae5..95bb5eadd 100644 --- a/cmd/bd/config_show.go +++ b/cmd/bd/config_show.go @@ -11,6 +11,7 @@ import ( "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/workapi" ) @@ -334,6 +335,7 @@ func collectGitConfigEntries() []configEntry { // beads.role is the only git config key currently cmd := exec.Command("git", "config", "--get", "beads.role") + cmd.Env = gitenv.ScrubRouting(os.Environ()) output, err := cmd.Output() if err == nil { value := strings.TrimSpace(string(output)) diff --git a/cmd/bd/config_show_test.go b/cmd/bd/config_show_test.go index 4e409ee32..fafd11cf8 100644 --- a/cmd/bd/config_show_test.go +++ b/cmd/bd/config_show_test.go @@ -3,11 +3,14 @@ package main import ( "encoding/json" "os" + "os/exec" "path/filepath" + "runtime" "strings" "testing" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/gitenv" ) // TestViperSourceLabel verifies source label formatting for different config sources. @@ -434,3 +437,79 @@ func TestCollectViperEntriesMetricsUserGlobalProvenance(t *testing.T) { t.Errorf("config show --json entry %s misattributes user-global value to project config.yaml", encoded) } } + +func TestCollectGitConfigEntriesIgnoresInheritedRouting(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } + } + pinJSONOutput(t, false) + runGit := func(t *testing.T, repo string, args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = repo + cmd.Env = gitenv.ScrubRouting(os.Environ()) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("fixture git %v: %v: %s", args, err, out) + } + } + for _, tc := range []struct { + name, local, global, want string + }{ + {"repository", "maintainer", "", "maintainer"}, + {"inline", "maintainer", "", "maintainer"}, + {"default_global", "", "contributor", "contributor"}, + {"absent", "", "", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + home, target, decoy := t.TempDir(), t.TempDir(), t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + if tc.global != "" { + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\nrole = "+tc.global+"\n"), 0o600); err != nil { + t.Fatal(err) + } + } + for _, repo := range []string{target, decoy} { + runGit(t, repo, "init", "--quiet") + } + runGit(t, decoy, "config", "beads.role", "decoy-role") + if tc.local != "" { + runGit(t, target, "config", "beads.role", tc.local) + } + t.Chdir(target) + poison := map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "beads.role", "GIT_CONFIG_VALUE_0": "injected-role"} + if tc.name == "repository" { + poison = map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy} + } + for key, value := range poison { + t.Setenv(key, value) + } + entries := collectGitConfigEntries() + wantGet := tc.want + if tc.want == "" { + wantGet = "beads.role (not set in git config)" + if len(entries) != 0 { + t.Errorf("absent role produced entries: %+v", entries) + } + } else if len(entries) != 1 || entries[0] != (configEntry{Key: "beads.role", Value: tc.want, Source: "git"}) { + t.Errorf("Git entries = %+v; want role=%q with source=git", entries, tc.want) + } + out := captureStdout(t, func() error { return configGetCmd.RunE(configGetCmd, []string{"beads.role"}) }) + if strings.TrimSpace(out) != wantGet { + t.Errorf("config get = %q; want %q", out, wantGet) + } + for key, value := range poison { + if os.Getenv(key) != value { + t.Errorf("reader changed parent environment %s", key) + } + } + }) + } +} diff --git a/cmd/bd/doctor/bare_parent_fallback_test.go b/cmd/bd/doctor/bare_parent_fallback_test.go index 888196490..0d8387fbe 100644 --- a/cmd/bd/doctor/bare_parent_fallback_test.go +++ b/cmd/bd/doctor/bare_parent_fallback_test.go @@ -4,9 +4,11 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/utils" ) @@ -155,3 +157,66 @@ func runGitInDirForDoctorTest(t *testing.T, dir string, args ...string) string { return strings.TrimSpace(string(output)) } + +func TestDoctorWorktreeFallbackIgnoresInheritedRouting(t *testing.T) { + clearResolveBeadsDirCache() + t.Cleanup(clearResolveBeadsDirCache) + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } + } + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, t.TempDir()) + } + // Production ScrubRouting removes this flag; it does not suppress system config there. + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + targetParent, target := setupBareParentWorktreeForDoctorTest(t) + decoyParent, decoy := setupBareParentWorktreeForDoctorTest(t) + want := utils.CanonicalizePath(filepath.Join(targetParent, ".beads")) + for _, dir := range []string{want, filepath.Join(decoyParent, ".beads")} { + if err := os.MkdirAll(dir, 0o750); err != nil { + t.Fatal(err) + } + } + if _, err := os.Stat(filepath.Join(target, ".beads")); !os.IsNotExist(err) { + t.Fatalf("fixture must require common-parent fallback: %v", err) + } + decoyGitDir := runGitInDirForDoctorTest(t, decoy, "rev-parse", "--absolute-git-dir") + for _, name := range []string{"decoy", "invalid_git_dir"} { + t.Run(name, func(t *testing.T) { + gitDir := decoyGitDir + if name == "invalid_git_dir" { + gitDir = filepath.Join(t.TempDir(), "missing.git") + } + t.Setenv("GIT_DIR", gitDir) + t.Setenv("GIT_WORK_TREE", decoy) + t.Setenv("GIT_COMMON_DIR", decoyParent) + before := strings.Join(os.Environ(), "\x00") + clearResolveBeadsDirCache() + if got := ResolveBeadsDirForRepo(target); !utils.PathsEqual(got, want) { + t.Errorf("cold ResolveBeadsDirForRepo() = %q, want target %q", got, want) + } + clearResolveBeadsDirCache() // Exercise the constructor's own cold resolution. + ss := NewSharedStore(target) + defer ss.Close() + if got := ss.BeadsDir(); !utils.PathsEqual(got, want) { + t.Errorf("cold NewSharedStore().BeadsDir() = %q, want target %q", got, want) + } + // Empty .beads proves path selection only, not a database or role read. + if ss.Store() != nil { + t.Error("empty fixture unexpectedly opened a database") + } + if entries, err := os.ReadDir(want); err != nil || len(entries) != 0 { + t.Errorf("empty target .beads changed: entries=%v, err=%v", entries, err) + } + if strings.Join(os.Environ(), "\x00") != before { + t.Error("doctor changed inherited environment") + } + }) + } +} diff --git a/cmd/bd/doctor/role.go b/cmd/bd/doctor/role.go index 4bd148d6b..e5e14579f 100644 --- a/cmd/bd/doctor/role.go +++ b/cmd/bd/doctor/role.go @@ -3,9 +3,11 @@ package doctor import ( "context" "fmt" + "os" "os/exec" "strings" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/storage/dolt" ) @@ -18,6 +20,7 @@ import ( func CheckBeadsRole(path string) DoctorCheck { // Read beads.role from git config (canonical location) cmd := exec.Command("git", "config", "--get", "beads.role") + cmd.Env = gitenv.ScrubRouting(os.Environ()) if path != "" { cmd.Dir = path } @@ -42,6 +45,7 @@ func CheckBeadsRole(path string) DoctorCheck { func CheckBeadsRoleWithStore(path string, ss *SharedStore) DoctorCheck { // Read beads.role from git config (canonical location) cmd := exec.Command("git", "config", "--get", "beads.role") + cmd.Env = gitenv.ScrubRouting(os.Environ()) if path != "" { cmd.Dir = path } @@ -87,6 +91,7 @@ func checkBeadsRoleNotInGit(path string) DoctorCheck { // isGitRepo checks whether the given path is inside a git repository. func isGitRepo(path string) bool { cmd := exec.Command("git", "rev-parse", "--git-dir") + cmd.Env = gitenv.ScrubRouting(os.Environ()) if path != "" { cmd.Dir = path } diff --git a/cmd/bd/doctor/role_test.go b/cmd/bd/doctor/role_test.go index f5d07e51a..b51a6ee0b 100644 --- a/cmd/bd/doctor/role_test.go +++ b/cmd/bd/doctor/role_test.go @@ -4,7 +4,10 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "testing" + + "github.com/steveyegge/beads/internal/gitenv" ) func TestCheckBeadsRole_NotConfigured(t *testing.T) { @@ -114,3 +117,90 @@ func TestCheckBeadsRole_NonexistentPath(t *testing.T) { t.Errorf("expected status %s, got %s", StatusOK, check.Status) } } + +func TestCheckBeadsRoleIgnoresInheritedRouting(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } + } + t.Setenv("BEADS_DIR", "") + clearResolveBeadsDirCache() + t.Cleanup(clearResolveBeadsDirCache) + for _, tc := range []struct { + name, role, global, status, message string + }{ + {"repository", "maintainer", "", StatusOK, "Configured as maintainer"}, + {"inline", "maintainer", "", StatusOK, "Configured as maintainer"}, + {"global_override", "", "maintainer", StatusOK, "Configured as maintainer"}, + {"invalid", "admin", "", StatusWarning, "Invalid beads.role value: \"admin\""}, + {"absent", "", "", StatusWarning, "beads.role not configured"}, + {"nonrepository", "", "", StatusOK, "N/A (not a git repository)"}, + {"default_global", "", "contributor", StatusOK, "Configured as contributor"}, + } { + t.Run(tc.name, func(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + if tc.global != "" { + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\nrole = "+tc.global+"\n"), 0600); err != nil { + t.Fatal(err) + } + } + target, decoy := newGitRepo(t), newGitRepo(t) + runGit := func(repo string, args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = repo, gitenv.ScrubRouting(os.Environ()) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("fixture git %v: %v: %s", args, err, out) + } + } + if tc.role != "" { + runGit(target, "config", "beads.role", tc.role) + } + if tc.name != "nonrepository" { + runGit(decoy, "config", "beads.role", "decoy-role") + } else { + target = t.TempDir() + } + poison := map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy} + switch tc.name { + case "inline", "default_global": + poison = map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "beads.role", "GIT_CONFIG_VALUE_0": "injected-role"} + case "global_override": + config := filepath.Join(home, "nondefault") + if err := os.WriteFile(config, []byte("[beads]\nrole = injected-role\n"), 0600); err != nil { + t.Fatal(err) + } + poison = map[string]string{"GIT_CONFIG_GLOBAL": config} + } + for key, value := range poison { + t.Setenv(key, value) + } + for _, api := range []struct { + name string + run func(string) DoctorCheck + }{ + {"standalone", CheckBeadsRole}, + {"nil shared store", func(path string) DoctorCheck { return CheckBeadsRoleWithStore(path, nil) }}, + {"empty shared store", func(path string) DoctorCheck { return CheckBeadsRoleWithStore(path, &SharedStore{}) }}, + } { + check := api.run(target) + if check.Status != tc.status || check.Message != tc.message || check.Name != "Role Configuration" || check.Category != CategoryData { + t.Errorf("%s: got %+v; want status=%q message=%q", api.name, check, tc.status, tc.message) + } + } + for key, value := range poison { + if os.Getenv(key) != value { + t.Errorf("doctor changed parent environment %s", key) + } + } + }) + } +} diff --git a/internal/beads/beads.go b/internal/beads/beads.go index 5087ae81e..db9c14057 100644 --- a/internal/beads/beads.go +++ b/internal/beads/beads.go @@ -21,6 +21,7 @@ import ( "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/backends" "github.com/steveyegge/beads/internal/utils" @@ -228,12 +229,12 @@ func preferStableBranchWorktreeBeadsDir(beadsDir string) string { return "" } - branch, err := gitOutput(repoRoot, "rev-parse", "--abbrev-ref", "HEAD") + branch, err := selectedBeadsGitOutput(repoRoot, "rev-parse", "--abbrev-ref", "HEAD") if err != nil || branch != "HEAD" { return "" } - head, err := gitOutput(repoRoot, "rev-parse", "HEAD") + head, err := selectedBeadsGitOutput(repoRoot, "rev-parse", "HEAD") if err != nil || head == "" { return "" } @@ -282,9 +283,21 @@ func isDetachedCommitWorktreePath(path string) bool { } func gitOutput(dir string, args ...string) (string, error) { + return gitOutputEnv(nil, dir, args...) +} + +// selectedBeadsGitOutput probes the repository of an already selected .beads path. +// The shared filter also removes GIT_CONFIG_* sandbox overrides; ordinary +// system/global config becomes visible again. Config authority is a separate policy. +func selectedBeadsGitOutput(dir string, args ...string) (string, error) { + return gitOutputEnv(gitenv.ScrubRouting(os.Environ()), dir, args...) +} + +func gitOutputEnv(env []string, dir string, args ...string) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() cmd := exec.CommandContext(ctx, "git", append([]string{"-C", dir}, args...)...) //nolint:gosec // args are internal, not user-supplied + cmd.Env = env output, err := cmd.Output() if err != nil { return "", err @@ -293,7 +306,7 @@ func gitOutput(dir string, args ...string) (string, error) { } func listWorktrees(repoRoot string) ([]worktreeInfo, error) { - output, err := gitOutput(repoRoot, "worktree", "list", "--porcelain") + output, err := selectedBeadsGitOutput(repoRoot, "worktree", "list", "--porcelain") if err != nil { return nil, err } @@ -598,7 +611,7 @@ func FindBeadsDirFrom(startDir string) string { startDir = utils.CanonicalizePath(startDir) repoRoot := "" - if out, err := gitOutput(startDir, "rev-parse", "--show-toplevel"); err == nil { + if out, err := selectedBeadsGitOutput(startDir, "rev-parse", "--show-toplevel"); err == nil { repoRoot = utils.CanonicalizePath(out) } @@ -1053,6 +1066,7 @@ func ResolveBeadsDirForRepo(repoPath string) string { func worktreeFallbackBeadsDirForRepo(repoPath string) string { cmd := exec.Command("git", "-C", repoPath, "rev-parse", "--git-dir", "--git-common-dir") + cmd.Env = gitenv.ScrubRouting(os.Environ()) output, err := cmd.Output() if err != nil { return "" diff --git a/internal/beads/beads_test.go b/internal/beads/beads_test.go index dd2958ebe..7e3094f6f 100644 --- a/internal/beads/beads_test.go +++ b/internal/beads/beads_test.go @@ -6,11 +6,14 @@ import ( "os" "os/exec" "path/filepath" + "reflect" + "runtime" "strings" "testing" "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/utils" ) @@ -2451,3 +2454,188 @@ func TestGitPathForRepo(t *testing.T) { } }) } + +func TestFindBeadsDirFromIgnoresInheritedRouting(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } + } + home := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + for _, layout := range []string{"regular", "bare"} { + t.Run(layout, func(t *testing.T) { + setup := setupRegularWorktreeRepo + if layout == "bare" { + setup = setupBareParentWorktree + } + main, target := setup(t) + decoyMain, decoy := setup(t) + for _, dir := range []string{main, decoyMain} { + if err := os.MkdirAll(filepath.Join(dir, ".beads", "dolt"), 0755); err != nil { + t.Fatal(err) + } + } + decoyGit := runGitInDir(t, decoy, "rev-parse", "--absolute-git-dir") + start := filepath.Join(target, "sub dir") + if err := os.Mkdir(start, 0755); err != nil { + t.Fatal(err) + } + t.Chdir(decoy) + t.Setenv("BEADS_DIR", filepath.Join(decoyMain, ".beads")) + for _, name := range []string{"ordinary", "decoy", "invalid", "work_tree_only"} { + t.Run(name, func(t *testing.T) { + if name != "ordinary" { + t.Setenv("GIT_WORK_TREE", decoy) + if name != "work_tree_only" { + gitDir := decoyGit + if name == "invalid" { + gitDir = filepath.Join(home, "missing git dir") + } + t.Setenv("GIT_DIR", gitDir) + } + got, err := gitOutput(start, "rev-parse", "--show-toplevel") + if (name == "invalid" && err == nil) || (name != "invalid" && (err != nil || !utils.PathsEqual(got, decoy))) { + t.Fatalf("inherited probe precondition: %q (%v)", got, err) + } + } + before := os.Environ() + if got := FindBeadsDirFrom(start); !utils.PathsEqual(got, filepath.Join(main, ".beads")) { + t.Errorf("explicit discovery = %q, want selected shared .beads", got) + } + cwd, err := os.Getwd() + if err != nil || !utils.PathsEqual(cwd, decoy) || !reflect.DeepEqual(before, os.Environ()) { + t.Errorf("explicit discovery changed process directory/environment: %q (%v)", cwd, err) + } + }) + } + }) + } +} + +func TestSelectedBeadsCanonicalizerIgnoresInheritedRouting(t *testing.T) { + t.Chdir(t.TempDir()) + detached, stable, database := setupDetachedCommitBeadsWorktree(t) + _, decoy, _ := setupDetachedCommitBeadsWorktree(t) + decoyGitDir := runGitInDir(t, filepath.Dir(decoy), "rev-parse", "--absolute-git-dir") + decoyCommonDir := runGitInDir(t, filepath.Dir(decoy), "rev-parse", "--path-format=absolute", "--git-common-dir") + redirect := filepath.Join(t.TempDir(), ".beads") + if err := os.Mkdir(redirect, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(redirect, RedirectFileName), []byte(detached), 0600); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + env map[string]string + query []string + }{ + {"decoy", map[string]string{"GIT_DIR": decoyGitDir}, []string{"rev-parse", "--abbrev-ref", "HEAD"}}, + {"invalid", map[string]string{"GIT_DIR": filepath.Join(t.TempDir(), "missing git dir")}, []string{"rev-parse", "--abbrev-ref", "HEAD"}}, + {"work_tree_only", map[string]string{"GIT_WORK_TREE": filepath.Dir(decoy)}, []string{"rev-parse", "--show-toplevel"}}, + {"common_dir_only", map[string]string{"GIT_COMMON_DIR": decoyCommonDir}, []string{"rev-parse", "--git-common-dir"}}, + // Linked worktrees stay non-bare regardless of core.bare; observe the config itself. + {"inline_config", map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.bare", "GIT_CONFIG_VALUE_0": "false"}, []string{"config", "--get", "core.bare"}}, + } { + t.Run(tc.name, func(t *testing.T) { + for key, value := range tc.env { + t.Setenv(key, value) + } + t.Setenv("BEADS_DIR", detached) + t.Setenv("BEADS_DB", "") + // Each vector changes the generic query; selected queries keep their own context. + inherited, inheritedErr := gitOutput(filepath.Dir(detached), tc.query...) + selected, err := selectedBeadsGitOutput(filepath.Dir(detached), tc.query...) + if err != nil || (tc.name == "invalid" && inheritedErr == nil) || + (tc.name != "invalid" && (inheritedErr != nil || inherited == selected)) { + t.Fatalf("routing precondition: inherited=%q (%v), selected=%q (%v)", inherited, inheritedErr, selected, err) + } + for _, check := range []struct{ name, got, want string }{ + {"FollowRedirect", FollowRedirect(redirect), stable}, + {"FindBeadsDir", FindBeadsDir(), stable}, + {"FindDatabasePath", FindDatabasePath(), database}, + } { + if !utils.PathsEqual(check.got, check.want) { + t.Errorf("%s = %q, want selected stable path %q", check.name, check.got, check.want) + } + } + }) + } +} + +func TestSelectedBeadsCanonicalizerFallbacks(t *testing.T) { + t.Chdir(t.TempDir()) + for _, name := range []string{"stable_branch", "different_head", "missing_stable"} { + t.Run(name, func(t *testing.T) { + detached, stable, _ := setupDetachedCommitBeadsWorktree(t) + want := detached + switch name { + case "stable_branch": + want = stable + case "different_head": + runGitInDir(t, filepath.Dir(stable), "commit", "--allow-empty", "-m", "Different branch head") + case "missing_stable": + if err := os.Rename(stable, stable+".saved"); err != nil { + t.Fatal(err) + } + } + if got := canonicalizeBeadsDirPath(want); !utils.PathsEqual(got, want) { + t.Errorf("canonical path = %q, want unchanged %q", got, want) + } + }) + } +} + +func TestResolveBeadsDirForRepoIgnoresInheritedRouting(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } + } + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, t.TempDir()) + } + // Production ScrubRouting removes this flag; it does not suppress system config there. + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + targetParent, target := setupRegularWorktreeRepo(t) + decoyParent, decoy := setupRegularWorktreeRepo(t) + want := utils.CanonicalizePath(filepath.Join(targetParent, ".beads")) + for _, dir := range []string{want, filepath.Join(decoyParent, ".beads")} { + if err := os.MkdirAll(dir, 0o750); err != nil { + t.Fatal(err) + } + } + if _, err := os.Stat(filepath.Join(target, ".beads")); !os.IsNotExist(err) { + t.Fatalf("fixture must require common-parent fallback: %v", err) + } + decoyGitDir := runGitInDir(t, decoy, "rev-parse", "--absolute-git-dir") + for _, name := range []string{"decoy", "invalid_git_dir"} { + t.Run(name, func(t *testing.T) { + gitDir := decoyGitDir + if name == "invalid_git_dir" { + gitDir = filepath.Join(t.TempDir(), "missing.git") + } + t.Setenv("GIT_DIR", gitDir) + t.Setenv("GIT_WORK_TREE", decoy) + t.Setenv("GIT_COMMON_DIR", filepath.Join(decoyParent, ".git")) + before := strings.Join(os.Environ(), "\x00") + if got := ResolveBeadsDirForRepo(target); !utils.PathsEqual(got, want) { + t.Errorf("ResolveBeadsDirForRepo() = %q, want target %q", got, want) + } + if strings.Join(os.Environ(), "\x00") != before { + t.Error("resolver changed inherited environment") + } + }) + } +} diff --git a/internal/beads/context.go b/internal/beads/context.go index ceb689c49..f9e74c3f1 100644 --- a/internal/beads/context.go +++ b/internal/beads/context.go @@ -30,6 +30,7 @@ import ( "sync" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" ) // UserRole represents the user's relationship to a repository. @@ -234,6 +235,11 @@ func getRepoRootFromPath(path string) (string, error) { // We explicitly set GIT_DIR and GIT_WORK_TREE to ensure git operates on // the correct repository (the one containing .beads/). func (rc *RepoContext) GitCmd(ctx context.Context, args ...string) *exec.Cmd { + return rc.gitCmdWithEnv(ctx, os.Environ(), args...) +} + +// gitCmdWithEnv applies the existing repository pins after the caller policy. +func (rc *RepoContext) gitCmdWithEnv(ctx context.Context, env []string, args ...string) *exec.Cmd { gitArgs := append([]string{"-c", "core.hooksPath="}, args...) cmd := exec.CommandContext(ctx, "git", gitArgs...) cmd.Dir = rc.RepoRoot @@ -244,7 +250,7 @@ func (rc *RepoContext) GitCmd(ctx context.Context, args ...string) *exec.Cmd { // Security: Disable git hooks and templates to prevent code execution // in potentially malicious repositories (SEC-001, SEC-002) - cmd.Env = append(os.Environ(), + cmd.Env = append(env, "GIT_TEMPLATE_DIR=", // Disable templates "GIT_DIR="+gitDir, // Ensure git uses the correct .git directory "GIT_WORK_TREE="+rc.RepoRoot, // Ensure git uses the correct work tree @@ -573,11 +579,12 @@ func (rc *RepoContext) Role() (UserRole, bool) { return Contributor, true } - output, err := rc.GitOutput(context.Background(), "config", "--get", "beads.role") + cmd := rc.gitCmdWithEnv(context.Background(), gitenv.ScrubRouting(os.Environ()), "config", "--get", "beads.role") + output, err := cmd.Output() if err != nil { return "", false // Not configured } - return UserRole(strings.TrimSpace(output)), true + return UserRole(strings.TrimSpace(string(output))), true } // IsContributor returns true if user is configured as contributor. diff --git a/internal/beads/context_test.go b/internal/beads/context_test.go index 0c06c6eda..4bcd5eecb 100644 --- a/internal/beads/context_test.go +++ b/internal/beads/context_test.go @@ -7,9 +7,11 @@ import ( "os/exec" "path/filepath" "runtime" + "strings" "testing" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" ) // TestGetRepoContextForWorkspace_NormalRepo tests context resolution for a normal git repository @@ -1300,3 +1302,98 @@ func initGitRepoWithCommit(dir string) error { commitCmd.Dir = dir return commitCmd.Run() } + +func TestRoleIgnoresInheritedGitRouting(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } + } + home, target, decoy := t.TempDir(), t.TempDir(), t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + runGit := func(t *testing.T, args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Env = gitenv.ScrubRouting(os.Environ()) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("fixture git %v: %v: %s", args, err, out) + } + } + for _, repo := range []string{target, decoy} { + runGit(t, "-C", repo, "init", "--quiet") + } + runGit(t, "-C", target, "config", "beads.role", "maintainer") + runGit(t, "-C", decoy, "config", "beads.role", "contributor") + t.Chdir(decoy) + rc := &RepoContext{RepoRoot: target} // The caller has already selected this repo. + for _, inline := range []bool{false, true} { + name, generic := "repository", "maintainer" + poison := map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy} + if inline { + name, generic = "inline", "injected-role" + poison = map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "beads.role", "GIT_CONFIG_VALUE_0": generic} + } + t.Run(name, func(t *testing.T) { + for key, value := range poison { + t.Setenv(key, value) + } + if role, ok := rc.Role(); !ok || role != Maintainer { + t.Errorf("Role() = %q, %v; want maintainer, true", role, ok) + } + if out, err := rc.GitOutput(t.Context(), "config", "--get", "beads.role"); err != nil || strings.TrimSpace(out) != generic { + t.Errorf("generic GitOutput = %q, %v; want %q", out, err, generic) + } + for key, value := range poison { + if os.Getenv(key) != value { + t.Errorf("Role changed parent environment %s", key) + } + } + }) + } + t.Run("common_dir", func(t *testing.T) { + commonDir := filepath.Join(decoy, ".git") + t.Setenv("GIT_COMMON_DIR", commonDir) + // Unlike GIT_DIR, this key is not overridden by the generic repository pins. + if role, ok := rc.Role(); !ok || role != Maintainer { + t.Errorf("Role() = %q, %v; want maintainer, true", role, ok) + } + if out, err := rc.GitOutput(t.Context(), "config", "--get", "beads.role"); err != nil || strings.TrimSpace(out) != string(Contributor) { + t.Errorf("generic GitOutput = %q, %v; want contributor", out, err) + } + if os.Getenv("GIT_COMMON_DIR") != commonDir { + t.Error("Role changed parent GIT_COMMON_DIR") + } + }) + t.Run("live_values", func(t *testing.T) { + for _, value := range []string{"contributor", "invalid", ""} { + runGit(t, "-C", target, "config", "beads.role", value) + if role, ok := rc.Role(); !ok || role != UserRole(value) { + t.Errorf("fresh Role() = %q, %v; want %q, true", role, ok, value) + } + } + }) + t.Run("absent_and_global", func(t *testing.T) { + runGit(t, "-C", target, "config", "--unset", "beads.role") + if role, ok := rc.Role(); ok || role != "" { + t.Errorf("absent Role() = %q, %v", role, ok) + } + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\nrole = contributor\n"), 0o600); err != nil { + t.Fatal(err) + } + if role, ok := rc.Role(); !ok || role != Contributor { + t.Errorf("global Role() = %q, %v", role, ok) + } + }) + t.Run("redirected", func(t *testing.T) { + redirected := &RepoContext{RepoRoot: t.TempDir(), IsRedirected: true} + if role, ok := redirected.Role(); !ok || role != Contributor { + t.Errorf("redirected Role() = %q, %v", role, ok) + } + }) +} diff --git a/internal/routing/routing.go b/internal/routing/routing.go index 0516939ff..6da3f9a30 100644 --- a/internal/routing/routing.go +++ b/internal/routing/routing.go @@ -9,10 +9,12 @@ import ( "strings" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" ) var gitCommandRunner = func(repoPath string, args ...string) ([]byte, error) { cmd := exec.Command("git", args...) + cmd.Env = gitenv.ScrubRouting(os.Environ()) if repoPath != "" { cmd.Dir = repoPath } diff --git a/internal/routing/routing_test.go b/internal/routing/routing_test.go index 9e0733595..c4af2b662 100644 --- a/internal/routing/routing_test.go +++ b/internal/routing/routing_test.go @@ -4,12 +4,15 @@ import ( "errors" "io" "os" + "os/exec" "path/filepath" "reflect" + "runtime" "strings" "testing" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" ) func TestDetermineTargetRepo(t *testing.T) { @@ -461,3 +464,78 @@ func TestDetectUserRole_JJSecondaryWorkspace_NonCwdRepoPath(t *testing.T) { t.Errorf("expected no role-not-configured warning, got stderr:\n%s", stderr) } } + +func TestDetectUserRoleIgnoresInheritedGitRouting(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } + } + t.Chdir(t.TempDir()) // The explicit target must also work outside CWD. + runGit := func(t *testing.T, repo string, args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = repo + cmd.Env = gitenv.ScrubRouting(os.Environ()) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("fixture git %v: %v: %s", args, err, out) + } + } + for _, tc := range []struct { + name, role, global string + inline, warning bool + want UserRole + }{ + {"repository", "maintainer", "", false, false, Maintainer}, + {"inline", "maintainer", "", true, false, Maintainer}, + {"missing_remote", "", "", false, true, Contributor}, + {"invalid_remote", "invalid", "", false, true, Contributor}, + {"default_global", "", "maintainer", true, false, Maintainer}, + } { + t.Run(tc.name, func(t *testing.T) { + home, target, decoy := t.TempDir(), t.TempDir(), t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + if tc.global != "" { + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\nrole = "+tc.global+"\n"), 0o600); err != nil { + t.Fatal(err) + } + } + for _, repo := range []string{target, decoy} { + runGit(t, repo, "init", "--quiet") + } + runGit(t, decoy, "config", "beads.role", "contributor") + runGit(t, decoy, "remote", "add", "origin", "git@example.invalid:owner/decoy.git") + runGit(t, target, "remote", "add", "origin", "https://example.invalid/owner/target.git") + if tc.role != "" { + runGit(t, target, "config", "beads.role", tc.role) + } + poison := map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy} + if tc.inline { + poison = map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "beads.role", "GIT_CONFIG_VALUE_0": "contributor"} + } + for key, value := range poison { + t.Setenv(key, value) + } + var got UserRole + var err error + stderr := captureStderr(t, func() { got, err = DetectUserRole(target) }) + if err != nil || got != tc.want { + t.Errorf("DetectUserRole(target) = %q, %v; want %q", got, err, tc.want) + } + if strings.Contains(stderr, "beads.role not configured") != tc.warning { + t.Errorf("fallback warning = %q; want warning=%v", stderr, tc.warning) + } + for key, value := range poison { + if os.Getenv(key) != value { + t.Errorf("reader changed parent environment %s", key) + } + } + }) + } +}