diff --git a/cmd/bd/config.go b/cmd/bd/config.go index 3982deef1..95bcb450b 100644 --- a/cmd/bd/config.go +++ b/cmd/bd/config.go @@ -119,12 +119,15 @@ var forceGitTracked bool // newRoleConfigWriter captures fresh cwd and scrubbed routing once per write // operation. The process-wide Git cache and Beads storage do not select it. +// Routing is scrubbed along with the suppression ScrubRouting deliberately +// keeps: beads.role is an authority value, and the reader it feeds treats a +// missing value as maintainer, so a suppressed config file would fail open. func newRoleConfigWriter() (func(...string) error, error) { dir, err := os.Getwd() if err != nil { return nil, err } - env := gitenv.ScrubRouting(os.Environ()) + env := gitenv.ScrubRoutingAndSuppression(os.Environ()) probe := exec.Command("git", "rev-parse", "--git-common-dir") probe.Dir, probe.Env = dir, env out, err := probe.Output() @@ -237,12 +240,14 @@ var configSetCmd = &cobra.Command{ } // bd config's own beads.role reads and writes ignore inherited Git // routing, including GIT_CONFIG_GLOBAL, so the value lands in the - // repository this command selected. The scope is this command set, - // not role resolution as a whole: routing.DetectUserRole, - // `bd config show`, `bd doctor` and `bd hooks uninstall` still - // resolve beads.role through the inherited environment, and - // beads.RepoContext.Role pins GIT_DIR/GIT_WORK_TREE last-wins but - // still inherits GIT_CONFIG_*. + // repository this command selected. beads.role is an authority + // value and the reader it feeds treats a missing value as + // maintainer, so these planes also discard the explicit suppression + // ScrubRouting deliberately keeps -- otherwise a blinded read fails + // open instead of erroring. That boundary is uniform across + // routing.DetectUserRole, `bd config show`, `bd doctor`, + // `bd hooks uninstall` and beads.RepoContext.Role, which re-pins + // GIT_DIR/GIT_WORK_TREE last-wins on top of it. write, err := newRoleConfigWriter() if err != nil { return HandleError("setting beads.role in git config: %v", err) @@ -567,8 +572,9 @@ var configGetCmd = &cobra.Command{ } if key == "beads.role" { + // Same role-authority boundary as `bd config set` above. cmd := exec.Command("git", "config", "--get", "beads.role") - cmd.Env = gitenv.ScrubRouting(os.Environ()) + cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ()) output, err := cmd.Output() value := strings.TrimSpace(string(output)) if err != nil { @@ -845,6 +851,9 @@ var configUnsetCmd = &cobra.Command{ } if key == "beads.role" { + // Same role-authority boundary as `bd config set`/`get` above: every + // spelling of a beads.role mutation resolves the repository the same + // way, so the next reader has one boundary to reason about. write, err := newRoleConfigWriter() if err != nil { return HandleError("unsetting beads.role in git config: %v", err) @@ -1140,6 +1149,8 @@ Examples: } if len(gitPairs) > 0 { + // set-many is the batch alias for `bd config set`, so it runs on the + // same role-authority boundary that verb does. write, err := newRoleConfigWriter() if err != nil { return HandleError("setting beads.role in git config: %v", err) diff --git a/cmd/bd/config_show.go b/cmd/bd/config_show.go index 5083a0ae5..ec409e7d4 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.ScrubRoutingAndSuppression(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 7001a6d07..9d4408f4c 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. @@ -437,3 +440,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..c6d2cbe3e 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 retains this explicit system-config suppression. + 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..bb1eb04dc 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.ScrubRoutingAndSuppression(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.ScrubRoutingAndSuppression(os.Environ()) if path != "" { cmd.Dir = path } @@ -85,8 +89,15 @@ func checkBeadsRoleNotInGit(path string) DoctorCheck { } // isGitRepo checks whether the given path is inside a git repository. +// +// Shares the boundary of the two role reads above, which is what this probe +// gates: rev-parse is config-sensitive through safe.directory, so retaining +// suppression here could answer false for a repository that is only reachable +// via a global safe.directory entry and silently downgrade the "beads.role not +// configured" warning to "N/A (not a git repository)". func isGitRepo(path string) bool { cmd := exec.Command("git", "rev-parse", "--git-dir") + cmd.Env = gitenv.ScrubRoutingAndSuppression(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/cmd/bd/hooks.go b/cmd/bd/hooks.go index 0d59c5cd7..9be51e6e8 100644 --- a/cmd/bd/hooks.go +++ b/cmd/bd/hooks.go @@ -1438,6 +1438,9 @@ func resetHooksPathIfBeadsManaged() error { return fmt.Errorf("empty Git common directory for role reset") } configEnv := gitenv.ScrubRouting(os.Environ()) + // beads.role is an authority value, unlike core.hooksPath, so its own + // commands drop inherited suppression too (see the role pair below). + roleConfigEnv := gitenv.ScrubRoutingAndSuppression(os.Environ()) var failures []string cmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--get", "core.hooksPath") @@ -1474,13 +1477,18 @@ func resetHooksPathIfBeadsManaged() error { // Keep the selected main/common config, including bare repositories with an // external worktree, while dropping routing overrides from both commands. // The presence query must use the same local scope as the unset. + // + // Both role commands additionally discard the explicit config suppression + // ScrubRouting keeps: beads.role is an authority value whose absence reads + // as maintainer, so a suppressed config file would report a clean uninstall + // while leaving the key set here. getRoleCmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--get", "beads.role") getRoleCmd.Dir = repoRoot - getRoleCmd.Env = configEnv + getRoleCmd.Env = roleConfigEnv if out, err := getRoleCmd.CombinedOutput(); err == nil { roleCmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--unset", "beads.role") roleCmd.Dir = repoRoot - roleCmd.Env = configEnv + roleCmd.Env = roleConfigEnv if output, err := roleCmd.CombinedOutput(); err != nil { failures = append(failures, fmt.Sprintf("beads.role: %v (output: %s)", err, strings.TrimSpace(string(output)))) } diff --git a/cmd/bd/init.go b/cmd/bd/init.go index 3b6b78865..5064509d2 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -1940,6 +1940,13 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // Earlier code paths may skip role-setting when BEADS_DIR is set, // promptContributorMode fails, or edge-case flag combinations are used. // This guarantees every init leaves a usable role-configured state. + // + // The gate and the pair answer on the same boundary: isInitRoleGitRepo + // scrubs inherited routing and config suppression exactly as + // getBeadsRole/setBeadsRole do, so the gate cannot open on a repository + // the write will then fail to reach. Gating on the inherited isGitRepo() + // instead is what used to make this safety net write the role into a + // redirected repository. if isInitRoleGitRepo(ctx) { if _, hasRole := getBeadsRole(); !hasRole { fallbackRole := "maintainer" @@ -2933,20 +2940,49 @@ func shouldPromptForRole() bool { return term.IsTerminal(int(os.Stdin.Fd())) } -// isInitRoleGitRepo uses the same CWD and routing policy as getBeadsRole/setBeadsRole. +// isInitRoleGitRepo uses the same CWD and routing policy as getBeadsRole/setBeadsRole, +// including their suppression scrub: rev-parse is config-sensitive through +// safe.directory, so retaining suppression here could answer false for a +// repository that is only reachable via a global safe.directory entry and skip +// the role write the pair would have completed. func isInitRoleGitRepo(ctx context.Context) bool { ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-dir") - cmd.Env = gitenv.ScrubRouting(os.Environ()) + cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ()) return cmd.Run() == nil } // getBeadsRole reads the beads.role git config value. // Returns the role and true if configured, or empty string and false if not set. +// +// Both halves of the pair run on the same authority boundary as every role +// reader so init cannot report a role it wrote into a different repository: +// an inherited GIT_DIR would redirect setBeadsRole's write, and inherited +// config suppression would blind the read that decides whether to write at +// all. +// +// Selection is then the working directory or a containing ancestor. The scrub +// drops GIT_CEILING_DIRECTORIES along with the redirects, so it removes a +// bound rather than installing one: measured from a non-repository directory +// nested under a repository, `git config beads.role ` fails "not in a +// git directory" while a ceiling below that repository is inherited, and +// writes the repository's local config once the ceiling is scrubbed. cmd.Dir +// is still not threaded through the pair, because no production path chdirs +// away from the invocation directory before these run. Two residuals remain: +// upward discovery from an unintended cwd, and `bd -C `, which redirects +// project selection by setting BEADS_DIR without chdir-ing +// (applyChangeDirSelection), so init can act on another project's workspace +// while the pair still reads and writes beads.role in the invocation +// repository; -C requires an existing beads project at the target, so that +// pairing arises on re-init rather than first init, and the GH#2950 safety net +// records the same BEADS_DIR skew. Threading init's resolved project root +// through the pair would close that one, but it is a behavior change rather +// than a boundary fix. clearWorktreeGitRoutingEnv discloses the same widening +// for the bd worktree commands. func getBeadsRole() (string, bool) { cmd := exec.Command("git", "config", "--get", "beads.role") - cmd.Env = gitenv.ScrubRouting(os.Environ()) + cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ()) output, err := cmd.Output() if err != nil { return "", false @@ -2958,10 +2994,11 @@ func getBeadsRole() (string, bool) { return role, true } -// setBeadsRole writes the beads.role git config value. +// setBeadsRole writes the beads.role git config value. See getBeadsRole for +// why the pair shares the role-authority environment boundary. func setBeadsRole(role string) error { cmd := exec.Command("git", "config", "beads.role", role) - cmd.Env = gitenv.ScrubRouting(os.Environ()) + cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ()) return cmd.Run() } diff --git a/cmd/bd/init_contributor.go b/cmd/bd/init_contributor.go index 2bf486786..a6c197da4 100644 --- a/cmd/bd/init_contributor.go +++ b/cmd/bd/init_contributor.go @@ -347,6 +347,9 @@ func autoConfigureForkContributor(ctx context.Context, store storage.DoltStorage return fmt.Errorf("failed to set sync.remote: %w", err) } + // setBeadsRole carries the shared role-authority boundary: an inherited + // GIT_DIR or a suppressed config file would otherwise land this write in a + // different repository than every beads.role reader consults. if err := setBeadsRole("contributor"); err != nil && !quiet { fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role=contributor: %v\n", err) } diff --git a/cmd/bd/init_role_routing_test.go b/cmd/bd/init_role_routing_test.go new file mode 100644 index 000000000..aea4cb7bf --- /dev/null +++ b/cmd/bd/init_role_routing_test.go @@ -0,0 +1,133 @@ +package main + +import ( + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/gitenv" +) + +// TestBeadsRoleWriterIgnoresInheritedGitRouting pins the init role pair to the +// same boundary as every beads.role reader. The reader half of the stack was +// hardened first, which is what makes the writer half load-bearing: with the +// writer still inherited, `GIT_DIR=/.git bd init` writes the role +// into that other repository, then reports success while every scrubbed reader +// looks at the repository the user is actually standing in and finds nothing. +// +// Both subtests must assert *where* the value landed. A roundtrip assertion is +// vacuous here: before the fix the write and the read followed the same +// redirect, so they agreed with each other about the wrong repository. +func TestBeadsRoleWriterIgnoresInheritedGitRouting(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("role routing fixture requires Git") + } + 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) + } + } + } + + // localRole reads repo's own config file directly, so it reports where a + // value physically landed rather than what discovery would resolve to. + localRole := func(t *testing.T, repo string) string { + t.Helper() + cmd := exec.Command("git", "config", "--local", "--get", "beads.role") + cmd.Dir = repo + cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ()) + out, err := cmd.Output() + if err != nil { + return "" + } + return strings.TrimSpace(string(out)) + } + setLocalRole := func(t *testing.T, repo, role string) { + t.Helper() + cmd := exec.Command("git", "config", "--local", "beads.role", role) + cmd.Dir = repo + cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ()) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("fixture git config: %v: %s", err, out) + } + } + poison := func(t *testing.T, decoy string) { + t.Helper() + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + t.Setenv("GIT_WORK_TREE", decoy) + } + + t.Run("write stays in the selected repository", func(t *testing.T) { + target, decoy := newGitRepo(t), newGitRepo(t) + t.Chdir(target) + poison(t, decoy) + + if err := setBeadsRole("contributor"); err != nil { + t.Fatalf("setBeadsRole: %v", err) + } + if got := localRole(t, target); got != "contributor" { + t.Errorf("target beads.role = %q, want %q: the write did not land where bd is standing", got, "contributor") + } + if got := localRole(t, decoy); got != "" { + t.Errorf("decoy beads.role = %q, want unset: an inherited GIT_DIR captured the write", got) + } + }) + + t.Run("read ignores a redirected repository", func(t *testing.T) { + target, decoy := newGitRepo(t), newGitRepo(t) + setLocalRole(t, decoy, "maintainer") + t.Chdir(target) + poison(t, decoy) + + // Fixture guard: the decoy really does hold a readable role, so a + // "not maintainer" result below can only come from ignoring it. + if got := localRole(t, decoy); got != "maintainer" { + t.Fatalf("decoy fixture beads.role = %q, want %q", got, "maintainer") + } + role, hasRole := getBeadsRole() + if hasRole { + t.Errorf("getBeadsRole() = %q, true; want unset: the read followed an inherited GIT_DIR", role) + } + }) + + // A redirect is not the only way to defeat the pair, and the two subtests + // above cannot tell the two vectors apart: they pass on the GIT_DIR half + // alone, so downgrading getBeadsRole to gitenv.ScrubRouting leaves them + // green. Suppression is the load-bearing half here — init.go treats a + // getBeadsRole miss as permission to write a default role — so it needs a + // pin of its own. + t.Run("read ignores inherited config suppression", func(t *testing.T) { + home, target := t.TempDir(), newGitRepo(t) + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\n\trole = contributor\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Chdir(target) + + for _, tc := range []struct{ name, blind string }{ + // Fixture guard: the global role must be readable at all, and must + // not be shadowed by a local one, or the blinded case below would + // pass for the wrong reason. + {"unblinded", ""}, + {"global_null", os.DevNull}, + } { + t.Run(tc.name, func(t *testing.T) { + if tc.blind != "" { + t.Setenv("GIT_CONFIG_GLOBAL", tc.blind) + } + role, hasRole := getBeadsRole() + if !hasRole || role != "contributor" { + t.Errorf("getBeadsRole() = %q, %t; want %q, true: a blinded read is what makes init write a default role", role, hasRole, "contributor") + } + }) + } + }) +} diff --git a/cmd/bd/worktree_cmd.go b/cmd/bd/worktree_cmd.go index 968e7c705..74a09ca99 100644 --- a/cmd/bd/worktree_cmd.go +++ b/cmd/bd/worktree_cmd.go @@ -672,9 +672,9 @@ func scrubWorktreeGitRoutingEnv(env []string) []string { } // scrubWorktreeGitRoutingEnvForOS removes inherited Git repository, index, -// object, namespace, executable, template, and config routing. It deliberately -// preserves non-routing controls such as GIT_OPTIONAL_LOCKS; the removal runner -// applies its stricter policy separately. +// object, namespace, executable, template, and custom config routing. It keeps +// explicit null config suppression, GIT_CONFIG_NOSYSTEM and non-routing controls +// such as GIT_OPTIONAL_LOCKS; the removal runner applies its stricter policy separately. func scrubWorktreeGitRoutingEnvForOS(env []string, goos string) []string { return gitenv.ScrubRoutingForOS(env, goos) } @@ -709,10 +709,18 @@ func worktreeGitEnvKey(entry string) string { // clearWorktreeGitRoutingEnv establishes the command working directory as the // repository-selection boundary without changing process identity or signal -// semantics. Startup config discovery applies the same scrub to its pre-hook -// config-path probe only; the .beads database discovery probes in -// internal/beads still honor inherited routing, so the two planes can resolve -// different repositories. +// semantics. Startup config discovery applies the same boundary to its one +// pre-hook Git probe, and the .beads discovery probes that run against an +// already selected path share it too (beads.selectedBeadsGitOutput and +// ResolveBeadsDirForRepo). The generic internal/beads gitOutput probes and +// internal/git/gitdir.go still honor inherited routing, so those planes can +// still resolve a different repository than this one (bd-p4che). +// +// The boundary removes inherited discovery *redirects*. It is not a floor: +// GIT_CEILING_DIRECTORIES is a routing key too, so dropping it also re-enables +// upward discovery, and a `bd worktree` command run outside a repository can +// then select a containing parent that an inherited ceiling would have hidden +// (init's role probe records the same trade-off). func clearWorktreeGitRoutingEnv(cmd *cobra.Command) error { if !hasWorktreeCommandAncestor(cmd) { return nil diff --git a/cmd/bd/worktree_test.go b/cmd/bd/worktree_test.go index bc380a541..01f4d9c85 100644 --- a/cmd/bd/worktree_test.go +++ b/cmd/bd/worktree_test.go @@ -79,6 +79,10 @@ func TestGitRevParse(t *testing.T) { func TestGitCmdInDirSuppressesHooksViaGitConfig(t *testing.T) { t.Setenv("GIT_DIR", "/wrong") t.Setenv("GIT_OPTIONAL_LOCKS", "1") + suppression := map[string]string{"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.DevNull, "GIT_CONFIG_SYSTEM": os.DevNull} + for key, value := range suppression { + t.Setenv(key, value) + } cmd := gitCmdInDir(t.Context(), "/tmp/example", "status", "--porcelain") if cmd.Dir != "/tmp/example" { t.Fatalf("cmd.Dir = %q, want /tmp/example", cmd.Dir) @@ -104,6 +108,14 @@ func TestGitCmdInDirSuppressesHooksViaGitConfig(t *testing.T) { if env == "GIT_OPTIONAL_LOCKS=1" { hasOptionalLocks = true } + key := worktreeGitEnvKey(env) + if want, ok := suppression[key]; ok { + if env != key+"="+want { + t.Fatalf("changed config suppression: %q", env) + } + delete(suppression, key) + continue + } if gitenv.IsRoutingKeyForOS(worktreeGitEnvKey(env), runtime.GOOS) && env != "GIT_TEMPLATE_DIR=" { t.Fatalf("cmd.Env retains Git routing state: %q", env) } @@ -114,6 +126,9 @@ func TestGitCmdInDirSuppressesHooksViaGitConfig(t *testing.T) { if !hasOptionalLocks { t.Fatal("cmd.Env did not preserve GIT_OPTIONAL_LOCKS") } + if len(suppression) != 0 { + t.Fatalf("cmd.Env dropped explicit config suppression: %v", suppression) + } } func TestScrubWorktreeRemovalGitEnvUsesSharedWindowsKeyIdentity(t *testing.T) { diff --git a/docs/reference/worktrees.md b/docs/reference/worktrees.md index 18dbd61aa..2adc406ee 100644 --- a/docs/reference/worktrees.md +++ b/docs/reference/worktrees.md @@ -25,6 +25,12 @@ 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. +`GIT_CEILING_DIRECTORIES` is scrubbed along with the redirects. That removes a +*bound* rather than a redirect, so discovery from the working directory is +widened, not narrowed: run in a directory that is not itself a repository, `bd` +can select a containing parent repository that an inherited ceiling would have +hidden. + ``` project/ ├── .git/ # Shared Git directory diff --git a/internal/beads/beads.go b/internal/beads/beads.go index 739a0db50..bf153a423 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 retains NOSYSTEM and null GLOBAL/SYSTEM suppression, +// while discarding custom config paths and inline config overrides. +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 } @@ -643,7 +656,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) } @@ -1174,6 +1187,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 4597bc65d..b4e64378d 100644 --- a/internal/beads/beads_test.go +++ b/internal/beads/beads_test.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "path/filepath" + "reflect" "runtime" "slices" "strings" @@ -13,6 +14,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/utils" ) @@ -2695,3 +2697,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 retains this explicit system-config suppression. + 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..1ae45003b 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.ScrubRoutingAndSuppression(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/config/config.go b/internal/config/config.go index 152935554..d3c0a12a9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1031,9 +1031,9 @@ func ResolveExternalProjectPath(projectName string) string { // 3. git config user.name // 4. hostname // -// The Git lookup discards inherited routing overrides, including -// GIT_CONFIG_GLOBAL. Set user.name in the default global config location -// rather than selecting a different file through that environment override. +// The Git lookup discards custom GIT_CONFIG_GLOBAL paths and other routing +// overrides, while retaining explicit config suppression. Set user.name in +// the default global config location when global config is enabled. func GetIdentity(flagValue string) string { // 1. Command-line flag takes precedence if flagValue != "" { diff --git a/internal/config/git_routing_test.go b/internal/config/git_routing_test.go index e39722d37..2f56defa7 100644 --- a/internal/config/git_routing_test.go +++ b/internal/config/git_routing_test.go @@ -36,6 +36,10 @@ func TestGetIdentityIgnoresInheritedGitRouting(t *testing.T) { if err := os.WriteFile(poisonConfig, []byte("[user]\n\tname = injected-user\n"), 0o600); err != nil { t.Fatal(err) } + hostname, err := os.Hostname() + if err != nil || hostname == "" { + t.Fatalf("hostname fixture: %q, %v", hostname, err) + } for _, tc := range []struct { name string env map[string]string @@ -45,8 +49,11 @@ func TestGetIdentityIgnoresInheritedGitRouting(t *testing.T) { {name: "repository", env: map[string]string{"GIT_DIR": filepath.Join(decoy, ".git")}, want: "target-user"}, {name: "inline config", env: map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "user.name", "GIT_CONFIG_VALUE_0": "injected-user"}, want: "target-user"}, {name: "global config", env: map[string]string{"GIT_CONFIG_GLOBAL": poisonConfig}, clearLocal: true, want: "home-user"}, + {name: "null config suppression", env: map[string]string{"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"}, clearLocal: true, want: hostname}, } { t.Run(tc.name, func(t *testing.T) { + // Keep each removal case independent of the preceding case. + runConfigProbeGit(t, target, "config", "--local", "user.name", "target-user") if tc.clearLocal { runConfigProbeGit(t, target, "config", "--local", "--unset", "user.name") } diff --git a/internal/config/yaml_config_test.go b/internal/config/yaml_config_test.go index ef413f92a..39634a89e 100644 --- a/internal/config/yaml_config_test.go +++ b/internal/config/yaml_config_test.go @@ -4,10 +4,12 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" "github.com/spf13/viper" + "github.com/steveyegge/beads/internal/gitenv" "gopkg.in/yaml.v3" ) @@ -1537,3 +1539,90 @@ func TestMetricsNoticeShownResolvesUserGlobalOnly(t *testing.T) { } }) } + +// TestCheckSecretKeyGitSafety_RoutedCheckout covers the call site's two +// environment shapes. The guard is fail-open — a probe that cannot answer reads +// as "not tracked" reads as "allow the secret write" — so each shape has to be +// pinned separately: neither probe alone answers both, and the existing tests +// above are all in-tree-repo, which is the one shape that never needed either. +func TestCheckSecretKeyGitSafety_RoutedCheckout(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("routed checkout fixture requires Git") + } + 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) + } + } + } + runGit := func(t *testing.T, dir string, env []string, args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = dir, env + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("fixture git %v: %v: %s", args, err, out) + } + } + writeConfig := func(t *testing.T, workTree string) string { + t.Helper() + beadsDir := filepath.Join(workTree, ".beads") + if err := os.MkdirAll(beadsDir, 0o755); err != nil { + t.Fatal(err) + } + configPath := filepath.Join(beadsDir, "config.yaml") + if err := os.WriteFile(configPath, []byte("json: false\n"), 0o644); err != nil { + t.Fatal(err) + } + return configPath + } + + // The routed layout the scrub-only probe cannot see: the repository lives + // outside the work tree and is reachable only through GIT_DIR/GIT_WORK_TREE, + // so there is no in-tree .git for a scrubbed probe to discover from. + t.Run("legitimate routing refuses a tracked config", func(t *testing.T) { + root := t.TempDir() + gitDir, workTree := filepath.Join(root, "repo.git"), filepath.Join(root, "work") + if err := os.MkdirAll(workTree, 0o755); err != nil { + t.Fatal(err) + } + clean := gitenv.ScrubRoutingAndSuppression(os.Environ()) + runGit(t, root, clean, "init", "--quiet", "--bare", gitDir) + configPath := writeConfig(t, workTree) + routed := append(clean, "GIT_DIR="+gitDir, "GIT_WORK_TREE="+workTree) + runGit(t, workTree, routed, "add", "--", ".beads/config.yaml") + + t.Setenv("GIT_DIR", gitDir) + t.Setenv("GIT_WORK_TREE", workTree) + err := checkSecretGitTracked(configPath, "linear.api_key") + if err == nil { + t.Fatal("secret write allowed into a tracked config: the guard lost its only view of the repository") + } + if !strings.Contains(err.Error(), "refusing to write secret key") { + t.Fatalf("expected a refusal, got: %v", err) + } + }) + + // The poisoned layout the inherited probe cannot see. Pinned alongside so + // the fallback above cannot be widened into a way around the scrub. + t.Run("poisoned routing still refuses a tracked config", func(t *testing.T) { + root, decoy := t.TempDir(), t.TempDir() + clean := gitenv.ScrubRoutingAndSuppression(os.Environ()) + runGit(t, root, clean, "init", "--quiet") + runGit(t, decoy, clean, "init", "--quiet") + configPath := writeConfig(t, root) + runGit(t, root, clean, "add", "--", ".beads/config.yaml") + + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + t.Setenv("GIT_WORK_TREE", decoy) + err := checkSecretGitTracked(configPath, "linear.api_key") + if err == nil { + t.Fatal("secret write allowed into a tracked config: an inherited GIT_DIR hid the file behind a decoy repository") + } + if !strings.Contains(err.Error(), "refusing to write secret key") { + t.Fatalf("expected a refusal, got: %v", err) + } + }) +} diff --git a/internal/gitenv/routing.go b/internal/gitenv/routing.go index 1e533df0b..44951645e 100644 --- a/internal/gitenv/routing.go +++ b/internal/gitenv/routing.go @@ -83,26 +83,82 @@ func ScrubRouting(env []string) []string { // ScrubRoutingForOS removes Git routing entries using goos environment-key // semantics. It preserves non-routing controls such as GIT_OPTIONAL_LOCKS and -// GIT_NO_REPLACE_OBJECTS. +// GIT_NO_REPLACE_OBJECTS, plus explicit system/global config suppression. +// Custom config paths and inline values still lose their routing authority. +// +// Suppression cannot redirect a read, but it can blind one. Callers whose +// result carries authority must use ScrubRoutingAndSuppression instead. func ScrubRoutingForOS(env []string, goos string) []string { + return scrubRoutingForOS(env, goos, true) +} + +// ScrubRoutingAndSuppression removes Git routing entries using the current +// host's environment-key semantics, including the explicit config suppression +// that ScrubRouting deliberately preserves. +func ScrubRoutingAndSuppression(env []string) []string { + return ScrubRoutingAndSuppressionForOS(env, runtime.GOOS) +} + +// ScrubRoutingAndSuppressionForOS is ScrubRoutingForOS without the config +// suppression exemption: GIT_CONFIG_GLOBAL=/dev/null, GIT_CONFIG_SYSTEM=/dev/null +// and GIT_CONFIG_NOSYSTEM lose their effect along with every other routing key. +// +// Use it wherever a *missing* config value grants privilege rather than merely +// losing a preference. Suppression is harmless for a command that only reports +// what Git sees, but on an authority lookup such as beads.role an inherited +// GIT_CONFIG_NOSYSTEM=1 lets a caller blind the read, and a permissive +// miss-handler (routing.detectFromURL defaults to maintainer) converts that +// blinding into an escalation. Keeping reads and writes of the same key on this +// boundary also stops them from disagreeing about which config file they mean. +func ScrubRoutingAndSuppressionForOS(env []string, goos string) []string { + return scrubRoutingForOS(env, goos, false) +} + +func scrubRoutingForOS(env []string, goos string, keepSuppression bool) []string { cleaned := make([]string, 0, len(env)) for _, entry := range env { if IsRoutingKeyForOS(EntryKey(entry), goos) { - continue + if !keepSuppression || !isConfigSuppressionControl(entry, goos) { + continue + } } cleaned = append(cleaned, entry) } return cleaned } +// isConfigSuppressionControl recognizes the config controls that cannot +// redirect Git at a file of the caller's choosing. IsRoutingKeyForOS stays +// conservative: a key alone cannot distinguish null suppression from a custom +// file that can redirect selected operations. +// +// GIT_CONFIG_NOSYSTEM is preserved value-blind — unlike the null-path forms +// below there is no value it can take that names a file, so Git is left to +// interpret its Boolean, including the "false"/"0" spellings that re-enable +// system config and any invalid value it should report itself. +func isConfigSuppressionControl(entry, goos string) bool { + key := execenv.KeyIdentityForOS(EntryKey(entry), goos) + _, value, assigned := strings.Cut(entry, "=") + if !assigned { + return false + } + switch key { + case execenv.KeyIdentityForOS("GIT_CONFIG_NOSYSTEM", goos): + return true + case execenv.KeyIdentityForOS("GIT_CONFIG_GLOBAL", goos), execenv.KeyIdentityForOS("GIT_CONFIG_SYSTEM", goos): + return value == "/dev/null" || (goos == "windows" && strings.EqualFold(value, "NUL")) + } + return false +} + // ClearRouting permanently removes Git routing entries from the current // process. CLI callers use it as a command-lifetime authority boundary. It -// reports whether any entry was removed. +// retains the same config suppression as ScrubRouting and reports any removal. func ClearRouting() (bool, error) { removed := false for _, entry := range os.Environ() { key := EntryKey(entry) - if !IsRoutingKeyForOS(key, runtime.GOOS) { + if !IsRoutingKeyForOS(key, runtime.GOOS) || isConfigSuppressionControl(entry, runtime.GOOS) { continue } if err := os.Unsetenv(key); err != nil { diff --git a/internal/gitenv/routing_test.go b/internal/gitenv/routing_test.go index c07089b2a..36b733d24 100644 --- a/internal/gitenv/routing_test.go +++ b/internal/gitenv/routing_test.go @@ -2,8 +2,11 @@ package gitenv import ( "os" + "os/exec" + "path/filepath" "reflect" "runtime" + "strings" "testing" ) @@ -47,6 +50,130 @@ func TestScrubRoutingForOSUsesHostKeySemantics(t *testing.T) { } } +func TestScrubRoutingPreservesConfigSuppression(t *testing.T) { + for _, goos := range []string{"linux", "windows"} { + for _, tc := range []struct { + entry string + linux, windows bool + }{ + {"GIT_CONFIG_NOSYSTEM=1", true, true}, + {"GIT_CONFIG_NOSYSTEM=false", true, true}, + {"GIT_CONFIG_NOSYSTEM=invalid", true, true}, + {"GIT_CONFIG_NOSYSTEM", false, false}, + {"GIT_CONFIG_GLOBAL=/dev/null", true, true}, + {"GIT_CONFIG_SYSTEM=/dev/null", true, true}, + {"GIT_CONFIG_GLOBAL=nUl", false, true}, + {"git_config_system=NUL", true, true}, // Lowercase is a distinct POSIX key. + {"GIT_CONFIG_GLOBAL=", false, false}, + {"GIT_CONFIG_SYSTEM=custom.conf", false, false}, + {"GIT_CONFIG_GLOBAL=custom.conf", false, false}, + {"GIT_CONFIG_COUNT=1", false, false}, + } { + t.Run(goos+"/"+tc.entry, func(t *testing.T) { + input := []string{tc.entry, "GIT_DIR=decoy", "KEEP=value"} + want := []string{"KEEP=value"} + if (goos == "linux" && tc.linux) || (goos == "windows" && tc.windows) { + want = append([]string{tc.entry}, want...) + } + if got := ScrubRoutingForOS(input, goos); !reflect.DeepEqual(got, want) || input[0] != tc.entry { + t.Fatalf("filtered environment = %q, want %q; input %q", got, want, input) + } + }) + } + } +} + +// TestScrubRoutingAndSuppressionDropsSuppression is the inverse of the table +// above: every entry ScrubRouting preserves as suppression must lose its effect +// on the authority boundary, because a caller who can blind an authority lookup +// can steer its miss-handler. Non-routing controls still survive both scrubs. +func TestScrubRoutingAndSuppressionDropsSuppression(t *testing.T) { + for _, goos := range []string{"linux", "windows"} { + for _, entry := range []string{ + "GIT_CONFIG_NOSYSTEM=1", + "GIT_CONFIG_NOSYSTEM=false", + "GIT_CONFIG_NOSYSTEM=invalid", + "GIT_CONFIG_GLOBAL=/dev/null", + "GIT_CONFIG_SYSTEM=/dev/null", + "GIT_CONFIG_GLOBAL=custom.conf", + "GIT_CONFIG_COUNT=1", + "GIT_DIR=decoy", + } { + t.Run(goos+"/"+entry, func(t *testing.T) { + input := []string{entry, "GIT_OPTIONAL_LOCKS=1", "KEEP=value"} + want := []string{"GIT_OPTIONAL_LOCKS=1", "KEEP=value"} + // Lowercase POSIX keys are distinct names, so only the + // case-insensitive host drops a folded spelling. + if goos == "linux" && strings.HasPrefix(entry, "git_") { + want = append([]string{entry}, want...) + } + got := ScrubRoutingAndSuppressionForOS(input, goos) + if !reflect.DeepEqual(got, want) || input[0] != entry { + t.Fatalf("filtered environment = %q, want %q; input %q", got, want, input) + } + // The suppression-preserving scrub must be unaffected. + if kept := ScrubRoutingForOS(input, goos); len(kept) < len(got) { + t.Fatalf("ScrubRoutingForOS() = %q dropped more than the authority scrub %q", kept, got) + } + }) + } + } +} + +func TestScrubRoutingGitConfigSuppressionEffects(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("real Git config isolation test requires Git") + } + for _, entry := range os.Environ() { + key := EntryKey(entry) + if 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) + } + custom := filepath.Join(home, "custom.config") + for path, value := range map[string]string{filepath.Join(home, ".gitconfig"): "home", custom: "custom"} { + if err := os.WriteFile(path, []byte("[beads-isolation-fixture]\n\tvalue = "+value+"\n"), 0600); err != nil { + t.Fatal(err) + } + } + query := func(t *testing.T, env []string, want string) { + t.Helper() + cmd := exec.Command("git", "config", "--get", "beads-isolation-fixture.value") + cmd.Dir, cmd.Env = home, env + out, err := cmd.Output() + if want == "" { + if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 || len(out) != 0 { + t.Fatalf("suppressed config = %q (%v), want absence", out, err) + } + } else if err != nil || strings.TrimSpace(string(out)) != want { + t.Fatalf("config value = %q (%v), want %q", out, err, want) + } + } + base := ScrubRouting(os.Environ()) + t.Run("global_null", func(t *testing.T) { + // Pin a null system file separately so the HOME observation is owned. + query(t, append(base, "GIT_CONFIG_SYSTEM="+os.DevNull), "home") + query(t, append(ScrubRouting(append(base, "GIT_CONFIG_GLOBAL="+os.DevNull)), "GIT_CONFIG_SYSTEM="+os.DevNull), "") + }) + t.Run("custom_global_still_rejected", func(t *testing.T) { + query(t, append(base, "GIT_CONFIG_GLOBAL="+custom, "GIT_CONFIG_SYSTEM="+os.DevNull), "custom") + query(t, append(ScrubRouting(append(base, "GIT_CONFIG_GLOBAL="+custom)), "GIT_CONFIG_SYSTEM="+os.DevNull), "home") + }) + t.Run("nosystem", func(t *testing.T) { + // An owned system-file override models system config after filtering; + // only NOSYSTEM's preservation is under test in this real Git query. + query(t, append(base, "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_SYSTEM="+custom, "GIT_CONFIG_NOSYSTEM=0"), "custom") + query(t, append(ScrubRouting(append(base, "GIT_CONFIG_NOSYSTEM=1")), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_SYSTEM="+custom), "") + }) +} + func TestRoutingUnicodeKeysFollowSubprocessIdentity(t *testing.T) { for _, goos := range []string{"linux", "windows"} { for _, tc := range []struct { @@ -156,6 +283,9 @@ func TestClearRoutingPreservesNonRoutingGitControls(t *testing.T) { t.Setenv("GIT_CONFIG_COUNT", "1") t.Setenv("GIT_OPTIONAL_LOCKS", "1") t.Setenv("GIT_NO_REPLACE_OBJECTS", "1") + for key, value := range map[string]string{"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.DevNull, "GIT_CONFIG_SYSTEM": os.DevNull} { + t.Setenv(key, value) + } removed, err := ClearRouting() if err != nil { @@ -174,4 +304,9 @@ func TestClearRoutingPreservesNonRoutingGitControls(t *testing.T) { t.Fatalf("%s = %q, want 1", key, value) } } + for key, want := range map[string]string{"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.DevNull, "GIT_CONFIG_SYSTEM": os.DevNull} { + if got := os.Getenv(key); got != want { + t.Errorf("config suppression %s = %q, want %q", key, got, want) + } + } } diff --git a/internal/routing/routing.go b/internal/routing/routing.go index 0516939ff..e83019633 100644 --- a/internal/routing/routing.go +++ b/internal/routing/routing.go @@ -9,10 +9,15 @@ import ( "strings" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" ) +// Role detection is an authority lookup, so it also discards inherited config +// suppression: detectFromURL below answers a missed read with Maintainer, which +// would let a caller escalate by blinding the lookup rather than forging it. var gitCommandRunner = func(repoPath string, args ...string) ([]byte, error) { cmd := exec.Command("git", args...) + cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ()) if repoPath != "" { cmd.Dir = repoPath } diff --git a/internal/routing/routing_test.go b/internal/routing/routing_test.go index 9e0733595..338b172fe 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,143 @@ 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) + } + } + }) + } +} + +// TestDetectUserRoleIgnoresInheritedConfigSuppression is the deny-direction +// counterpart to the test above. Injecting a role is not the only way to steer +// role detection: an inherited config-suppression entry blinds the lookup +// instead, and DetectUserRole answers a miss with detectFromURL, whose +// no-remote arm returns Maintainer. So the reader must discard suppression too, +// not just redirects. +// +// Only the global-file vector is observable end to end: repository config is +// never suppressed by these variables, and a system file cannot be planted +// hermetically because GIT_CONFIG_SYSTEM= is itself scrubbed. The +// GIT_CONFIG_NOSYSTEM and GIT_CONFIG_SYSTEM forms are pinned one level down, in +// gitenv.TestScrubRoutingAndSuppressionDropsSuppression. +func TestDetectUserRoleIgnoresInheritedConfigSuppression(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()) + + home, target := t.TempDir(), t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\nrole = contributor\n"), 0o600); err != nil { + t.Fatal(err) + } + // No local role and no origin: the only arms left after a blinded read are + // detectFromURL's permissive ones, so an escalation would be visible. + initCmd := exec.Command("git", "init", "--quiet") + initCmd.Dir = target + initCmd.Env = gitenv.ScrubRouting(os.Environ()) + if out, err := initCmd.CombinedOutput(); err != nil { + t.Fatalf("fixture git init: %v: %s", err, out) + } + + for _, tc := range []struct { + name, blind string + }{ + // Fixture guard: without blinding the global role must be readable at + // all, otherwise every case below would pass for the wrong reason. + {"unblinded", ""}, + {"global_null", os.DevNull}, + } { + t.Run(tc.name, func(t *testing.T) { + if tc.blind != "" { + t.Setenv("GIT_CONFIG_GLOBAL", tc.blind) + } + var got UserRole + var err error + captureStderr(t, func() { got, err = DetectUserRole(target) }) + if err != nil { + t.Fatalf("DetectUserRole(target) error: %v", err) + } + if got != Contributor { + t.Errorf("DetectUserRole(target) = %q, want %q: a blinded role read must not escalate", got, Contributor) + } + }) + } +} diff --git a/internal/storage/domain/git.go b/internal/storage/domain/git.go index de2684a98..69bd6c9c3 100644 --- a/internal/storage/domain/git.go +++ b/internal/storage/domain/git.go @@ -76,7 +76,11 @@ type CommitInitArtifactsResult struct { DidCommit bool } -const beadsRoleConfigKey = "beads.role" +// BeadsRoleConfigKey is the git config key that carries role authority. +// It is exported because the GitRepository adapters select the strict +// role-authority environment on this key, so the two sides must not drift into +// separate spellings of one contract. +const BeadsRoleConfigKey = "beads.role" func NewGitUseCase(workDir string, repo GitRepository) GitUseCase { return &gitUseCaseImpl{workDir: workDir, repo: repo} @@ -149,14 +153,14 @@ func (u *gitUseCaseImpl) DetectFork(ctx context.Context) (bool, string, error) { } func (u *gitUseCaseImpl) BeadsRole(ctx context.Context) (string, bool, error) { - return u.repo.GetConfig(ctx, beadsRoleConfigKey) + return u.repo.GetConfig(ctx, BeadsRoleConfigKey) } func (u *gitUseCaseImpl) SetBeadsRole(ctx context.Context, role string) error { if role == "" { return fmt.Errorf("SetBeadsRole: role must not be empty") } - return u.repo.SetConfig(ctx, beadsRoleConfigKey, role) + return u.repo.SetConfig(ctx, BeadsRoleConfigKey, role) } func (u *gitUseCaseImpl) HasAnyRemotes(ctx context.Context) bool { diff --git a/internal/storage/domain/git/git.go b/internal/storage/domain/git/git.go index 4a9071546..2cbc4a9fa 100644 --- a/internal/storage/domain/git/git.go +++ b/internal/storage/domain/git/git.go @@ -21,6 +21,8 @@ func NewGitRepository(workDir string) domain.GitRepository { // NewInitGitRepository binds init artifact operations to the selected workDir. // The generic constructor retains inherited routing for its existing callers. +// beads.role reads and writes re-scrub this captured environment for config +// suppression as well; see roleAuthorityEnv for why that is not optional here. func NewInitGitRepository(workDir string) domain.GitRepository { return &gitRepositoryImpl{workDir: workDir, env: gitenv.ScrubRouting(os.Environ())} } @@ -102,13 +104,33 @@ func (r *gitRepositoryImpl) Init(ctx context.Context) error { return nil } +// roleAuthorityEnv returns the environment for a beads.role read or write. +// The role grants privilege, so this boundary drops the explicit config +// suppression that ScrubRouting deliberately preserves: an inherited +// GIT_CONFIG_GLOBAL=/dev/null blinds the lookup, and the proxied init tail +// answers a missing role by persisting "maintainer" into repository-local +// config, where it then outranks the global value for every later read. +// +// The strict scrub applies to whichever environment this repository already +// carries, not to os.Environ(), so a captured environment keeps its own HOME +// and loses only the suppression entries. Testing r.env for nil instead would +// leave the arm dead on the one production role path, which always arrives +// through NewInitGitRepository and therefore always carries a captured env. +func (r *gitRepositoryImpl) roleAuthorityEnv() []string { + env := r.env + if env == nil { + env = os.Environ() + } + return gitenv.ScrubRoutingAndSuppression(env) +} + func (r *gitRepositoryImpl) GetConfig(ctx context.Context, key string) (string, bool, error) { if key == "" { return "", false, fmt.Errorf("git: GetConfig: key must not be empty") } cmd := r.gitCmd(ctx, "config", "--get", key) - if key == "beads.role" && r.env == nil { - cmd.Env = gitenv.ScrubRouting(os.Environ()) + if key == domain.BeadsRoleConfigKey { + cmd.Env = r.roleAuthorityEnv() } out, err := cmd.Output() if err != nil { @@ -134,8 +156,8 @@ 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 == "beads.role" && r.env == nil { - cmd.Env = gitenv.ScrubRouting(os.Environ()) + if key == domain.BeadsRoleConfigKey { + cmd.Env = r.roleAuthorityEnv() } out, err := cmd.CombinedOutput() if err != nil { diff --git a/internal/storage/domain/git/git_test.go b/internal/storage/domain/git/git_test.go index 8e555986a..87a719a26 100644 --- a/internal/storage/domain/git/git_test.go +++ b/internal/storage/domain/git/git_test.go @@ -72,14 +72,17 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() { original, err := os.ReadFile(configPath) s.Require().NoError(err) for _, tc := range []struct { - name, key string - exitCode int + name, key string + exitCode int + roleReadFails bool }{ - {"malformed_config", "beads.role", 128}, - {"invalid_key", "invalid", 1}, - // beads.role reads now scrub GIT_CONFIG* routing, so a routing poison can - // only reach a key that is not role-scoped. - {"invalid_routing_boolean", "test.marker", 128}, + {"malformed_config", "beads.role", 128, true}, + {"invalid_key", "invalid", 1, false}, + // A beads.role read scrubs inherited config suppression, so a bad + // GIT_CONFIG_NOSYSTEM value never reaches that one key. Read a key that + // still inherits it, so the env-borne failure stays covered, and pin the + // role read's immunity below rather than dropping the case. + {"invalid_routing_boolean", "core.bare", 128, false}, } { s.Run(tc.name, func() { switch tc.name { @@ -104,10 +107,14 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() { diagnostic := strings.TrimSpace(string(exitErr.Stderr)) s.Require().NotEmpty(diagnostic) s.Contains(err.Error(), diagnostic) - if tc.name == "malformed_config" { + if tc.roleReadFails { _, _, roleErr := domain.NewGitUseCase(s.tmpDir, s.repo).BeadsRole(s.Ctx()) s.Require().Error(roleErr) s.ErrorAs(roleErr, &exitErr) + } else if tc.name == "invalid_routing_boolean" { + _, found, roleErr := domain.NewGitUseCase(s.tmpDir, s.repo).BeadsRole(s.Ctx()) + 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, @@ -467,9 +474,12 @@ func TestInitGitRepositoryUsesSelectedDirectory(t *testing.T) { t.Setenv(key, changedHome) } role, found, err := inherited.GetConfig(t.Context(), "beads.role") - // The generic reader runs under the caller's current environment, so the - // broken HOME config surfaces as a preserved read failure, not absence. + // 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") + require.ErrorContains(t, err, ".gitconfig") require.False(t, found) require.Empty(t, role) require.Error(t, inherited.SetConfig(t.Context(), "beads.role", "decoy")) @@ -482,3 +492,59 @@ func TestInitGitRepositoryUsesSelectedDirectory(t *testing.T) { }) } } + +// TestInitGitRepositoryRoleIgnoresInheritedConfigSuppression pins the role +// boundary on the environment the production path actually carries. cmd/bd's +// proxied init tail always rebinds the use case to NewInitGitRepository +// (cmd/bd/init_proxied_server.go), so the *captured* environment — not +// os.Environ() — is the one a beads.role lookup has to be strict about. An +// inherited GIT_CONFIG_GLOBAL=/dev/null that survives into that capture blinds +// the read, and the tail answers a missing role by writing "maintainer" into +// repository-local config, where it outranks the global value from then on. A +// guard keyed on the environment's provenance would therefore be dead exactly +// where the escalation happens. +// +// Only the global-file vector is observable end to end here, for the reasons +// internal/routing's counterpart test records: repository config is never +// suppressed by these variables, and GIT_CONFIG_SYSTEM= is itself +// scrubbed. The remaining forms are pinned in gitenv's suppression table. +func TestInitGitRepositoryRoleIgnoresInheritedConfigSuppression(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, target := t.TempDir(), t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + require.NoError(t, os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\n\trole = contributor\n"), 0600)) + // No local role in the target: the global file is the only place the answer + // can come from, so blinding it is visible as a miss. + initCmd := exec.Command("git", "init", "--quiet") + initCmd.Dir, initCmd.Env = target, gitenv.ScrubRouting(os.Environ()) + out, err := initCmd.CombinedOutput() + require.NoError(t, err, "fixture git init: %s", out) + + for _, tc := range []struct{ name, blind string }{ + // Fixture guard: the global role must be readable at all, otherwise the + // blinded case below would pass for the wrong reason. + {"unblinded", ""}, + {"global_null", os.DevNull}, + } { + t.Run(tc.name, func(t *testing.T) { + if tc.blind != "" { + t.Setenv("GIT_CONFIG_GLOBAL", tc.blind) + } + // Constructed inside the subtest: the constructor captures the + // environment, so the suppression entry has to be present first. + useCase := domain.NewGitUseCase(target, NewInitGitRepository(target)) + role, found, err := useCase.BeadsRole(t.Context()) + require.NoError(t, err) + require.True(t, found, "a blinded role read makes the init tail persist a maintainer default") + require.Equal(t, "contributor", role) + }) + } +} diff --git a/scripts/ci/test-windows-env-helpers.sh b/scripts/ci/test-windows-env-helpers.sh index 31894452b..e8be1e33c 100644 --- a/scripts/ci/test-windows-env-helpers.sh +++ b/scripts/ci/test-windows-env-helpers.sh @@ -35,6 +35,8 @@ required=( TestScrubEnvDoesNotEqualFoldUnicodeKeys TestStderrDirectedWindowsLeadingSlashIsFileTarget TestScrubRoutingUsesHostKeySemantics + TestScrubRoutingPreservesConfigSuppression + TestScrubRoutingAndSuppressionDropsSuppression ) for name in "${required[@]}"; do count=$(grep -Ec "^[[:space:]]*--- PASS: $name \\(" "$log" || true)