From 79631656c012f2bf706bfb481aec72cb77e4e14b Mon Sep 17 00:00:00 2001 From: ecuthiell Date: Sun, 27 Sep 2026 03:00:16 -0600 Subject: [PATCH] fix(config): pin role writes to a fresh common-config context (#6454) * fix(exec): match Windows environment key identity (#5618) Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions. Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell Signed-off-by: Ewen Cuthiell * fix(worktree): scrub inherited Git routing state Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics. Fixes #5531 Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell * refactor(worktree): explain owned filtering and remove an unused shim Document why filtering the fresh routing slice in place is safe and call the shared routing-key classifier directly from tests. Retain the two forwarders used by production worktree subprocess/removal paths. Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671 Bead: saa-cgh.23 Agent-Signature: unknown-model/unknown-reasoning * fix(config): isolate identity and tracked-file Git probes from routing Reuse the worktree routing owner for GetIdentity and isGitTracked so explicit cwd/path selection is not displaced by inherited repository, index or injected config state. Preserve identity precedence and the tracked-secret refusal contract, with real target/decoy regressions. Follow-up: https://github.com/gastownhall/beads/issues/6222 Dependency: https://github.com/gastownhall/beads/pull/5623 Reported-by: bee-ghosttrack Bead: saa-cgh.93 Agent-Signature: unknown-model/unknown-reasoning * test(execenv): exercise every environment operation under both host rules Thread the host choice through narrow private helpers behind the existing exported functions. Keep one normalization owner and retain native wrapper tests; the additional table covers both host branches for equality, prefix matching, last-wins lookup, filtering and input preservation. Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965 Bead: saa-cgh.78 Agent-Signature: unknown-model/unknown-reasoning * docs(worktree): explain startup Git environment scope (saa-cgh.23) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(execenv): exercise exported host policy wiring (saa-cgh.78) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(config): share subprocess key identity for Git routing (saa-cgh.93) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): isolate tracked-file guard from Git routing (saa-cgh.98) Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6356. Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(config): isolate role commands from Git routing (saa-cgh.99) Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357. Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(env): exercise shared key helpers on native Windows (saa-cgh.78) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(config): explain role command routing policy (saa-cgh.99) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): retain legitimate inherited tracking context (saa-cgh.98) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(hooks): isolate trusted global configuration fixture (saa-cgh.98) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): isolate role cleanup in the selected repository (saa-cgh.109.4) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): reset only common local role configuration (saa-cgh.109.10) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): scope hooks-path cleanup to selected common config (saa-cgh.109.11) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(hooks): make worktree role preservation independent (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Report selected config read failures during hook reset (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): keep successful config stdout separate from diagnostics (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * fix(config): pin role writes to fresh common context (GH#6384) (saa-cgh.120.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(config): retain Git diagnostics from role writes (saa-cgh.120.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(config): assert the actual Git lock diagnostic (saa-cgh.120.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(config,hooks): restore the inherited-tracking fallback in the secret guard Maintainer review fixes for PR #6454 (adopt-pr iteration 1). The scorecard approved at 913/1000 with no blocker or major surviving synthesis; these are the non-gating findings that were cheap to close while the fixup was open. Finding 1 (minor, security) is the only in-range regression in the report. The range switched internal/config.isGitTracked from the inherited environment to gitenv.ScrubRouting only, so a config.yaml tracked solely through legitimate routing -- a bare repository whose work tree is named by GIT_DIR/GIT_WORK_TREE -- reported untracked, and a secret-key write that upstream-base refused was silently allowed. Restores the scrubbed-then-inherited union the same stack already gave cmd/bd.isGitTrackedFile. Finding 4 (nit) composes with it rather than conflicting, so both land as one change: the inherited probe now runs only when the scrubbed probe failed for a configuration reason. git's exit codes discriminate exactly -- 0 tracked, 1 repository reached but path untracked (final), 128 no reachable repository -- so the ordinary untracked-hook miss no longer spawns a second `git ls-files` while the bare-work-tree fallback is preserved. Finding 2 (minor). scrubWorktreeRemovalGitEnvForOS keyed its stricter no-optional-locks policy on strings.ToUpper while the rest of the PR uses execenv key identity. The two disagree in both directions on Windows: GIT_OPTIONAL_LOCKS with a dotted capital I (U+0130) survived the scrub although Git honors it, and GIT_OPTIONAL_LOCK with a long s (U+017F) was dropped although os/exec keeps it distinct. normalizeWorktreeGitEnvKey is deleted in favour of execenv.KeyEqualForOS. Base applied ToUpper on all platforms, so this is a consistency fix in newly rewritten code, not a regression. Finding 5 (nit). The comment above resetHooksPathIfBeadsManaged's probe asserted that repoRoot and commonDir share the cached Git context. Probed false: with cwd A and GIT_DIR=B/.git, `git rev-parse --git-common-dir --show-toplevel` prints B/.git and A. Restated as intent. Finding 3 (scrubGitHookEnv is a fifth, strictly weaker routing scrubber) is deliberately not taken here: cmd/bd/export_auto.go is untouched by this range, so the hazard is byte-identical at base, and the synthesis scoped it to a follow-up bead rather than growing this stack. Each fix is mutation-proved. Reverting isGitTracked reds only the new TestSecretGitTrackingHonorsInheritedBareWorkTree -- including "refusal = ", the actual security consequence -- while the incumbent decoy test stays green, so the pin adds coverage rather than duplicating it. Restoring ToUpper reds only the new Windows row, showing both directions at once. TestGuardHookWritePathHonorsInheritedRepository gains a fixture guard asserting its scrubbed probe fails for a configuration reason rather than exit 1, so a future fixture change cannot silently make the fallback unreachable. scrubWorktreeRemovalGitEnvForOS had no test at all before this. Green locally: ./internal/config, ./internal/execenv, ./internal/gitenv, ./internal/githooksenv, ./internal/gittraceenv, ./internal/metrics, ./scripts, ./internal/beads (the GIT_CONFIG_GLOBAL blast radius neither reviewer ran), and a blast-radius cmd/bd run over the hooks, worktree, role and uninstall suites. Co-Authored-By: Claude Opus 5 --------- Signed-off-by: Ewen Cuthiell Co-authored-by: Bee Co-authored-by: Gas City Adopt-PR Co-authored-by: Julian Knutsen Co-authored-by: Claude Opus 5 --- .github/workflows/pr.yml | 5 + cmd/bd/config.go | 64 +++- cmd/bd/config_test.go | 272 +++++++++++++++ cmd/bd/dolt_remote_reset_data.go | 11 +- cmd/bd/dolt_remote_reset_data_test.go | 22 ++ cmd/bd/hooks.go | 71 +++- cmd/bd/hooks_guard_test.go | 220 +++++++++++++ cmd/bd/hooks_worktree_test.go | 60 +++- cmd/bd/main.go | 3 + cmd/bd/uninstall_config_test.go | 223 ++++++++++++- cmd/bd/worktree_cmd.go | 99 +++--- cmd/bd/worktree_remove_test.go | 105 +++++- cmd/bd/worktree_test.go | 310 +++++++++++++++++- docs/reference/worktrees.md | 5 + internal/config/config.go | 10 +- internal/config/git_routing_test.go | 189 +++++++++++ internal/config/worktree_config_test.go | 30 ++ internal/config/yaml_config.go | 36 +- internal/execenv/execenv.go | 155 +++++++++ internal/execenv/execenv_test.go | 193 +++++++++++ internal/gitenv/routing.go | 107 ++++++ internal/gitenv/routing_test.go | 174 ++++++++++ internal/githooksenv/githooksenv.go | 23 +- internal/githooksenv/githooksenv_test.go | 32 ++ internal/gittraceenv/gittraceenv.go | 15 +- internal/gittraceenv/gittraceenv_test.go | 12 + internal/metrics/metrics_test.go | 31 ++ internal/metrics/spawn.go | 10 +- internal/storage/dolt/credentials.go | 41 +-- internal/storage/dolt/credentials_test.go | 62 ++++ scripts/ci/test-windows-env-helpers.sh | 45 +++ scripts/ci_workflow_test.go | 16 + scripts/repro-dolt-prod-timeouts/main.go | 28 +- scripts/repro-dolt-prod-timeouts/main_test.go | 3 +- 34 files changed, 2504 insertions(+), 178 deletions(-) create mode 100644 internal/config/git_routing_test.go create mode 100644 internal/execenv/execenv.go create mode 100644 internal/execenv/execenv_test.go create mode 100644 internal/gitenv/routing.go create mode 100644 internal/gitenv/routing_test.go create mode 100644 scripts/ci/test-windows-env-helpers.sh diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 36d7d0d96..3f90bca75 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -520,6 +520,11 @@ jobs: shell: bash run: go test -tags gms_pure_go -count=1 -run '^(TestCleanEnvUsesHostKeySemantics|TestBenchmarkCommandBuildersStripDoltEnvOverrides)$' ./scripts/repro-dolt-prod-timeouts + - name: Check shared environment key semantics + if: matrix.os == 'windows-latest' + shell: bash + run: bash scripts/ci/test-windows-env-helpers.sh + # Fast check to catch accidental .beads/issues.jsonl changes from contributors check-no-beads-changes: name: Check for .beads changes diff --git a/cmd/bd/config.go b/cmd/bd/config.go index 3510473a5..e9fd4ba68 100644 --- a/cmd/bd/config.go +++ b/cmd/bd/config.go @@ -14,6 +14,7 @@ import ( "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/remotecache" "github.com/steveyegge/beads/internal/tracker" @@ -115,6 +116,41 @@ Examples: 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. +func newRoleConfigWriter() (func(...string) error, error) { + dir, err := os.Getwd() + if err != nil { + return nil, err + } + env := gitenv.ScrubRouting(os.Environ()) + probe := exec.Command("git", "rev-parse", "--git-common-dir") + probe.Dir, probe.Env = dir, env + out, err := probe.Output() + if err != nil { + if exit, ok := err.(*exec.ExitError); ok && len(exit.Stderr) > 0 { + err = fmt.Errorf("%w: %s", err, strings.TrimSpace(string(exit.Stderr))) + } + return nil, fmt.Errorf("resolving common Git config: %w", err) + } + commonDir := git.NormalizePath(strings.TrimSpace(string(out))) + if commonDir == "" { + return nil, fmt.Errorf("Git returned an empty common directory") + } + if !filepath.IsAbs(commonDir) { + commonDir = filepath.Join(dir, commonDir) + } + return func(args ...string) error { + // Callers supply only the fixed role key, validated values and unset flag. + cmd := exec.Command("git", append([]string{"--git-dir", commonDir, "config", "--local"}, args...)...) //nolint:gosec // private validated config operations + cmd.Dir, cmd.Env = dir, env + if output, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(output))) + } + return nil + }, nil +} + var configSetCmd = &cobra.Command{ Use: "set ", Short: "Set a configuration value", @@ -198,8 +234,11 @@ var configSetCmd = &cobra.Command{ if !validRoles[value] { return HandleError("invalid role %q (valid values: maintainer, contributor)", value) } - cmd := exec.Command("git", "config", "beads.role", value) //nolint:gosec // value is validated against allowlist above - if err := cmd.Run(); err != nil { + write, err := newRoleConfigWriter() + if err != nil { + return HandleError("setting beads.role in git config: %v", err) + } + if err := write("beads.role", value); err != nil { return HandleError("setting beads.role in git config: %v", err) } if jsonOutput { @@ -344,6 +383,7 @@ var configGetCmd = &cobra.Command{ if key == "beads.role" { cmd := exec.Command("git", "config", "--get", "beads.role") + cmd.Env = gitenv.ScrubRouting(os.Environ()) output, err := cmd.Output() value := strings.TrimSpace(string(output)) if err != nil { @@ -596,8 +636,11 @@ var configUnsetCmd = &cobra.Command{ } if key == "beads.role" { - gitCmd := exec.Command("git", "config", "--unset", "beads.role") - if err := gitCmd.Run(); err != nil { + write, err := newRoleConfigWriter() + if err != nil { + return HandleError("unsetting beads.role in git config: %v", err) + } + if err := write("--unset", "beads.role"); err != nil { return HandleError("unsetting beads.role in git config: %v", err) } if jsonOutput { @@ -887,10 +930,15 @@ Examples: } } - for _, p := range gitPairs { - cmd := exec.Command("git", "config", "beads.role", p.value) //nolint:gosec // value is validated against allowlist above - if err := cmd.Run(); err != nil { - return HandleError("setting %s in git config: %v", p.key, err) + if len(gitPairs) > 0 { + write, err := newRoleConfigWriter() + if err != nil { + return HandleError("setting beads.role in git config: %v", err) + } + for _, p := range gitPairs { + if err := write("beads.role", p.value); err != nil { + return HandleError("setting %s in git config: %v", p.key, err) + } } } diff --git a/cmd/bd/config_test.go b/cmd/bd/config_test.go index 752796415..3b8ad0ad5 100644 --- a/cmd/bd/config_test.go +++ b/cmd/bd/config_test.go @@ -7,14 +7,18 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" + "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/storage/dolt" "github.com/steveyegge/beads/internal/types" + "github.com/stretchr/testify/require" ) func TestConfigCommands(t *testing.T) { @@ -275,6 +279,214 @@ func TestBeadsRoleGitConfig(t *testing.T) { }) } +func TestBeadsRoleCommandsIgnoreInheritedGitRouting(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) + } + pinJSONOutput(t, false) + runGit := func(t *testing.T, repo string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = repo + cmd.Env = gitenv.ScrubRouting(os.Environ()) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("fixture git %v: %v: %s", args, err, out) + } + return strings.TrimSpace(string(out)) + } + target, decoy := t.TempDir(), t.TempDir() + for _, repo := range []string{target, decoy} { + runGit(t, repo, "init", "--quiet") + runGit(t, repo, "config", "--local", "core.hooksPath", ".git/hooks") + } + t.Chdir(target) + localRole := func(t *testing.T, repo string) string { + t.Helper() + for _, line := range strings.Split(runGit(t, repo, "config", "--local", "--list"), "\n") { + if value, ok := strings.CutPrefix(line, "beads.role="); ok { + return value + } + } + return "" + } + commands := []struct { + name string + cmd *cobra.Command + args []string + wantRole string + wantOutput string + }{ + {"set", configSetCmd, []string{"beads.role", "contributor"}, "contributor", "Set beads.role = contributor (in git config)"}, + {"get", configGetCmd, []string{"beads.role"}, "maintainer", "maintainer"}, + {"unset", configUnsetCmd, []string{"beads.role"}, "", "Unset beads.role (in git config)"}, + {"set-many", configSetManyCmd, []string{"beads.role=contributor"}, "contributor", "Set beads.role = contributor (in git config)"}, + } + for _, command := range commands { + for _, poison := range []struct { + name string + env map[string]string + }{ + {"repository", map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy}}, + {"inline_config", map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "beads.role", "GIT_CONFIG_VALUE_0": "injected-role"}}, + } { + t.Run(command.name+"/"+poison.name, func(t *testing.T) { + runGit(t, target, "config", "--local", "beads.role", "maintainer") + runGit(t, decoy, "config", "--local", "beads.role", "decoy-role") + for key, value := range poison.env { + t.Setenv(key, value) + } + out := captureStdout(t, func() error { return command.cmd.RunE(command.cmd, command.args) }) + if strings.TrimSpace(out) != command.wantOutput { + t.Errorf("handler output = %q, want %q", out, command.wantOutput) + } + if got := localRole(t, target); got != command.wantRole { + t.Errorf("target role = %q, want %q", got, command.wantRole) + } + if got := localRole(t, decoy); got != "decoy-role" { + t.Errorf("decoy role changed to %q", got) + } + for key, value := range poison.env { + if os.Getenv(key) != value { + t.Errorf("handler changed parent environment %s", key) + } + } + }) + } + } + for _, command := range []struct { + name string + cmd *cobra.Command + args []string + }{ + {"invalid set", configSetCmd, []string{"beads.role", "admin"}}, + {"invalid batch", configSetManyCmd, []string{"beads.role=contributor", "beads.role=admin"}}, + } { + t.Run(command.name, func(t *testing.T) { + runGit(t, target, "config", "--local", "beads.role", "maintainer") + var err error + out := captureStderr(t, func() { err = command.cmd.RunE(command.cmd, command.args) }) + if code, ok := exitCodeFromError(err); !ok || code != 1 || !strings.Contains(out, "invalid role") { + t.Errorf("invalid role refusal = %v, stderr %q", err, out) + } + if got := localRole(t, target); got != "maintainer" { + t.Errorf("invalid role changed target to %q", got) + } + }) + } + t.Run("absent role", func(t *testing.T) { + runGit(t, target, "config", "--local", "beads.role", "maintainer") + runGit(t, target, "config", "--local", "--unset", "beads.role") + out := captureStdout(t, func() error { return configGetCmd.RunE(configGetCmd, []string{"beads.role"}) }) + if strings.TrimSpace(out) != "beads.role (not set in git config)" { + t.Errorf("absent role output = %q", out) + } + var err error + stderr := captureStderr(t, func() { err = configUnsetCmd.RunE(configUnsetCmd, []string{"beads.role"}) }) + if code, ok := exitCodeFromError(err); !ok || code != 1 || !strings.Contains(stderr, "unsetting beads.role in git config") { + t.Errorf("absent unset = %v, stderr %q", err, stderr) + } + }) + t.Run("default global role", func(t *testing.T) { + runGit(t, target, "config", "--local", "beads.role", "maintainer") + runGit(t, target, "config", "--local", "--unset", "beads.role") + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\n\trole = contributor\n"), 0o600); err != nil { + t.Fatal(err) + } + out := captureStdout(t, func() error { return configGetCmd.RunE(configGetCmd, []string{"beads.role"}) }) + if strings.TrimSpace(out) != "contributor" { + t.Errorf("default global role output = %q", out) + } + }) +} + +func TestBeadsRoleWritesUseFreshCommonConfig(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)) + } + } + pinJSONOutput(t, false) + t.Cleanup(git.ResetCaches) + for _, kind := range []string{"linked", "bare", "separate", "nonrepo"} { + t.Run(kind, func(t *testing.T) { + home := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + run := func(dir string, args ...string) string { + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ()) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "fixture git %v: %s", args, out) + return strings.TrimSpace(string(out)) + } + main, decoy, target := t.TempDir(), t.TempDir(), t.TempDir() + for _, dir := range []string{main, decoy} { + run(dir, "init", "--quiet") + run(dir, "config", "--local", "core.hooksPath", ".git/hooks") + } + switch kind { + case "linked": + run(main, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "-c", "commit.gpgSign=false", "commit", "--allow-empty", "-m", "seed") + run(main, "config", "extensions.worktreeConfig", "true") + run(main, "worktree", "add", "--detach", target) + run(target, "config", "--worktree", "beads.role", "private-role") + case "bare": + run(home, "init", "--bare", target) + case "separate": + run(home, "init", "--separate-git-dir", filepath.Join(home, "external git"), target) + } + t.Chdir(decoy) + git.ResetCaches() + cached, err := git.GetGitCommonDir() + require.NoError(t, err) + t.Chdir(target) + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + t.Setenv("GIT_CONFIG", filepath.Join(decoy, ".git", "config")) + before, err := os.ReadFile(filepath.Join(decoy, ".git", "config")) + require.NoError(t, err) + for _, command := range []struct { + cmd *cobra.Command + args []string + }{ + {configSetCmd, []string{"beads.role", "contributor"}}, + {configSetManyCmd, []string{"beads.role=maintainer", "beads.role=contributor"}}, + {configUnsetCmd, []string{"beads.role"}}, + } { + if kind == "nonrepo" { + captureStderr(t, func() { require.Error(t, command.cmd.RunE(command.cmd, command.args)) }) + continue + } + captureStdout(t, func() error { return command.cmd.RunE(command.cmd, command.args) }) + role := run(target, "config", "--local", "--list") + require.Equal(t, command.cmd != configUnsetCmd, strings.Contains(role, "beads.role=contributor")) + if kind == "linked" { + require.Equal(t, "private-role", run(target, "config", "--worktree", "--get", "beads.role")) + } + } + after, err := os.ReadFile(filepath.Join(decoy, ".git", "config")) + require.NoError(t, err) + require.Equal(t, before, after) + stillCached, err := git.GetGitCommonDir() + require.NoError(t, err) + require.Equal(t, cached, stillCached) + }) + } +} + // TestIsValidRemoteURL tests the remote URL validation function func TestIsValidRemoteURL(t *testing.T) { tests := []struct { @@ -921,3 +1133,63 @@ func TestConfigSetManyValidationIntegration(t *testing.T) { } }) } + +func TestBeadsRoleWriteErrorsRetainGitDiagnostics(t *testing.T) { + t.Setenv("LC_ALL", "C") + pinJSONOutput(t, false) + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + require.NoError(t, os.Unsetenv(key)) + } + } + for _, operation := range []struct { + name string + cmd *cobra.Command + args []string + }{ + {"set", configSetCmd, []string{"beads.role", "contributor"}}, + {"set-many", configSetManyCmd, []string{"beads.role=contributor"}}, + {"unset", configUnsetCmd, []string{"beads.role"}}, + } { + for _, failure := range []string{"nonrepo", "config_lock", "duplicate"} { + t.Run(operation.name+"/"+failure, func(t *testing.T) { + home := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + repo := newGitRepo(t) + t.Chdir(repo) + run := func(args ...string) { + cmd := exec.Command("git", args...) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", out) + } + run("config", "--local", "beads.role", "maintainer") + want := "not a git repository" + switch failure { + case "nonrepo": + t.Chdir(t.TempDir()) + case "config_lock": + require.NoError(t, os.WriteFile(filepath.Join(repo, ".git", "config.lock"), []byte("owned lock"), 0600)) + want = "could not lock config file" + case "duplicate": + run("config", "--local", "--add", "beads.role", "contributor") + want = "multiple values" + } + configPath := filepath.Join(repo, ".git", "config") + before, err := os.ReadFile(configPath) + require.NoError(t, err) + stderr := captureStderr(t, func() { err = operation.cmd.RunE(operation.cmd, operation.args) }) + code, ok := exitCodeFromError(err) + require.True(t, ok) + require.Equal(t, 1, code) + require.Contains(t, stderr, want) + after, readErr := os.ReadFile(configPath) + require.NoError(t, readErr) + require.Equal(t, before, after, "failed role write changed config") + }) + } + } +} diff --git a/cmd/bd/dolt_remote_reset_data.go b/cmd/bd/dolt_remote_reset_data.go index 8f9af4159..1ea1b5468 100644 --- a/cmd/bd/dolt_remote_reset_data.go +++ b/cmd/bd/dolt_remote_reset_data.go @@ -157,16 +157,7 @@ func deleteGitDoltDataRefs(ctx context.Context, gitURL string, refs []string) er // hooks disabled via GIT_CONFIG_PARAMETERS, preserving any parameters the // caller already set (mirrors applyNoGitHooksToCmd in internal/storage/dolt). func envWithNoGitHooks() []string { - base := os.Environ() - merged := githooksenv.AppendParameter(githooksenv.Extract(base), githooksenv.NoHooksParam) - env := make([]string, 0, len(base)+1) - prefix := githooksenv.ParametersEnv + "=" - for _, e := range base { - if !strings.HasPrefix(e, prefix) { - env = append(env, e) - } - } - return append(env, prefix+merged) + return githooksenv.DisabledEnv(os.Environ()) } // clearDoltFileStore removes the contents of a native Dolt file-store diff --git a/cmd/bd/dolt_remote_reset_data_test.go b/cmd/bd/dolt_remote_reset_data_test.go index 9e66f7645..a39dc06af 100644 --- a/cmd/bd/dolt_remote_reset_data_test.go +++ b/cmd/bd/dolt_remote_reset_data_test.go @@ -3,9 +3,12 @@ package main import ( "os" "path/filepath" + "slices" "testing" "github.com/dolthub/dolt/go/store/blobstore" + "github.com/steveyegge/beads/internal/execenv" + "github.com/steveyegge/beads/internal/githooksenv" ) // TestResetDataRefNamesMatchDolt keeps the locally pinned data-plane ref @@ -21,6 +24,25 @@ func TestResetDataRefNamesMatchDolt(t *testing.T) { } } +func TestEnvWithNoGitHooksPreservesExistingParameters(t *testing.T) { + const existing = "'user.email=ci@example.com'" + t.Setenv(githooksenv.ParametersEnv, existing) + t.Setenv("BEADS_TEST_NO_HOOKS_KEEP", "GIT_CONFIG_PARAMETERS=unrelated-value") + + // Build the expected slice independently of Without/DisabledEnv so a + // stale entry cannot hide behind Extract's last-wins lookup. + var want []string + for _, entry := range os.Environ() { + if !execenv.KeyEqual(execenv.EntryKey(entry), githooksenv.ParametersEnv) { + want = append(want, entry) + } + } + want = append(want, githooksenv.ParametersEnv+"="+existing+" "+githooksenv.NoHooksParam) + if got := envWithNoGitHooks(); !slices.Equal(got, want) { + t.Fatalf("envWithNoGitHooks() differs from the expected environment: got %d entries, want %d", len(got), len(want)) + } +} + func TestClassifyResetDataRemote(t *testing.T) { makeBareGitRepo := func(t *testing.T) string { dir := t.TempDir() diff --git a/cmd/bd/hooks.go b/cmd/bd/hooks.go index 4954e29fe..be6ca1747 100644 --- a/cmd/bd/hooks.go +++ b/cmd/bd/hooks.go @@ -15,6 +15,7 @@ import ( "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/debug" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" @@ -854,16 +855,33 @@ func isBdOwnedHookFile(path string) bool { return err == nil && versionInfo.IsBdHook } -// isGitTrackedFile reports whether path is tracked by git in the repository -// containing it. Errors (not a repo, path inside .git/, no work tree) count +// isGitTrackedFile reports whether either the containing repository or the +// inherited Git context tracks path. If neither probe succeeds, errors count // as untracked — the guard only blocks writes it can prove are unsafe. func isGitTrackedFile(path string) bool { dir := filepath.Dir(path) base := filepath.Base(path) - // #nosec G204 G702 - fixed "git" command; dir/base come from the hooks - // directory bd itself resolved, not user input - cmd := exec.Command("git", "-C", dir, "ls-files", "--error-unmatch", "--", base) - return cmd.Run() == nil + inherited := os.Environ() + // Check the containing repository first so inherited routing cannot hide a + // tracked hook. The fallback preserves bare work trees and trusted config. + // Exit 1 is git's "repository reached, path is not tracked" answer and is + // final, so the second probe runs only when the scrubbed environment failed + // for a configuration reason (no reachable repository) rather than spawning + // a second `git ls-files` on every ordinary miss. + for _, env := range [][]string{gitenv.ScrubRouting(inherited), inherited} { + // #nosec G204 G702 - fixed "git" command; dir/base come from the hooks + // directory bd itself resolved, not user input + cmd := exec.Command("git", "-C", dir, "ls-files", "--error-unmatch", "--", base) + cmd.Env = env + err := cmd.Run() + if err == nil { + return true + } + if exit, ok := err.(*exec.ExitError); ok && exit.ExitCode() == 1 { + return false + } + } + return false } //nolint:unparam // force and chain kept for CLI flag compatibility; section markers make them no-ops @@ -1401,10 +1419,24 @@ func resetHooksPathIfBeadsManaged() error { return nil // not in a git repo } + // These checks are defensive. repoRoot and commonDir are resolved + // independently, and an inherited GIT_DIR can make them name different + // repositories, so their agreement is intent rather than an invariant. + // The common-dir pin states that intent: --git-dir addresses the common + // config through either gitdir, while repoRoot is only the subprocess cwd. + commonDir, err := git.GetGitCommonDir() + if err != nil { + return fmt.Errorf("resolve Git common directory for role reset: %w", err) + } + if commonDir == "" { + return fmt.Errorf("empty Git common directory for role reset") + } + configEnv := gitenv.ScrubRouting(os.Environ()) var failures []string - cmd := exec.Command("git", "config", "--get", "core.hooksPath") + cmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--get", "core.hooksPath") cmd.Dir = repoRoot + cmd.Env = configEnv if out, err := cmd.Output(); err == nil { hooksPath := strings.TrimSpace(string(out)) // Matches both relative (legacy) and absolute (GH#2414) beads hooks @@ -1412,29 +1444,42 @@ func resetHooksPathIfBeadsManaged() error { // doctor.CheckHooksPath/FixHooksPath so uninstall and `bd doctor --fix` // cannot disagree about what "beads-managed" means. if doctor.IsBeadsManagedHooksPath(repoRoot, hooksPath) { - unsetCmd := exec.Command("git", "config", "--unset", "core.hooksPath") + unsetCmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--unset", "core.hooksPath") unsetCmd.Dir = repoRoot + unsetCmd.Env = configEnv if output, err := unsetCmd.CombinedOutput(); err != nil { failures = append(failures, fmt.Sprintf("core.hooksPath: %v (output: %s)", err, strings.TrimSpace(string(output)))) } } + } else if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 { + var diagnostic string + if ok { + diagnostic = strings.TrimSpace(string(exit.Stderr)) + } + failures = append(failures, fmt.Sprintf("read core.hooksPath: %v (output: %s)", err, diagnostic)) } - // core.hooksPath not set at all — nothing to reset there; still fall - // through to beads.role below. + // Exit 1 means the key is absent. Other read failures must remain visible. // Read before unsetting rather than treating git's exit 5 as "already // absent". Exit 5 also means "the key has multiple values, refusing an // ambiguous unset" — a repo with a duplicated beads.role (bad merge, hand // edit) would then report a clean uninstall while leaving the key set, // which is the exact failure this is supposed to stop. - getRoleCmd := exec.Command("git", "config", "--get", "beads.role") + // 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. + getRoleCmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--get", "beads.role") getRoleCmd.Dir = repoRoot - if _, err := getRoleCmd.Output(); err == nil { - roleCmd := exec.Command("git", "config", "--unset", "beads.role") + getRoleCmd.Env = configEnv + 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 if output, err := roleCmd.CombinedOutput(); err != nil { failures = append(failures, fmt.Sprintf("beads.role: %v (output: %s)", err, strings.TrimSpace(string(output)))) } + } else if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 { + failures = append(failures, fmt.Sprintf("read beads.role: %v (output: %s)", err, strings.TrimSpace(string(out)))) } if len(failures) > 0 { diff --git a/cmd/bd/hooks_guard_test.go b/cmd/bd/hooks_guard_test.go index 9f91026d0..4297597af 100644 --- a/cmd/bd/hooks_guard_test.go +++ b/cmd/bd/hooks_guard_test.go @@ -4,12 +4,93 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" ) +func TestGuardHookWritePathIgnoresInheritedGitRouting(t *testing.T) { + runGit := func(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("git %v: %v\n%s", args, err, out) + } + } + target, decoy := t.TempDir(), t.TempDir() + for _, repo := range []string{target, decoy} { + runGit(repo, "init", "--quiet") + runGit(repo, "config", "core.hooksPath", ".git/hooks") + } + hooksDir := filepath.Join(target, "hooks") + if err := os.Mkdir(hooksDir, 0755); err != nil { + t.Fatal(err) + } + foreign := filepath.Join(hooksDir, "pre-commit") + owned := filepath.Join(hooksDir, "pre-push") + untracked := filepath.Join(hooksDir, "post-merge") + contents := map[string]string{ + foreign: "#!/bin/sh\necho team hook\n", + owned: "#!/bin/sh\n" + generateHookSection("pre-push"), + untracked: "#!/bin/sh\necho untracked hook\n", + filepath.Join(decoy, "decoy-only"): "decoy\n", + } + for path, content := range contents { + if err := os.WriteFile(path, []byte(content), 0755); err != nil { + t.Fatal(err) + } + } + runGit(target, "add", "--force", "--", "hooks/pre-commit", "hooks/pre-push") + runGit(decoy, "add", "--force", "--", "decoy-only") + for _, tc := range []struct { + name string + env map[string]string + }{ + {"repository", map[string]string{"GIT_DIR": filepath.Join(decoy, ".git")}}, + {"worktree", map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy}}, + {"index", map[string]string{"GIT_INDEX_FILE": filepath.Join(decoy, ".git", "index")}}, + {"inline_config", map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.worktree", "GIT_CONFIG_VALUE_0": decoy}}, + } { + t.Run(tc.name, func(t *testing.T) { + for key, value := range tc.env { + t.Setenv(key, value) + } + if !isGitTrackedFile(foreign) { + t.Error("inherited routing hid the tracked hook") + } + if err := guardHookWritePath(foreign, false); err == nil || !strings.Contains(err.Error(), "tracked by git") { + t.Errorf("expected tracked-file refusal, got %v", err) + } + if err := guardHookWritePath(foreign, true); err != nil { + t.Errorf("shared tracked hook refused: %v", err) + } + if !isGitTrackedFile(owned) { + t.Error("owned hook fixture must remain tracked") + } + if err := guardHookWritePath(owned, false); err != nil { + t.Errorf("bd-owned tracked hook refused: %v", err) + } + if isGitTrackedFile(untracked) { + t.Error("untracked hook reported as tracked") + } + if err := guardHookWritePath(untracked, false); err != nil { + t.Errorf("untracked hook refused: %v", err) + } + for path, want := range contents { + got, err := os.ReadFile(path) + if err != nil || string(got) != want { + t.Errorf("guard changed %s: content=%q, err=%v", path, got, err) + } + } + }) + } +} + // setupGuardTestRepo creates a git repo with one tracked script and chdirs // into it. Returns the repo dir. func setupGuardTestRepo(t *testing.T) string { @@ -249,3 +330,142 @@ func TestApplyHookMigrationRefusesSymlink(t *testing.T) { t.Fatalf("expected symlink refusal, got: %v", err) } } + +func TestGuardHookWritePathHonorsInheritedRepository(t *testing.T) { + // Isolate configuration and restore every inherited routing entry afterwards. + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, os.Getenv(key)) + } + } + if _, err := gitenv.ClearRouting(); err != nil { + t.Fatal(err) + } + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(home, "nondefault-config")) + t.Setenv("GIT_CONFIG_SYSTEM", os.DevNull) + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + t.Setenv("GIT_TEST_ASSUME_DIFFERENT_OWNER", "0") + for _, name := range []string{"bare_worktree", "global_safe_directory"} { + t.Run(name, func(t *testing.T) { + repo, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + runGit := func(args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = repo + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + if name == "bare_worktree" { + gitDir := t.TempDir() + runGit("init", "--bare", "--quiet", gitDir) + t.Setenv("GIT_DIR", gitDir) + t.Setenv("GIT_WORK_TREE", repo) + } else { + runGit("init", "--quiet") + } + hooksDir := filepath.Join(repo, ".githooks") + if err := os.Mkdir(hooksDir, 0755); err != nil { + t.Fatal(err) + } + hook := filepath.Join(hooksDir, "pre-commit") + const content = "#!/bin/sh\necho team hook\n" + if err := os.WriteFile(hook, []byte(content), 0755); err != nil { + t.Fatal(err) + } + runGit("config", "core.hooksPath", ".githooks") + runGit("add", "--force", "--", ".githooks/pre-commit") + if name == "global_safe_directory" { + // Reproduce a lower-priority ambient allowance even on an isolated host. + ambient := filepath.Join(home, ".config", "git") + if err := os.MkdirAll(ambient, 0755); err != nil { + t.Fatal(err) + } + runGit("config", "--file", filepath.Join(ambient, "config"), "safe.directory", "*") + // This default-global reset survives ScrubRouting removing GIT_CONFIG_*. + runGit("config", "--file", filepath.Join(home, ".gitconfig"), "safe.directory", "") + runGit("config", "--global", "--add", "safe.directory", filepath.ToSlash(repo)) + // Exercise Git's ownership-check control flow, not OS ownership/ACLs. + t.Setenv("GIT_TEST_ASSUME_DIFFERENT_OWNER", "1") + } + t.Chdir(repo) + git.ResetCaches() + t.Cleanup(git.ResetCaches) + resolved, err := git.GetGitHooksDir() + if err != nil { + t.Fatal(err) + } + gotInfo, gotErr := os.Stat(resolved) + wantInfo, wantErr := os.Stat(hooksDir) + if gotErr != nil || wantErr != nil || !os.SameFile(gotInfo, wantInfo) { + t.Fatalf("resolved hooks %q must identify %q: %v, %v", resolved, hooksDir, gotErr, wantErr) + } + inherited := os.Environ() + args := []string{"-C", hooksDir, "ls-files", "--error-unmatch", "--", "pre-commit"} + clean := exec.Command("git", args...) + clean.Env = gitenv.ScrubRouting(inherited) + out, cleanErr := clean.CombinedOutput() + if cleanErr == nil { + t.Fatalf("fixture must require inherited context, scrubbed probe succeeded: %s", out) + } + // The inherited fallback runs only when the scrubbed probe fails + // for a configuration reason. Exit 1 means "repository reached, + // path is not tracked" and is final, so a fixture that produced it + // would make the fallback unreachable and this test vacuous. + if exit, ok := cleanErr.(*exec.ExitError); ok && exit.ExitCode() == 1 { + t.Fatalf("fixture must fail the scrubbed probe for a configuration reason, got exit 1: %s", out) + } + fallback := exec.Command("git", args...) + fallback.Env = inherited + if out, err := fallback.CombinedOutput(); err != nil { + t.Fatalf("inherited tracking precondition: %v\n%s", err, out) + } + for _, check := range []struct { + name string + run func() error + }{ + {"guard", func() error { return guardHookWritePath(hook, false) }}, + {"install", func() error { return installHooksWithOptions(managedHookNames, false, false, false, false) }}, + {"migrate", func() error { + _, err := applyHookMigrationExecution(hookMigrationExecutionPlan{ + WriteOps: []hookMigrationWriteOp{{HookName: "pre-commit", HookPath: hook, SourceKind: hookMigrationWriteFromTemplate}}, + }) + return err + }}, + } { + if err := check.run(); err == nil || !strings.Contains(err.Error(), "tracked by git") { + t.Errorf("%s must refuse tracked foreign hook, got %v", check.name, err) + } + if got, err := os.ReadFile(hook); err != nil || string(got) != content { + t.Errorf("%s changed hook: %q, %v", check.name, got, err) + } + entries, err := os.ReadDir(hooksDir) + if err != nil || len(entries) != 1 || entries[0].Name() != "pre-commit" { + t.Errorf("%s created backup or other hook: %v, %v", check.name, entries, err) + } + } + }) + } +} + +func TestGuardHookWritePathAllowsFileWhenGitUnavailable(t *testing.T) { + path := filepath.Join(t.TempDir(), "pre-commit") + if err := os.WriteFile(path, []byte("foreign hook\n"), 0755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", "") + if _, err := exec.LookPath("git"); err == nil { + t.Fatal("fixture must make Git unavailable") + } + if err := guardHookWritePath(path, false); err != nil { + t.Fatalf("both tracking errors must retain the untracked policy: %v", err) + } +} diff --git a/cmd/bd/hooks_worktree_test.go b/cmd/bd/hooks_worktree_test.go index 435958afb..60f9b9477 100644 --- a/cmd/bd/hooks_worktree_test.go +++ b/cmd/bd/hooks_worktree_test.go @@ -205,6 +205,18 @@ func TestResetHooksPathIfBeadsManaged_Worktree(t *testing.T) { t.Fatalf("git config core.hooksPath failed: %v", err) } + run("config", "beads.role", "primary") + run("config", "extensions.worktreeConfig", "true") + cmd = exec.Command("git", "config", "--worktree", "beads.role", "worktree-only") + cmd.Dir = worktreeDir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("configure worktree role: %v\n%s", err, out) + } + cmd = exec.Command("git", "config", "--worktree", "core.hooksPath", ".beads/hooks") + cmd.Dir = worktreeDir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("configure worktree hooksPath: %v\n%s", err, out) + } t.Chdir(worktreeDir) git.ResetCaches() @@ -212,16 +224,62 @@ func TestResetHooksPathIfBeadsManaged_Worktree(t *testing.T) { t.Fatal("expected git.IsWorktree() to return true") } + git.ResetCaches() // Exercise the actual reset with a cold context. if err := resetHooksPathIfBeadsManaged(); err != nil { t.Fatalf("resetHooksPathIfBeadsManaged failed: %v", err) } - cmd = exec.Command("git", "config", "--get", "core.hooksPath") + cmd = exec.Command("git", "config", "--local", "--get", "core.hooksPath") cmd.Dir = mainRepoDir out, _ := cmd.Output() if strings.TrimSpace(string(out)) != "" { t.Errorf("core.hooksPath = %q after reset, want empty", strings.TrimSpace(string(out))) } + cmd = exec.Command("git", "config", "--local", "--get", "beads.role") + cmd.Dir = mainRepoDir + out, err = cmd.Output() + if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 { + t.Errorf("main role remains after reset: %q, %v", out, err) + } + cmd = exec.Command("git", "config", "--worktree", "--get", "beads.role") + cmd.Dir = worktreeDir + out, err = cmd.Output() + if err != nil || strings.TrimSpace(string(out)) != "worktree-only" { + t.Errorf("worktree-specific role changed: %q, %v", out, err) + } + cmd = exec.Command("git", "config", "--worktree", "--get", "core.hooksPath") + cmd.Dir = worktreeDir + out, err = cmd.Output() + if err != nil || strings.TrimSpace(string(out)) != ".beads/hooks" { + t.Errorf("worktree-specific hooksPath changed: %q, %v", out, err) + } + t.Run("preserve_worktree_role", func(t *testing.T) { + // Seed a new common role so this reset proves removal independently of the first call. + run("config", "--local", "beads.role", "primary") + privateDir, err := git.GetGitDir() + if err != nil { + t.Fatal(err) + } + privateConfig := filepath.Join(privateDir, "config.worktree") + before, err := os.ReadFile(privateConfig) + if err != nil { + t.Fatal(err) + } + git.ResetCaches() + t.Cleanup(git.ResetCaches) + if err := resetHooksPathIfBeadsManaged(); err != nil { + t.Fatalf("reset while preserving a worktree role failed: %v", err) + } + if after, err := os.ReadFile(privateConfig); err != nil || string(after) != string(before) { + t.Fatalf("private worktree config changed: %v", err) + } + get := exec.Command("git", "config", "--local", "--get", "beads.role") + get.Dir = mainRepoDir + out, err := get.Output() + if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 { + t.Errorf("common role after reset = %q, %v; want absent", out, err) + } + }) } func TestConfigureBeadsHooksPath_NormalRepoUnchanged(t *testing.T) { diff --git a/cmd/bd/main.go b/cmd/bd/main.go index 834cd0e7b..260a14774 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -1009,6 +1009,9 @@ var rootCmd = &cobra.Command{ _ = cmd.Help() // Help() always returns nil for cobra commands }, PersistentPreRunE: func(cmd *cobra.Command, args []string) (retErr error) { + if err := clearWorktreeGitRoutingEnv(cmd); err != nil { + return err + } applyNoColorFlag() // Initialize CommandContext to hold runtime state (replaces scattered globals) diff --git a/cmd/bd/uninstall_config_test.go b/cmd/bd/uninstall_config_test.go index 43fac9c12..cd500ae3c 100644 --- a/cmd/bd/uninstall_config_test.go +++ b/cmd/bd/uninstall_config_test.go @@ -4,8 +4,12 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" + + "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" ) // TestUninstallHooksUnsetsBeadsRole verifies AC2: bd hooks uninstall clears @@ -25,7 +29,7 @@ func TestUninstallHooksUnsetsBeadsRole(t *testing.T) { t.Fatalf("uninstallHooks() failed: %v", err) } - getCmd := exec.Command("git", "config", "--get", "beads.role") + getCmd := exec.Command("git", "config", "--local", "--get", "beads.role") getCmd.Dir = tmpDir out, err := getCmd.Output() if err == nil { @@ -70,7 +74,7 @@ func TestUninstallHooksReportsAmbiguousBeadsRole(t *testing.T) { } // And the key really is still set — the error was not spurious. - getCmd := exec.Command("git", "config", "--get-all", "beads.role") + getCmd := exec.Command("git", "config", "--local", "--get-all", "beads.role") getCmd.Dir = tmpDir out, getErr := getCmd.Output() if getErr != nil { @@ -125,3 +129,218 @@ func TestResetHooksPathIfBeadsManagedReportsFailureLoudly(t *testing.T) { } }) } + +func TestResetConfigReportsReadFailure(t *testing.T) { + repo := newGitRepo(t) + t.Chdir(repo) + git.ResetCaches() + t.Cleanup(git.ResetCaches) + common, err := git.GetGitCommonDir() + if err != nil { + t.Fatal(err) + } + // Corrupt the selected config after context capture so the reads, not discovery, fail. + path := filepath.Join(common, "config") + data := []byte("[invalid\n") + if err := os.WriteFile(path, data, 0600); err != nil { + t.Fatal(err) + } + err = resetHooksPathIfBeadsManaged() + for _, fragment := range []string{"read core.hooksPath", "read beads.role", "bad config"} { + if err == nil || !strings.Contains(err.Error(), fragment) { + t.Errorf("reset error = %v, want %q", err, fragment) + } + } + if after, err := os.ReadFile(path); err != nil || string(after) != string(data) { + t.Errorf("failed read changed config: %q (%v)", after, err) + } +} + +func TestResetRolePreservesSelectedGitContext(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 _, name := range []string{"ordinary", "selected_repository", "bare_external", "invalid", "inline_absent", "selected_config", "global_role", "config_lock", "global_only", "hooks_inline_only", "hooks_global_only", "hooks_foreign_absolute"} { + t.Run(name, func(t *testing.T) { + home := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + global := filepath.Join(home, ".gitconfig") + globalData := "[user]\n\tname = fixture global\n" + if name == "global_role" || name == "global_only" { + globalData += "[beads]\n\trole = global-default\n" + } + if name == "hooks_global_only" { + globalData += "[core]\n\thooksPath = .beads/hooks\n" + } + if err := os.WriteFile(global, []byte(globalData), 0o600); err != nil { + t.Fatal(err) + } + query := func(dir string, args ...string) ([]byte, error) { + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ()) + return cmd.CombinedOutput() + } + must := func(dir string, args ...string) string { + out, err := query(dir, args...) + if err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + return strings.TrimSpace(string(out)) + } + cwd, decoy := newGitRepo(t), newGitRepo(t) + selected := filepath.Join(cwd, ".git") + for _, repo := range []string{cwd, decoy} { + must(repo, "config", "beads.role", "primary") + must(repo, "read-tree", "--empty") + if err := os.WriteFile(filepath.Join(repo, ".git", "hooks", "pre-commit"), []byte("#!/bin/sh\necho foreign\n"), 0o600); err != nil { + t.Fatal(err) + } + } + must(decoy, "config", "beads.role", "decoy") + switch name { + case "selected_repository": + selected = filepath.Join(decoy, ".git") + t.Setenv("GIT_DIR", selected) + t.Setenv("GIT_WORK_TREE", decoy) + case "bare_external": + root := t.TempDir() + selected, cwd = filepath.Join(root, "selected bare.git"), filepath.Join(root, "external tree") + must(root, "init", "--bare", selected) + if err := os.Mkdir(cwd, 0o750); err != nil { + t.Fatal(err) + } + must(root, "--git-dir", selected, "config", "beads.role", "primary") + t.Setenv("GIT_DIR", filepath.Join("..", "selected bare.git")) + t.Setenv("GIT_WORK_TREE", cwd) + case "invalid": + t.Setenv("GIT_DIR", filepath.Join(t.TempDir(), "missing.git")) + case "inline_absent": + must(cwd, "config", "--unset", "beads.role") + t.Setenv("GIT_CONFIG_COUNT", "1") + t.Setenv("GIT_CONFIG_KEY_0", "beads.role") + t.Setenv("GIT_CONFIG_VALUE_0", "forged") + case "selected_config": + t.Setenv("GIT_CONFIG", filepath.Join(decoy, ".git", "config")) + probe := exec.Command("git", "--git-dir", selected, "config", "beads.routing-test", "selected-file") + probe.Dir = cwd // This fixture precondition deliberately inherits GIT_CONFIG. + if out, err := probe.CombinedOutput(); err != nil { + t.Fatalf("selected-file probe: %v\n%s", err, out) + } + if got := must(decoy, "config", "--get", "beads.routing-test"); got != "selected-file" { + t.Fatalf("GIT_CONFIG did not select decoy: %q", got) + } + must(decoy, "config", "--unset", "beads.routing-test") + case "global_only": + must(cwd, "config", "--local", "--unset", "beads.role") + if got := must(cwd, "config", "--get", "beads.role"); got != "global-default" { + t.Fatalf("global-only role precondition = %q", got) + } + case "config_lock": + if err := os.WriteFile(filepath.Join(selected, "config.lock"), []byte("owned lock"), 0o600); err != nil { + t.Fatal(err) + } + } + wantHooksPath, checkHooksPath := "", true + switch name { + case "ordinary", "selected_repository", "bare_external", "selected_config": + must(cwd, "--git-dir", selected, "config", "--local", "core.hooksPath", ".beads/hooks") + if name == "selected_config" { + must(decoy, "config", "--local", "core.hooksPath", ".beads/hooks") + } + case "hooks_inline_only", "hooks_global_only": + must(cwd, "config", "--local", "--unset", "core.hooksPath") + if name == "hooks_inline_only" { + t.Setenv("GIT_CONFIG_COUNT", "1") + t.Setenv("GIT_CONFIG_KEY_0", "core.hooksPath") + t.Setenv("GIT_CONFIG_VALUE_0", ".beads/hooks") + } + case "hooks_foreign_absolute": + wantHooksPath = filepath.Join(t.TempDir(), "foreign-hooks") + must(cwd, "config", "--local", "core.hooksPath", wantHooksPath) + default: + checkHooksPath = false + } + saved := map[string][]byte{global: []byte(globalData)} + if checkHooksPath { + for _, hooksDir := range []string{filepath.Join(cwd, ".beads", "hooks"), filepath.Join(decoy, ".beads", "hooks"), wantHooksPath} { + if hooksDir == "" { + continue + } + if err := os.MkdirAll(hooksDir, 0o750); err != nil { + t.Fatal(err) + } + path := filepath.Join(hooksDir, "pre-commit") + data := []byte("#!/bin/sh\necho foreign\n") + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatal(err) + } + saved[path] = data + } + } + for _, repo := range []string{cwd, decoy} { + for _, path := range []string{filepath.Join(repo, ".git", "config"), filepath.Join(repo, ".git", "index"), filepath.Join(repo, ".git", "hooks", "pre-commit")} { + if path == filepath.Join(selected, "config") && name != "invalid" && name != "config_lock" && name != "global_only" { + continue + } + if data, err := os.ReadFile(path); err == nil { + saved[path] = data + } else if !os.IsNotExist(err) { + t.Fatal(err) + } + } + } + t.Chdir(cwd) + before := strings.Join(os.Environ(), "\x00") + git.ResetCaches() // Poison is present before either actual entrypoint resolves its context. + t.Cleanup(git.ResetCaches) + var err error + if name == "invalid" || name == "inline_absent" { + err = resetHooksPathIfBeadsManaged() + } else { + err = uninstallHooks() + } + if name == "config_lock" { + if err == nil || !strings.Contains(err.Error(), "beads.role") { + t.Errorf("locked uninstall = %v, want beads.role failure", err) + } + } else if err != nil { + t.Errorf("reset/uninstall failed: %v", err) + } + out, readErr := query(cwd, "--git-dir", selected, "config", "--local", "--get", "beads.role") + if name == "invalid" || name == "config_lock" { + if readErr != nil || strings.TrimSpace(string(out)) != "primary" { + t.Errorf("retained selected role = %q, %v", out, readErr) + } + } else if exit, ok := readErr.(*exec.ExitError); !ok || exit.ExitCode() != 1 { + t.Errorf("selected local role remains: %q, %v", out, readErr) + } + if checkHooksPath { + out, readErr := query(cwd, "--git-dir", selected, "config", "--local", "--get", "core.hooksPath") + if wantHooksPath != "" { + if readErr != nil || strings.TrimSpace(string(out)) != wantHooksPath { + t.Errorf("foreign hooksPath changed: %q, %v", out, readErr) + } + } else if exit, ok := readErr.(*exec.ExitError); !ok || exit.ExitCode() != 1 { + t.Errorf("selected local hooksPath remains: %q, %v", out, readErr) + } + } + for path, before := range saved { + if after, err := os.ReadFile(path); err != nil || string(after) != string(before) { + t.Errorf("unrelated file changed: %s (%v)", path, err) + } + } + if strings.Join(os.Environ(), "\x00") != before { + t.Error("reset changed inherited environment") + } + }) + } +} diff --git a/cmd/bd/worktree_cmd.go b/cmd/bd/worktree_cmd.go index 171b08523..ed29649af 100644 --- a/cmd/bd/worktree_cmd.go +++ b/cmd/bd/worktree_cmd.go @@ -11,6 +11,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "sort" "strconv" "strings" @@ -19,7 +20,9 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/execenv" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/worktreeremove" @@ -469,7 +472,7 @@ func gitCmdInDir(ctx context.Context, dir string, args ...string) *exec.Cmd { cmd := exec.CommandContext(ctx, "git", gitArgs...) cmd.Dir = dir // Security: Disable git hooks and templates (SEC-001, SEC-002) - cmd.Env = append(os.Environ(), + cmd.Env = append(scrubWorktreeGitRoutingEnv(os.Environ()), "GIT_TEMPLATE_DIR=", ) return cmd @@ -664,47 +667,67 @@ func newWorktreeRemovalGit() (*worktreeRemovalGit, error) { }, nil } -func scrubWorktreeRemovalGitEnv(env []string) []string { - exactKeys := map[string]struct{}{ - "GIT_ALTERNATE_OBJECT_DIRECTORIES": {}, - "GIT_CEILING_DIRECTORIES": {}, - "GIT_COMMON_DIR": {}, - "GIT_DIR": {}, - "GIT_DISCOVERY_ACROSS_FILESYSTEM": {}, - "GIT_EXEC_PATH": {}, - "GIT_GRAFT_FILE": {}, - "GIT_IMPLICIT_WORK_TREE": {}, - "GIT_INDEX_FILE": {}, - "GIT_INTERNAL_SUPER_PREFIX": {}, - "GIT_NAMESPACE": {}, - "GIT_NO_REPLACE_OBJECTS": {}, - "GIT_OBJECT_DIRECTORY": {}, - "GIT_OPTIONAL_LOCKS": {}, - "GIT_PREFIX": {}, - "GIT_QUARANTINE_PATH": {}, - "GIT_REPLACE_REF_BASE": {}, - "GIT_SHALLOW_FILE": {}, - "GIT_SUPER_PREFIX": {}, - "GIT_TEMPLATE_DIR": {}, - "GIT_WORK_TREE": {}, - } +func scrubWorktreeGitRoutingEnv(env []string) []string { + return scrubWorktreeGitRoutingEnvForOS(env, runtime.GOOS) +} - cleaned := make([]string, 0, len(env)) - for _, entry := range env { - key := entry - if separator := strings.IndexByte(entry, '='); separator >= 0 { - key = entry[:separator] - } - upperKey := strings.ToUpper(key) - if strings.HasPrefix(upperKey, "GIT_CONFIG") { +// 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. +func scrubWorktreeGitRoutingEnvForOS(env []string, goos string) []string { + return gitenv.ScrubRoutingForOS(env, goos) +} + +func scrubWorktreeRemovalGitEnv(env []string) []string { + return scrubWorktreeRemovalGitEnvForOS(env, runtime.GOOS) +} + +func scrubWorktreeRemovalGitEnvForOS(env []string, goos string) []string { + cleaned := scrubWorktreeGitRoutingEnvForOS(env, goos) + // ScrubRoutingForOS returns a fresh slice, so filtering it in place is safe. + result := cleaned[:0] + for _, entry := range cleaned { + key := worktreeGitEnvKey(entry) + // Key identity is the subprocess lookup rule (execenv), not ToUpper. + // The two disagree in both directions for non-ASCII keys on Windows: + // ToUpper leaves GİT_OPTIONAL_LOCKS unmatched although Git honors it, + // and folds GIT_OPTIONAL_LOCKſ onto the literal although os/exec keeps + // it distinct. + if execenv.KeyEqualForOS(key, "GIT_NO_REPLACE_OBJECTS", goos) || + execenv.KeyEqualForOS(key, "GIT_OPTIONAL_LOCKS", goos) { continue } - if _, blocked := exactKeys[upperKey]; blocked { - continue - } - cleaned = append(cleaned, entry) + result = append(result, entry) } - return cleaned + return result +} + +func worktreeGitEnvKey(entry string) string { + return gitenv.EntryKey(entry) +} + +// clearWorktreeGitRoutingEnv establishes the command working directory as the +// repository-selection boundary without changing process identity or signal +// semantics. Startup config discovery applies the same boundary to its one +// pre-hook Git probe. +func clearWorktreeGitRoutingEnv(cmd *cobra.Command) error { + if !hasWorktreeCommandAncestor(cmd) { + return nil + } + if _, err := gitenv.ClearRouting(); err != nil { + return fmt.Errorf("clear inherited Git routing for worktree command: %w", err) + } + return nil +} + +func hasWorktreeCommandAncestor(cmd *cobra.Command) bool { + for current := cmd; current != nil; current = current.Parent() { + if current == worktreeCmd { + return true + } + } + return false } func (git *worktreeRemovalGit) command(ctx context.Context, dir string, args ...string) *exec.Cmd { diff --git a/cmd/bd/worktree_remove_test.go b/cmd/bd/worktree_remove_test.go index 4a7f3a323..8a3b90dcc 100644 --- a/cmd/bd/worktree_remove_test.go +++ b/cmd/bd/worktree_remove_test.go @@ -85,7 +85,7 @@ func TestWorktreeRemoveProcessHelper(t *testing.T) { func runWorktreeRemoveHookGit(dir string, args ...string) error { command := exec.Command("git", args...) command.Dir = dir - command.Env = append(scrubWorktreeRemovalGitEnv(os.Environ()), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_SYSTEM="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1", "GIT_NO_REPLACE_OBJECTS=1") + command.Env = append(scrubWorktreeGitRoutingEnv(os.Environ()), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_SYSTEM="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1", "GIT_NO_REPLACE_OBJECTS=1") output, err := command.CombinedOutput() if err != nil { return fmt.Errorf("git %s failed: %w\n%s", strings.Join(args, " "), err, output) @@ -157,12 +157,84 @@ func TestWorktreeRemoveE2EReportsRemovalSuccessCleanupFailure(t *testing.T) { fixture.git(t, fixture.repo, "rev-parse", "--verify", "refs/heads/lane") } -func TestScrubWorktreeRemovalGitEnv(t *testing.T) { - input := []string{"PATH=/trusted/bin", "HOME=/home/test", "GIT_DIR=/wrong", "git_work_tree=/wrong-case", "GIT_CONFIG_COUNT=1", "GIT_CONFIG_KEY_0=core.worktree", "GIT_OBJECT_DIRECTORY=/wrong-objects", "GIT_EXEC_PATH=/wrong-exec"} - want := []string{"PATH=/trusted/bin", "HOME=/home/test"} - if got := scrubWorktreeRemovalGitEnv(input); !reflect.DeepEqual(got, want) { - t.Fatalf("scrubWorktreeRemovalGitEnv() = %#v, want %#v", got, want) +func TestScrubWorktreeGitEnvUsesHostKeySemantics(t *testing.T) { + input := []string{ + "PATH=/trusted/bin", + "HOME=/home/test", + "GIT_AUTHOR_NAME=Test User", + "GIT_DIR=/wrong", + "git_work_tree=/wrong-case", + "GIT_CONFIG_COUNT=1", + "GIT_CONFIG_KEY_0=core.worktree", + "git_config_value_0=/wrong-case", + "GIT_OBJECT_DIRECTORY=/wrong-objects", + "GIT_EXEC_PATH=/wrong-exec", + "GIT_NO_REPLACE_OBJECTS=1", + "GIT_OPTIONAL_LOCKS=1", } + for _, test := range []struct { + name, goos string + want []string + }{ + { + name: "POSIX names are case-sensitive", + goos: "linux", + want: []string{"PATH=/trusted/bin", "HOME=/home/test", "GIT_AUTHOR_NAME=Test User", "git_work_tree=/wrong-case", "git_config_value_0=/wrong-case", "GIT_NO_REPLACE_OBJECTS=1", "GIT_OPTIONAL_LOCKS=1"}, + }, + { + name: "Windows names are case-insensitive", + goos: "windows", + want: []string{"PATH=/trusted/bin", "HOME=/home/test", "GIT_AUTHOR_NAME=Test User", "GIT_NO_REPLACE_OBJECTS=1", "GIT_OPTIONAL_LOCKS=1"}, + }, + } { + t.Run(test.name, func(t *testing.T) { + if got := scrubWorktreeGitRoutingEnvForOS(input, test.goos); !reflect.DeepEqual(got, test.want) { + t.Fatalf("scrubWorktreeGitRoutingEnvForOS() = %#v, want %#v", got, test.want) + } + }) + } +} + +// The removal scrub's stricter no-optional-locks policy must key off the same +// identity rule the subprocess uses (execenv), not strings.ToUpper: on Windows +// the two disagree in both directions for non-ASCII keys, so ToUpper both lets +// a honored key survive and drops one os/exec keeps distinct. +func TestScrubWorktreeRemovalGitEnvUsesSubprocessKeyIdentity(t *testing.T) { + input := []string{ + "PATH=/trusted/bin", + "GIT_NO_REPLACE_OBJECTS=1", + "GIT_OPTIONAL_LOCKS=1", + // U+0130: ToUpper leaves it unmatched, Win32 folds it to git_optional_locks. + "GİT_OPTIONAL_LOCKS=1", + // U+017F: ToUpper folds it onto the literal, Win32 keeps it distinct. + "GIT_OPTIONAL_LOCKſ=1", + } + for _, test := range []struct { + name, goos string + want []string + }{ + { + name: "POSIX keys are byte-exact", + goos: "linux", + want: []string{"PATH=/trusted/bin", "GİT_OPTIONAL_LOCKS=1", "GIT_OPTIONAL_LOCKſ=1"}, + }, + { + name: "Windows keys follow subprocess identity", + goos: "windows", + want: []string{"PATH=/trusted/bin", "GIT_OPTIONAL_LOCKſ=1"}, + }, + } { + t.Run(test.name, func(t *testing.T) { + if got := scrubWorktreeRemovalGitEnvForOS(input, test.goos); !reflect.DeepEqual(got, test.want) { + t.Fatalf("scrubWorktreeRemovalGitEnvForOS() = %#v, want %#v", got, test.want) + } + }) + } +} + +func TestNewWorktreeRemovalGitPinsExecutable(t *testing.T) { + t.Setenv("GIT_NO_REPLACE_OBJECTS", "0") + t.Setenv("GIT_OPTIONAL_LOCKS", "1") runner, err := newWorktreeRemovalGit() if err != nil { t.Fatal(err) @@ -170,6 +242,23 @@ func TestScrubWorktreeRemovalGitEnv(t *testing.T) { if !filepath.IsAbs(runner.executable) { t.Fatalf("git executable is not absolute: %q", runner.executable) } + for key, want := range map[string]string{ + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_OPTIONAL_LOCKS": "0", + } { + matches := 0 + for _, entry := range runner.env { + if strings.HasPrefix(entry, key+"=") { + matches++ + if entry != key+"="+want { + t.Fatalf("%s = %q, want %q", key, entry, key+"="+want) + } + } + } + if matches != 1 { + t.Fatalf("%s occurs %d times in removal environment, want once", key, matches) + } + } } type worktreeRemoveProcessResult struct { @@ -181,7 +270,7 @@ func (result worktreeRemoveProcessResult) combined() string { return result.stdo func (result worktreeRemoveProcessResult) requireSuccess(t *testing.T) { t.Helper() if result.exitCode != 0 { - t.Fatalf("worktree remove failed with exit code %d\nstdout:\n%s\nstderr:\n%s", result.exitCode, result.stdout, result.stderr) + t.Fatalf("worktree command failed with exit code %d\nstdout:\n%s\nstderr:\n%s", result.exitCode, result.stdout, result.stderr) } } func (result worktreeRemoveProcessResult) requireFailure(t *testing.T, substring string) { @@ -355,7 +444,7 @@ func (fixture *worktreeRemovalFixture) git(t *testing.T, directory string, args t.Helper() command := exec.Command("git", args...) command.Dir = directory - command.Env = append(scrubWorktreeRemovalGitEnv(os.Environ()), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_SYSTEM="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1", "GIT_NO_REPLACE_OBJECTS=1") + command.Env = append(scrubWorktreeGitRoutingEnv(os.Environ()), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_SYSTEM="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1", "GIT_NO_REPLACE_OBJECTS=1") output, err := command.CombinedOutput() if err != nil { t.Fatalf("git %s failed: %v\n%s", strings.Join(args, " "), err, output) diff --git a/cmd/bd/worktree_test.go b/cmd/bd/worktree_test.go index 8c7b01f8b..c24c01ed4 100644 --- a/cmd/bd/worktree_test.go +++ b/cmd/bd/worktree_test.go @@ -1,11 +1,18 @@ package main import ( + "bytes" "context" + "encoding/json" + "errors" "os" "os/exec" "path/filepath" + "runtime" + "strings" "testing" + + "github.com/steveyegge/beads/internal/gitenv" ) func TestTruncateForBox(t *testing.T) { @@ -69,6 +76,8 @@ func TestGitRevParse(t *testing.T) { } func TestGitCmdInDirSuppressesHooksViaGitConfig(t *testing.T) { + t.Setenv("GIT_DIR", "/wrong") + t.Setenv("GIT_OPTIONAL_LOCKS", "1") cmd := gitCmdInDir(t.Context(), "/tmp/example", "status", "--porcelain") if cmd.Dir != "/tmp/example" { t.Fatalf("cmd.Dir = %q, want /tmp/example", cmd.Dir) @@ -82,15 +91,312 @@ func TestGitCmdInDirSuppressesHooksViaGitConfig(t *testing.T) { t.Fatalf("cmd.Args[%d] = %q, want %q; full args: %#v", i+1, got, want, cmd.Args) } } + hasTemplateSuppression := false + hasOptionalLocks := false for _, env := range cmd.Env { if env == "GIT_HOOKS_PATH=" { t.Fatal("cmd.Env contains dead GIT_HOOKS_PATH hook suppression") } if env == "GIT_TEMPLATE_DIR=" { - return + hasTemplateSuppression = true + } + if env == "GIT_OPTIONAL_LOCKS=1" { + hasOptionalLocks = true + } + if gitenv.IsRoutingKeyForOS(worktreeGitEnvKey(env), runtime.GOOS) && env != "GIT_TEMPLATE_DIR=" { + t.Fatalf("cmd.Env retains Git routing state: %q", env) } } - t.Fatal("cmd.Env missing GIT_TEMPLATE_DIR suppression") + if !hasTemplateSuppression { + t.Fatal("cmd.Env missing GIT_TEMPLATE_DIR suppression") + } + if !hasOptionalLocks { + t.Fatal("cmd.Env did not preserve GIT_OPTIONAL_LOCKS") + } +} + +func TestClearWorktreeGitRoutingEnvPreservesNonRoutingVariables(t *testing.T) { + // ClearRouting is deliberately process-lifetime state for the real CLI. + // Register restorations for every routing key inherited by the test process + // before exercising that boundary in-process. + for _, entry := range os.Environ() { + key := worktreeGitEnvKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, os.Getenv(key)) + } + } + t.Setenv("GIT_DIR", "/wrong") + t.Setenv("GIT_CONFIG_COUNT", "1") + t.Setenv("GIT_OPTIONAL_LOCKS", "1") + t.Setenv("GIT_NO_REPLACE_OBJECTS", "1") + t.Setenv("BD_WORKTREE_ENV_SENTINEL", "keep") + + if err := clearWorktreeGitRoutingEnv(worktreeListCmd); err != nil { + t.Fatalf("clearWorktreeGitRoutingEnv() error = %v", err) + } + for _, key := range []string{"GIT_DIR", "GIT_CONFIG_COUNT"} { + if value, ok := os.LookupEnv(key); ok { + t.Fatalf("%s remains set to %q", key, value) + } + } + for key, want := range map[string]string{ + "GIT_OPTIONAL_LOCKS": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "BD_WORKTREE_ENV_SENTINEL": "keep", + } { + if got := os.Getenv(key); got != want { + t.Fatalf("%s = %q, want %q", key, got, want) + } + } +} + +func TestWorktreeCommandsIgnoreInheritedGitRoutingState(t *testing.T) { + bdBinary := buildBDForInitTests(t) + + decoyRepo := newGitRepo(t) + commitTestFile(t, decoyRepo, "README.md", "decoy\n", "decoy commit") + decoyBeadsDir := filepath.Join(decoyRepo, ".beads") + writeTestConfigYAML(t, decoyBeadsDir, "issue-prefix: decoy\n") + if err := os.WriteFile( + filepath.Join(decoyBeadsDir, ".env"), + []byte("BEADS_DIR="+filepath.ToSlash(decoyBeadsDir)+"\n"), + 0o600, + ); err != nil { + t.Fatalf("write decoy selector environment: %v", err) + } + // An unsanitized post-create status check would see this file and reject an + // otherwise clean target worktree. + if err := os.WriteFile(filepath.Join(decoyRepo, "decoy-dirty.txt"), []byte("dirty\n"), 0600); err != nil { + t.Fatal(err) + } + + poisonConfig := filepath.Join(t.TempDir(), "poison.gitconfig") + if err := os.WriteFile(poisonConfig, []byte("[core]\n\tworktree = "+filepath.ToSlash(decoyRepo)+"\n"), 0600); err != nil { + t.Fatal(err) + } + poisonEnv := []string{ + "GIT_DIR=" + filepath.Join(decoyRepo, ".git"), + "GIT_WORK_TREE=" + decoyRepo, + "GIT_COMMON_DIR=" + filepath.Join(decoyRepo, ".git"), + "GIT_INDEX_FILE=" + filepath.Join(decoyRepo, ".git", "index"), + "GIT_OBJECT_DIRECTORY=" + filepath.Join(decoyRepo, ".git", "objects"), + "GIT_ALTERNATE_OBJECT_DIRECTORIES=" + filepath.Join(decoyRepo, ".git", "objects"), + "GIT_EXEC_PATH=" + filepath.Join(decoyRepo, "missing-git-exec"), + "GIT_NAMESPACE=poison", + "GIT_CONFIG_GLOBAL=" + poisonConfig, + "GIT_CONFIG_SYSTEM=" + poisonConfig, + "GIT_CONFIG_NOSYSTEM=0", + "GIT_CONFIG_COUNT=1", + "GIT_CONFIG_KEY_0=core.worktree", + "GIT_CONFIG_VALUE_0=" + decoyRepo, + "GIT_OPTIONAL_LOCKS=1", + "BEADS_DIR=", + "BEADS_DB=", + "BD_DB=", + } + + t.Run("create list and remove stay in the target repository", func(t *testing.T) { + targetRepo := newGitRepo(t) + commitTestFile(t, targetRepo, "README.md", "target\n", "target commit") + writeTestConfigYAML(t, filepath.Join(targetRepo, ".beads"), "issue-prefix: target\n") + decoyRegistryBefore := gitWorktreeRegistry(t, decoyRepo) + + create := runWorktreeCommandProcess(t, bdBinary, targetRepo, "create", poisonEnv, "lane") + create.requireSuccess(t) + var created struct { + Path string `json:"path"` + Branch string `json:"branch"` + } + decodeWorktreeCommandJSON(t, create.stdout, &created) + lane := filepath.Join(targetRepo, "lane") + if !sameWorktreePath(created.Path, lane) || created.Branch != "lane" { + t.Fatalf("create result = %#v, want target lane %q", created, lane) + } + assertGitWorktreePaths(t, targetRepo, targetRepo, lane) + if got := gitWorktreeRegistry(t, decoyRepo); got != decoyRegistryBefore { + t.Fatalf("create mutated decoy worktree registry:\n--- before ---\n%s\n--- after ---\n%s", decoyRegistryBefore, got) + } + + list := runWorktreeCommandProcess(t, bdBinary, targetRepo, "list", poisonEnv) + list.requireSuccess(t) + var listed []WorktreeInfo + decodeWorktreeCommandJSON(t, list.stdout, &listed) + if len(listed) != 2 || + !sameWorktreePath(listed[0].Path, targetRepo) || listed[0].BeadsState != "shared" || + !sameWorktreePath(listed[1].Path, lane) || listed[1].BeadsState != "none" { + t.Fatalf("list resolved outside target repository or beads state: %#v", listed) + } + + info := runWorktreeCommandProcess(t, bdBinary, lane, "info", poisonEnv) + info.requireSuccess(t) + var details struct { + IsWorktree bool `json:"is_worktree"` + Path string `json:"path"` + MainRepo string `json:"main_repo"` + Branch string `json:"branch"` + BeadsRedirected bool `json:"beads_redirected"` + } + decodeWorktreeCommandJSON(t, info.stdout, &details) + if !details.IsWorktree || + !sameWorktreePath(details.Path, lane) || + !sameWorktreePath(details.MainRepo, targetRepo) || + details.Branch != "lane" || + details.BeadsRedirected { + t.Fatalf("info resolved outside the target worktree: %#v", details) + } + + remove := runWorktreeCommandProcess(t, bdBinary, targetRepo, "remove", poisonEnv, lane, "--force") + remove.requireSuccess(t) + if _, err := os.Stat(lane); !os.IsNotExist(err) { + t.Fatalf("remove left target worktree behind: %v", err) + } + assertGitWorktreePaths(t, targetRepo, targetRepo) + if _, err := os.Stat(filepath.Join(decoyRepo, "decoy-dirty.txt")); err != nil { + t.Fatalf("remove mutated decoy repository: %v", err) + } + }) + + t.Run("create refuses a target without a beads workspace", func(t *testing.T) { + targetRepo := newGitRepo(t) + commitTestFile(t, targetRepo, "README.md", "target without beads\n", "target commit") + lane := filepath.Join(targetRepo, "lane") + registryBefore := gitWorktreeRegistry(t, targetRepo) + + create := runWorktreeCommandProcess(t, bdBinary, targetRepo, "create", poisonEnv, "lane") + if create.exitCode == 0 { + t.Fatalf("create accepted the decoy beads workspace\nstdout:\n%s\nstderr:\n%s", create.stdout, create.stderr) + } + if _, err := os.Stat(lane); !os.IsNotExist(err) { + t.Fatalf("refused create mutated target path: %v", err) + } + if got := gitWorktreeRegistry(t, targetRepo); got != registryBefore { + t.Fatalf("refused create mutated target worktree registry:\n--- before ---\n%s\n--- after ---\n%s", registryBefore, got) + } + if _, err := os.Stat(filepath.Join(targetRepo, ".gitignore")); !os.IsNotExist(err) { + t.Fatalf("refused create mutated target gitignore: %v", err) + } + }) + + t.Run("startup ignores malformed config selected by linked-worktree routing", func(t *testing.T) { + targetRepo := newGitRepo(t) + commitTestFile(t, targetRepo, "README.md", "target\n", "target commit") + + decoyMain := newGitRepo(t) + commitTestFile(t, decoyMain, "README.md", "linked decoy\n", "decoy commit") + writeTestConfigYAML(t, filepath.Join(decoyMain, ".beads"), "json: [\n") + decoyLane := filepath.Join(t.TempDir(), "linked-decoy") + command := exec.Command("git", "worktree", "add", "-b", "linked-decoy", decoyLane) + command.Dir = decoyMain + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("create decoy linked worktree: %v\n%s", err, output) + } + decoyAdminDir := gitRevParsePath(t, decoyLane, "--absolute-git-dir") + decoyCommonDir := gitRevParsePath(t, decoyLane, "--git-common-dir") + + linkedPoisonEnv := append(append([]string(nil), poisonEnv...), + "GIT_DIR="+decoyAdminDir, + "GIT_WORK_TREE="+decoyLane, + "GIT_COMMON_DIR="+decoyCommonDir, + "GIT_INDEX_FILE="+filepath.Join(decoyAdminDir, "index"), + "GIT_OBJECT_DIRECTORY="+filepath.Join(decoyCommonDir, "objects"), + "GIT_ALTERNATE_OBJECT_DIRECTORIES="+filepath.Join(decoyCommonDir, "objects"), + "BEADS_TEST_IGNORE_REPO_CONFIG=", + ) + list := runWorktreeCommandProcess(t, bdBinary, targetRepo, "list", linkedPoisonEnv) + list.requireSuccess(t) + if strings.Contains(strings.ToLower(list.stderr), "failed to initialize config") { + t.Fatalf("malformed decoy config reached startup initialization:\n%s", list.stderr) + } + var listed []WorktreeInfo + decodeWorktreeCommandJSON(t, list.stdout, &listed) + if len(listed) != 1 || !sameWorktreePath(listed[0].Path, targetRepo) { + t.Fatalf("list resolved outside target repository: %#v", listed) + } + }) +} + +func runWorktreeCommandProcess(t *testing.T, bdBinary, dir, action string, extraEnv []string, args ...string) worktreeRemoveProcessResult { + t.Helper() + commandArgs := append([]string{"--json", "worktree", action}, args...) + command := exec.Command(bdBinary, commandArgs...) + command.Dir = dir + command.Env = overrideWorktreeRemoveEnv(os.Environ(), append([]string{ + "BD_DISABLE_METRICS=1", + "BD_DISABLE_EVENT_FLUSH=1", + "BEADS_TEST_MODE=1", + }, extraEnv...)) + var stdout, stderr bytes.Buffer + command.Stdout, command.Stderr = &stdout, &stderr + err := command.Run() + exitCode := 0 + if err != nil { + var exitError *exec.ExitError + if !errors.As(err, &exitError) { + t.Fatalf("launch worktree command helper: %v", err) + } + exitCode = exitError.ExitCode() + } + return worktreeRemoveProcessResult{stdout: stdout.String(), stderr: stderr.String(), exitCode: exitCode} +} + +func decodeWorktreeCommandJSON(t *testing.T, output string, target any) { + t.Helper() + if err := json.NewDecoder(strings.NewReader(output)).Decode(target); err != nil { + t.Fatalf("decode helper JSON: %v\noutput:\n%s", err, output) + } +} + +func gitWorktreeRegistry(t *testing.T, repoDir string) string { + t.Helper() + command := exec.Command("git", "worktree", "list", "--porcelain") + command.Dir = repoDir + output, err := command.CombinedOutput() + if err != nil { + t.Fatalf("list Git worktree registry for %q: %v\n%s", repoDir, err, output) + } + return strings.TrimSpace(string(output)) +} + +func assertGitWorktreePaths(t *testing.T, repoDir string, want ...string) { + t.Helper() + var got []string + for _, line := range strings.Split(gitWorktreeRegistry(t, repoDir), "\n") { + if path, ok := strings.CutPrefix(strings.TrimSpace(line), "worktree "); ok { + got = append(got, filepath.FromSlash(path)) + } + } + if len(got) != len(want) { + t.Fatalf("Git worktree paths = %#v, want %#v", got, want) + } + matched := make([]bool, len(got)) + for _, wantPath := range want { + found := false + for index, gotPath := range got { + if !matched[index] && sameWorktreePath(gotPath, wantPath) { + matched[index] = true + found = true + break + } + } + if !found { + t.Fatalf("Git worktree paths = %#v, missing %q", got, wantPath) + } + } +} + +func gitRevParsePath(t *testing.T, repoDir, selector string) string { + t.Helper() + command := exec.Command("git", "rev-parse", selector) + command.Dir = repoDir + output, err := command.CombinedOutput() + if err != nil { + t.Fatalf("git rev-parse %s in %q: %v\n%s", selector, repoDir, err, output) + } + path := filepath.FromSlash(strings.TrimSpace(string(output))) + if !filepath.IsAbs(path) { + path = filepath.Join(repoDir, path) + } + return filepath.Clean(path) } // TestResolveWorktreePathByName verifies that resolveWorktreePath can find diff --git a/docs/reference/worktrees.md b/docs/reference/worktrees.md index 6fd87b340..d0ef49f71 100644 --- a/docs/reference/worktrees.md +++ b/docs/reference/worktrees.md @@ -12,6 +12,11 @@ separate from Git branch commits. All worktrees in the same repository use the same beads workspace unless you override discovery with `BEADS_DIR`. +Startup Git discovery probes for every `bd` command scrub inherited Git routing +variables such as `GIT_DIR` and `GIT_WORK_TREE` from their subprocess environment. +Clearing those variables from the `bd` process environment applies only to +`bd worktree` commands. + ``` project/ ├── .git/ # Shared Git directory diff --git a/internal/config/config.go b/internal/config/config.go index ae48de830..5d37cbd51 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/viper" "github.com/steveyegge/beads/internal/debug" + "github.com/steveyegge/beads/internal/gitenv" "gopkg.in/yaml.v3" ) @@ -417,6 +418,10 @@ func worktreeFallbackConfigPath(repoPath string) string { func gitDirsForRepo(repoPath string) (gitDir, commonDir string, ok bool) { cmd := exec.Command("git", "-C", repoPath, "rev-parse", "--git-dir", "--git-common-dir") + // repoPath is the authority for this probe. Inherited Git routing such as + // GIT_DIR overrides -C and can make startup read another repository's + // shared-worktree config before command dispatch has begun. + cmd.Env = gitenv.ScrubRouting(os.Environ()) output, err := cmd.Output() if err != nil { return "", "", false @@ -1010,7 +1015,9 @@ func ResolveExternalProjectPath(projectName string) string { // 3. git config user.name // 4. hostname // -// This is used as the sender field in bd mail commands. +// 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. func GetIdentity(flagValue string) string { // 1. Command-line flag takes precedence if flagValue != "" { @@ -1024,6 +1031,7 @@ func GetIdentity(flagValue string) string { // 3. git config user.name cmd := exec.Command("git", "config", "user.name") + cmd.Env = gitenv.ScrubRouting(os.Environ()) if output, err := cmd.Output(); err == nil { if gitUser := strings.TrimSpace(string(output)); gitUser != "" { return gitUser diff --git a/internal/config/git_routing_test.go b/internal/config/git_routing_test.go new file mode 100644 index 000000000..e39722d37 --- /dev/null +++ b/internal/config/git_routing_test.go @@ -0,0 +1,189 @@ +package config + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/gitenv" +) + +func TestGetIdentityIgnoresInheritedGitRouting(t *testing.T) { + ResetForTesting() + t.Cleanup(ResetForTesting) + t.Setenv("BEADS_IDENTITY", "") + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", home) + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[user]\n\tname = home-user\n"), 0o600); err != nil { + t.Fatal(err) + } + target, decoy := t.TempDir(), t.TempDir() + for _, repo := range []string{target, decoy} { + runConfigProbeGit(t, repo, "init", "--quiet") + } + runConfigProbeGit(t, target, "config", "--local", "user.name", "target-user") + runConfigProbeGit(t, decoy, "config", "--local", "user.name", "decoy-user") + t.Chdir(target) + if err := Initialize(); err != nil { + t.Fatal(err) + } + Set("identity", "") + poisonConfig := filepath.Join(t.TempDir(), "poison.gitconfig") + if err := os.WriteFile(poisonConfig, []byte("[user]\n\tname = injected-user\n"), 0o600); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + env map[string]string + clearLocal bool + want string + }{ + {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"}, + } { + t.Run(tc.name, func(t *testing.T) { + if tc.clearLocal { + runConfigProbeGit(t, target, "config", "--local", "--unset", "user.name") + } + for key, value := range tc.env { + t.Setenv(key, value) + } + if got := GetIdentity(""); got != tc.want { + t.Errorf("GetIdentity() = %q, want %q from the intended config", got, tc.want) + } + Set("identity", "configured-user") + t.Cleanup(func() { Set("identity", "") }) + if got := GetIdentity("flag-user"); got != "flag-user" { + t.Errorf("flag identity = %q", got) + } + if got := GetIdentity(""); got != "configured-user" { + t.Errorf("configured identity = %q", got) + } + }) + } + t.Run("missing Git retains hostname fallback", func(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + want, err := os.Hostname() + if err != nil || want == "" { + t.Fatalf("hostname fixture: %q, %v", want, err) + } + if got := GetIdentity(""); got != want { + t.Errorf("hostname identity = %q, want %q", got, want) + } + }) +} + +func TestSecretGitTrackingIgnoresInheritedGitRouting(t *testing.T) { + target, decoy := t.TempDir(), t.TempDir() + for _, repo := range []string{target, decoy} { + runConfigProbeGit(t, repo, "init", "--quiet") + } + tracked := filepath.Join(target, "config.yaml") + untracked := filepath.Join(target, "untracked.yaml") + for _, path := range []string{tracked, untracked} { + if err := os.WriteFile(path, []byte("json: false\n"), 0o600); err != nil { + t.Fatal(err) + } + } + runConfigProbeGit(t, target, "add", "--", tracked) + for _, tc := range []struct { + name string + env map[string]string + }{ + {name: "repository", env: map[string]string{"GIT_DIR": filepath.Join(decoy, ".git")}}, + {name: "index", env: map[string]string{"GIT_INDEX_FILE": filepath.Join(decoy, "missing-index")}}, + {name: "config", env: map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.worktree", "GIT_CONFIG_VALUE_0": decoy}}, + } { + t.Run(tc.name, func(t *testing.T) { + for key, value := range tc.env { + t.Setenv(key, value) + } + if !isGitTracked(tracked) { + t.Error("routing hid the tracked file in the intended repository") + } + if isGitTracked(untracked) { + t.Error("untracked file reported as tracked") + } + if err := checkSecretGitTracked(tracked, "linear.api_key"); err == nil || !strings.Contains(err.Error(), "refusing to write secret key") { + t.Errorf("tracked secret refusal = %v", err) + } + if err := checkSecretGitTracked(untracked, "linear.api_key"); err != nil { + t.Errorf("untracked secret refused: %v", err) + } + if err := checkSecretGitTracked(tracked, "no-db"); err != nil { + t.Errorf("non-secret key refused: %v", err) + } + }) + } +} + +// A bare repository whose work tree is named only by GIT_DIR/GIT_WORK_TREE is +// invisible to the scrubbed probe — it is reachable through the inherited +// routing alone. The secret guard must still refuse a write into the tracked +// config.yaml there, which is the refusal upstream-base performed before the +// probe began scrubbing routing. +func TestSecretGitTrackingHonorsInheritedBareWorkTree(t *testing.T) { + gitDir, workTree := t.TempDir(), t.TempDir() + runConfigProbeGit(t, workTree, "init", "--bare", "--quiet", gitDir) + tracked := filepath.Join(workTree, "config.yaml") + untracked := filepath.Join(workTree, "untracked.yaml") + for _, path := range []string{tracked, untracked} { + if err := os.WriteFile(path, []byte("json: false\n"), 0o600); err != nil { + t.Fatal(err) + } + } + runConfigProbeGit(t, workTree, "--git-dir", gitDir, "--work-tree", workTree, "add", "--", tracked) + t.Setenv("GIT_DIR", gitDir) + t.Setenv("GIT_WORK_TREE", workTree) + + // Fixture guard: the tracked file must be reachable only through the + // inherited routing, and the scrubbed probe must fail for a configuration + // reason (no reachable repository) rather than "path is not tracked" + // (exit 1), which is final and would leave the fallback unreachable. + probe := func(env []string) error { + cmd := exec.Command("git", "ls-files", "--error-unmatch", tracked) + cmd.Dir = workTree + cmd.Env = env + return cmd.Run() + } + inherited := os.Environ() + scrubbedErr := probe(gitenv.ScrubRouting(inherited)) + if scrubbedErr == nil { + t.Fatal("fixture must require inherited routing, scrubbed probe found the file") + } + if exit, ok := scrubbedErr.(*exec.ExitError); ok && exit.ExitCode() == 1 { + t.Fatalf("fixture must fail the scrubbed probe for a configuration reason, got exit 1") + } + if err := probe(inherited); err != nil { + t.Fatalf("inherited tracking precondition: %v", err) + } + + if !isGitTracked(tracked) { + t.Error("bare work tree tracking was ignored, secret writes are no longer refused") + } + if isGitTracked(untracked) { + t.Error("untracked file reported as tracked") + } + if err := checkSecretGitTracked(tracked, "linear.api_key"); err == nil || !strings.Contains(err.Error(), "refusing to write secret key") { + t.Errorf("tracked secret refusal = %v", err) + } + if err := checkSecretGitTracked(untracked, "linear.api_key"); err != nil { + t.Errorf("untracked secret refused: %v", err) + } +} + +// Fixture setup uses the same routing boundary before any per-case poison is set. +func runConfigProbeGit(t *testing.T, dir string, args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = gitenv.ScrubRouting(os.Environ()) + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v in %s: %v\n%s", args, dir, err, output) + } +} diff --git a/internal/config/worktree_config_test.go b/internal/config/worktree_config_test.go index 892a9adb8..8cef7aa60 100644 --- a/internal/config/worktree_config_test.go +++ b/internal/config/worktree_config_test.go @@ -287,6 +287,36 @@ func TestWorktreeFallbackConfigPath(t *testing.T) { }) } +func TestWorktreeFallbackConfigPathIgnoresInheritedGitRouting(t *testing.T) { + _, worktreeDir, want := setupConfigWorktree(t) + + decoyRepo := filepath.Join(t.TempDir(), "decoy") + if err := os.MkdirAll(decoyRepo, 0o755); err != nil { + t.Fatal(err) + } + command := exec.Command("git", "init", "--quiet") + command.Dir = decoyRepo + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("initialize decoy repository: %v\n%s", err, output) + } + t.Setenv("GIT_DIR", filepath.Join(decoyRepo, ".git")) + t.Setenv("GIT_WORK_TREE", decoyRepo) + t.Setenv("GIT_COMMON_DIR", filepath.Join(decoyRepo, ".git")) + + got := worktreeFallbackConfigPath(worktreeDir) + gotResolved, err := filepath.EvalSymlinks(filepath.Clean(got)) + if err != nil { + t.Fatalf("EvalSymlinks(%q): %v", got, err) + } + wantResolved, err := filepath.EvalSymlinks(filepath.Clean(want)) + if err != nil { + t.Fatalf("EvalSymlinks(%q): %v", want, err) + } + if gotResolved != wantResolved { + t.Fatalf("worktreeFallbackConfigPath() = %q, want target repository config %q", gotResolved, wantResolved) + } +} + func TestGitDirsForRepo_NonGitRepo(t *testing.T) { if gitDir, commonDir, ok := gitDirsForRepo(t.TempDir()); ok || gitDir != "" || commonDir != "" { t.Fatalf("gitDirsForRepo(non-git) = (%q, %q, %v), want empty paths and false", gitDir, commonDir, ok) diff --git a/internal/config/yaml_config.go b/internal/config/yaml_config.go index ed40e1f4e..b6d752cf3 100644 --- a/internal/config/yaml_config.go +++ b/internal/config/yaml_config.go @@ -10,6 +10,7 @@ import ( "strconv" "strings" + "github.com/steveyegge/beads/internal/gitenv" "gopkg.in/yaml.v3" ) @@ -178,14 +179,35 @@ func IsSecretKey(key string) bool { return false } -// isGitTracked returns true if the file at path is tracked by git -// (i.e., has been git-added). Uses `git ls-files --error-unmatch`. +// isGitTracked reports whether either the containing repository or the +// inherited Git context tracks the file at path (i.e., it has been git-added). +// Uses `git ls-files --error-unmatch`. If neither probe succeeds, errors count +// as untracked — the secret guard only blocks writes it can prove are unsafe. +// +// The containing repository is probed first so inherited routing cannot hide a +// tracked file. Exit 1 is git's "repository reached, path is not tracked" +// answer and is final; any other failure means the scrubbed environment +// reached no repository at all — as for a bare repository whose work tree is +// named only by GIT_DIR/GIT_WORK_TREE — so the inherited context is consulted +// before declaring the file untracked. Mirrors isGitTrackedFile in cmd/bd. func isGitTracked(path string) bool { - cmd := exec.Command("git", "ls-files", "--error-unmatch", path) - cmd.Dir = filepath.Dir(path) - cmd.Stdout = nil - cmd.Stderr = nil - return cmd.Run() == nil + dir := filepath.Dir(path) + inherited := os.Environ() + for _, env := range [][]string{gitenv.ScrubRouting(inherited), inherited} { + cmd := exec.Command("git", "ls-files", "--error-unmatch", path) + cmd.Dir = dir + cmd.Env = env + cmd.Stdout = nil + cmd.Stderr = nil + err := cmd.Run() + if err == nil { + return true + } + if exit, ok := err.(*exec.ExitError); ok && exit.ExitCode() == 1 { + return false + } + } + return false } var secretKeyEnvVarHints = map[string]string{ //nolint:gosec // Values are environment variable names, not credentials. diff --git a/internal/execenv/execenv.go b/internal/execenv/execenv.go new file mode 100644 index 000000000..1f50bb8ed --- /dev/null +++ b/internal/execenv/execenv.go @@ -0,0 +1,155 @@ +// Package execenv provides helpers for constructing explicit subprocess +// environments with the same key identity rules as os/exec. +package execenv + +import ( + "runtime" + "strings" +) + +// A single host seam lets package tests exercise the exported wrappers for +// both key policies without changing the process environment. +// Process-wide seam: tests that swap it must not run in parallel. +var hostOS = runtime.GOOS + +// KeyIdentityForOS returns the key identity used by os/exec on goos. Callers +// doing repeated membership checks can normalize once; POSIX keys stay exact. +func KeyIdentityForOS(key, goos string) string { + return keyIdentityForWindows(key, goos == "windows") +} + +// KeyEqual reports whether left and right identify the same environment key +// for a subprocess on the current host. Windows keys are case-insensitive; +// keys on other hosts are exact. +func KeyEqual(left, right string) bool { + return KeyEqualForOS(left, right, hostOS) +} + +// KeyEqualForOS compares environment keys using goos subprocess semantics. +func KeyEqualForOS(left, right, goos string) bool { + return keyEqualForWindows(left, right, goos == "windows") +} + +// KeyHasPrefixForOS compares a key, rather than an environment entry, with a +// prefix using goos subprocess semantics. Valueless-entry policy belongs to +// the caller. +func KeyHasPrefixForOS(key, prefix, goos string) bool { + windows := goos == "windows" + return strings.HasPrefix(keyIdentityForWindows(key, windows), keyIdentityForWindows(prefix, windows)) +} + +func keyEqualForWindows(left, right string, windows bool) bool { + return keyIdentityForWindows(left, windows) == keyIdentityForWindows(right, windows) +} + +// ContainsKeyWithPrefix reports whether env contains a key beginning with one +// of prefixes, using the current host's environment-key semantics. +func ContainsKeyWithPrefix(env []string, prefixes ...string) bool { + return containsKeyWithPrefixForWindows(env, hostOS == "windows", prefixes...) +} + +func containsKeyWithPrefixForWindows(env []string, windows bool, prefixes ...string) bool { + identities := make([]string, len(prefixes)) + for i, prefix := range prefixes { + identities[i] = keyIdentityForWindows(prefix, windows) + } + for _, entry := range env { + key, _, ok := split(entry) + if !ok { + continue + } + key = keyIdentityForWindows(key, windows) + for _, prefix := range identities { + if strings.HasPrefix(key, prefix) { + return true + } + } + } + return false +} + +// Lookup returns the last value for key in env, matching os/exec's last-wins +// handling of duplicate effective keys. +func Lookup(env []string, key string) (string, bool) { + return lookupForWindows(env, key, hostOS == "windows") +} + +func lookupForWindows(env []string, key string, windows bool) (string, bool) { + wanted := keyIdentityForWindows(key, windows) + var value string + var found bool + for _, entry := range env { + entryKey, entryValue, ok := split(entry) + if ok && keyIdentityForWindows(entryKey, windows) == wanted { + value, found = entryValue, true + } + } + return value, found +} + +// Without returns a copy of env without entries matching keys. Unrelated +// duplicates, malformed entries, and Windows drive pseudo-variables are +// preserved in their original order. The input slice is not modified. +func Without(env []string, keys ...string) []string { + return WithoutForOS(env, hostOS, keys...) +} + +// WithoutForOS is Without with explicit goos environment-key semantics. +func WithoutForOS(env []string, goos string, keys ...string) []string { + return withoutForWindows(env, goos == "windows", keys...) +} + +func withoutForWindows(env []string, windows bool, keys ...string) []string { + drop := make(map[string]struct{}, len(keys)) + for _, key := range keys { + drop[keyIdentityForWindows(key, windows)] = struct{}{} + } + + out := make([]string, 0, len(env)) + for _, entry := range env { + key, _, ok := split(entry) + if ok { + if _, remove := drop[keyIdentityForWindows(key, windows)]; remove { + continue + } + } + out = append(out, entry) + } + return out +} + +// keyIdentityForWindows mirrors the key normalization in os/exec.dedupEnvCase. +// strings.ToLower is intentional: EqualFold would collapse Unicode +// near-collisions such as s and ſ that os/exec keeps distinct. +func keyIdentityForWindows(key string, windows bool) string { + if windows { + return strings.ToLower(key) + } + return key +} + +// EntryKey returns an entry's key using the same split rule as os/exec, +// including drive pseudo-variables. A bare entry is returned unchanged so +// callers retain authority over their valueless-entry policy. +func EntryKey(entry string) string { + if key, _, ok := split(entry); ok { + return key + } + return entry +} + +// split mirrors os/exec's handling of Windows drive pseudo-variables such as +// =C:=C:\work, whose key includes the leading equals sign. +func split(entry string) (key, value string, ok bool) { + separator := strings.IndexByte(entry, '=') + if separator == 0 { + next := strings.IndexByte(entry[1:], '=') + if next >= 0 { + separator = next + 1 + } + } + if separator < 0 { + return "", "", false + } + return entry[:separator], entry[separator+1:], true +} diff --git a/internal/execenv/execenv_test.go b/internal/execenv/execenv_test.go new file mode 100644 index 000000000..51cb1acf8 --- /dev/null +++ b/internal/execenv/execenv_test.go @@ -0,0 +1,193 @@ +package execenv + +import ( + "runtime" + "slices" + "testing" +) + +func TestKeyIdentityForWindows(t *testing.T) { + tests := []struct { + name string + key string + windows bool + want string + }{ + {name: "Unix stays exact", key: "BeAdS_DiR", want: "BeAdS_DiR"}, + {name: "Windows lowercases", key: "BeAdS_DiR", windows: true, want: "beads_dir"}, + {name: "Windows keeps long s distinct", key: "BEADſ_DIR", windows: true, want: "beadſ_dir"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + goos := "linux" + if tt.windows { + goos = "windows" + } + if got := KeyIdentityForOS(tt.key, goos); got != tt.want { + t.Errorf("KeyIdentityForOS(%q, %q) = %q, want %q", tt.key, goos, got, tt.want) + } + }) + } +} + +func TestEntryKey(t *testing.T) { + for _, tc := range []struct{ entry, want string }{ + {"NAME=value=with=equals", "NAME"}, + {"NAME=", "NAME"}, + {"GIT_CONFIG_COUNT", "GIT_CONFIG_COUNT"}, + {"GIT_DIR", "GIT_DIR"}, + {"", ""}, + {`=C:=C:\work`, "=C:"}, + {"=leading", ""}, + } { + t.Run(tc.entry, func(t *testing.T) { + if got := EntryKey(tc.entry); got != tc.want { + t.Errorf("EntryKey(%q) = %q, want %q", tc.entry, got, tc.want) + } + }) + } +} + +func TestKeyEqualUsesHostSemantics(t *testing.T) { + if got, want := KeyEqual("BeAdS_DiR", "BEADS_DIR"), runtime.GOOS == "windows"; got != want { + t.Errorf("KeyEqual mixed-case = %v, want %v on %s", got, want, runtime.GOOS) + } + if KeyEqual("BEADſ_DIR", "BEADS_DIR") { + t.Error("KeyEqual merged Unicode long s with ASCII s") + } +} + +func TestEnvironmentOperationsForBothHosts(t *testing.T) { + for _, tc := range []struct { + name string + windows bool + }{ + {name: "Unix"}, + {name: "Windows", windows: true}, + } { + t.Run(tc.name, func(t *testing.T) { + previousHost := hostOS + hostOS = "linux" + if tc.windows { + hostOS = "windows" + } + t.Cleanup(func() { hostOS = previousHost }) + // Exercise all four exported host wrappers, so hardwiring one to + // POSIX semantics is falsifiable even when this test runs on Linux. + env := []string{"MIXED=canonical-first", "mixed=lower-last", "KEEP=first", "KEEP=second", "MALFORMED", `=C:=C:\work`, "MIXEſ=near-collision"} + original := slices.Clone(env) + if got := KeyEqual("MIXED", "mixed"); got != tc.windows { + t.Errorf("mixed-case equality = %v", got) + } + if KeyEqual("MIXEſ", "MIXES") { + t.Error("equality merged the Unicode near-collision") + } + wantValue := "canonical-first" + wantWithout := []string{"KEEP=first", "KEEP=second", "MALFORMED", `=C:=C:\work`, "MIXEſ=near-collision"} + if tc.windows { + wantValue = "lower-last" + } else { + wantWithout = append([]string{"mixed=lower-last"}, wantWithout...) + } + if value, ok := Lookup(env, "MIXED"); !ok || value != wantValue { + t.Errorf("lookup = %q, %v, want %q, true", value, ok, wantValue) + } + if value, ok := Lookup(env, "=C:"); !ok || value != `C:\work` { + t.Errorf("drive lookup = %q, %v", value, ok) + } + if got := ContainsKeyWithPrefix(env, "miX"); got != tc.windows { + t.Errorf("mixed-case prefix = %v", got) + } + if got := KeyHasPrefixForOS("MIXED", "miX", hostOS); got != tc.windows { + t.Errorf("explicit key prefix = %v", got) + } + if got := Without(env, "MIXED"); !slices.Equal(got, wantWithout) { + t.Errorf("without = %q, want %q", got, wantWithout) + } + if !slices.Equal(env, original) { + t.Errorf("input mutated: %q", env) + } + }) + } +} + +func TestWithoutUsesHostSemanticsAndPreservesOtherEntries(t *testing.T) { + in := []string{ + "FIRST=keep-first", + "beads_dir=drop-on-windows", + "BEADS_DIR=drop-canonical", + "ALLOWED=keep-duplicate-first", + "MALFORMED", + "BEADſ_DIR=keep-unicode-near-collision", + "ALLOWED=keep-duplicate-second", + `=C:=C:\work`, + "LAST=keep-last", + } + original := slices.Clone(in) + + got := Without(in, "BEADS_DIR") + want := []string{ + "FIRST=keep-first", + "beads_dir=drop-on-windows", + "ALLOWED=keep-duplicate-first", + "MALFORMED", + "BEADſ_DIR=keep-unicode-near-collision", + "ALLOWED=keep-duplicate-second", + `=C:=C:\work`, + "LAST=keep-last", + } + if runtime.GOOS == "windows" { + want = slices.Delete(want, 1, 2) + } + if !slices.Equal(got, want) { + t.Fatalf("Without() = %q, want %q on %s", got, want, runtime.GOOS) + } + if !slices.Equal(in, original) { + t.Fatalf("Without modified input: got %q, want %q", in, original) + } +} + +func TestLookupUsesLastEffectiveValue(t *testing.T) { + env := []string{ + "TARGET=first", + "target=mixed-case", + "TARGET=last", + "MALFORMED", + `=C:=C:\work`, + } + value, ok := Lookup(env, "TARGET") + if !ok || value != "last" { + t.Fatalf("Lookup(TARGET) = %q, %v; want last, true", value, ok) + } + if value, ok := Lookup(env, "target"); runtime.GOOS == "windows" { + if !ok || value != "last" { + t.Fatalf("Lookup(target) = %q, %v; want last, true on Windows", value, ok) + } + } else if !ok || value != "mixed-case" { + t.Fatalf("Lookup(target) = %q, %v; want mixed-case, true on %s", value, ok, runtime.GOOS) + } + if value, ok := Lookup(env, "MISSING"); ok || value != "" { + t.Fatalf("Lookup(MISSING) = %q, %v; want empty, false", value, ok) + } + if value, ok := Lookup(env, "=C:"); !ok || value != `C:\work` { + t.Fatalf("Lookup(=C:) = %q, %v; want %q, true", value, ok, `C:\work`) + } +} + +func TestContainsKeyWithPrefixUsesKeyIdentity(t *testing.T) { + env := []string{ + "MALFORMED", + `=C:=C:\work`, + "dolt_remote_password=secret", + "DOLT_REMOTEſ_PASSWORD=near-collision", + } + if got, want := ContainsKeyWithPrefix(env, "DOLT_REMOTE_"), runtime.GOOS == "windows"; got != want { + t.Errorf("ContainsKeyWithPrefix mixed-case = %v, want %v on %s", got, want, runtime.GOOS) + } + if ContainsKeyWithPrefix([]string{"DOLT_REMOTEſ_PASSWORD=secret"}, "DOLT_REMOTES_") { + t.Error("ContainsKeyWithPrefix merged Unicode long s with ASCII s") + } + if ContainsKeyWithPrefix([]string{"DOLT_REMOTE_PASSWORD", `=C:=C:\work`}, "DOLT_REMOTE_") { + t.Error("ContainsKeyWithPrefix treated a malformed or drive entry as a matching key-value entry") + } +} diff --git a/internal/gitenv/routing.go b/internal/gitenv/routing.go new file mode 100644 index 000000000..5864fd052 --- /dev/null +++ b/internal/gitenv/routing.go @@ -0,0 +1,107 @@ +// Package gitenv defines Git environment boundaries shared by command and +// startup discovery code. +package gitenv + +import ( + "fmt" + "os" + "runtime" + "strings" + + "github.com/steveyegge/beads/internal/execenv" +) + +var routingKeys = map[string]struct{}{ + "GIT_ALTERNATE_OBJECT_DIRECTORIES": {}, + "GIT_CEILING_DIRECTORIES": {}, + "GIT_COMMON_DIR": {}, + "GIT_DIR": {}, + "GIT_DISCOVERY_ACROSS_FILESYSTEM": {}, + "GIT_EXEC_PATH": {}, + "GIT_GRAFT_FILE": {}, + "GIT_IMPLICIT_WORK_TREE": {}, + "GIT_INDEX_FILE": {}, + "GIT_INTERNAL_SUPER_PREFIX": {}, + "GIT_NAMESPACE": {}, + "GIT_OBJECT_DIRECTORY": {}, + "GIT_PREFIX": {}, + "GIT_QUARANTINE_PATH": {}, + "GIT_REPLACE_REF_BASE": {}, + "GIT_SHALLOW_FILE": {}, + "GIT_SUPER_PREFIX": {}, + "GIT_TEMPLATE_DIR": {}, + "GIT_WORK_TREE": {}, +} + +// Derive Windows membership once from the canonical routing-key set. +var windowsRoutingKeys = func() map[string]struct{} { + keys := make(map[string]struct{}, len(routingKeys)) + for key := range routingKeys { + keys[execenv.KeyIdentityForOS(key, "windows")] = struct{}{} + } + return keys +}() + +var windowsConfigPrefix = execenv.KeyIdentityForOS("GIT_CONFIG", "windows") + +// EntryKey returns the key portion using the shared subprocess split rule. +func EntryKey(entry string) string { + return execenv.EntryKey(entry) +} + +// IsRoutingKeyForOS reports whether key can redirect Git away from an explicit +// working directory or alter its repository, index, object, namespace, +// executable, template, or config authority. Environment names follow host +// semantics: byte-exact on POSIX and case-insensitive on Windows. +func IsRoutingKeyForOS(key, goos string) bool { + keys := routingKeys + prefix := "GIT_CONFIG" + if goos == "windows" { + keys = windowsRoutingKeys + prefix = windowsConfigPrefix + } + key = execenv.KeyIdentityForOS(key, goos) + if strings.HasPrefix(key, prefix) { + return true + } + _, routing := keys[key] + return routing +} + +// ScrubRouting removes Git routing entries using the current host's +// environment-key semantics. +func ScrubRouting(env []string) []string { + return ScrubRoutingForOS(env, runtime.GOOS) +} + +// 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. +func ScrubRoutingForOS(env []string, goos string) []string { + cleaned := make([]string, 0, len(env)) + for _, entry := range env { + if IsRoutingKeyForOS(EntryKey(entry), goos) { + continue + } + cleaned = append(cleaned, entry) + } + return cleaned +} + +// 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. +func ClearRouting() (bool, error) { + removed := false + for _, entry := range os.Environ() { + key := EntryKey(entry) + if !IsRoutingKeyForOS(key, runtime.GOOS) { + continue + } + if err := os.Unsetenv(key); err != nil { + return removed, fmt.Errorf("unset %s: %w", key, err) + } + removed = true + } + return removed, nil +} diff --git a/internal/gitenv/routing_test.go b/internal/gitenv/routing_test.go new file mode 100644 index 000000000..84e006a50 --- /dev/null +++ b/internal/gitenv/routing_test.go @@ -0,0 +1,174 @@ +package gitenv + +import ( + "os" + "reflect" + "runtime" + "testing" +) + +func TestScrubRoutingForOSUsesHostKeySemantics(t *testing.T) { + input := []string{ + "PATH=/trusted/bin", + "HOME=/home/test", + "GIT_AUTHOR_NAME=Test User", + "GIT_DIR=/wrong", + "git_work_tree=/wrong-case", + "GIT_CONFIG_COUNT=1", + "GIT_CONFIG_KEY_0=core.worktree", + "git_config_value_0=/wrong-case", + "GIT_OBJECT_DIRECTORY=/wrong-objects", + "GIT_EXEC_PATH=/wrong-exec", + "GIT_NO_REPLACE_OBJECTS=1", + "GIT_OPTIONAL_LOCKS=1", + } + + for _, test := range []struct { + name string + goos string + want []string + }{ + { + name: "POSIX names are case-sensitive", + goos: "linux", + want: []string{"PATH=/trusted/bin", "HOME=/home/test", "GIT_AUTHOR_NAME=Test User", "git_work_tree=/wrong-case", "git_config_value_0=/wrong-case", "GIT_NO_REPLACE_OBJECTS=1", "GIT_OPTIONAL_LOCKS=1"}, + }, + { + name: "Windows names are case-insensitive", + goos: "windows", + want: []string{"PATH=/trusted/bin", "HOME=/home/test", "GIT_AUTHOR_NAME=Test User", "GIT_NO_REPLACE_OBJECTS=1", "GIT_OPTIONAL_LOCKS=1"}, + }, + } { + t.Run(test.name, func(t *testing.T) { + if got := ScrubRoutingForOS(input, test.goos); !reflect.DeepEqual(got, test.want) { + t.Fatalf("ScrubRoutingForOS() = %#v, want %#v", got, test.want) + } + }) + } +} + +func TestRoutingUnicodeKeysFollowSubprocessIdentity(t *testing.T) { + for _, goos := range []string{"linux", "windows"} { + for _, tc := range []struct { + key string + unix, windows bool + }{ + {"GIT_DIR", true, true}, + {"GIT_CONFIG_COUNT", true, true}, + {"git_dir", false, true}, + {"GİT_DİR", false, true}, + {"GIT_WORK_TREE", false, true}, + {"gİt_config_count", false, true}, + {"GIT_ſHALLOW_FILE", false, false}, + {"GıT_DIR", false, false}, + } { + t.Run(goos+"/"+tc.key, func(t *testing.T) { + input := []string{tc.key + "=value", "KEEP=first", "KEEP=second", `=C:=C:\work`} + blocked := tc.unix + if goos == "windows" { + blocked = tc.windows + } + want := input + if blocked { + want = input[1:] + } + if got := ScrubRoutingForOS(input, goos); !reflect.DeepEqual(got, want) { + t.Fatalf("routing environment = %q, want %q", got, want) + } + }) + } + } +} + +func TestEntryKeyUsesSharedSplit(t *testing.T) { + for _, tc := range []struct{ entry, want string }{ + {"KEEP=value=more", "KEEP"}, + {`=C:=C:\work`, "=C:"}, + {"GIT_CONFIG", "GIT_CONFIG"}, + {"", ""}, + } { + if got := EntryKey(tc.entry); got != tc.want { + t.Errorf("EntryKey(%q) = %q, want %q", tc.entry, got, tc.want) + } + } +} + +func TestScrubRoutingUsesHostKeySemantics(t *testing.T) { + input := []string{ + "GIT_DIR=canonical", "git_dir=mixed", "GİT_DİR=conservative", + "GIT_WORK_TREE=lookup-alias", "gİt_config_count=conservative", + "GıT_DIR=distinct", "GIT_ſHALLOW_FILE=distinct", "GIT_CONFIG", + "KEEP=first", "KEEP=second", "KEEP=GIT_DIR=value", + "GIT_OPTIONAL_LOCKS=1", "GIT_NO_REPLACE_OBJECTS=1", "MALFORMED", `=C:=C:\work`, + } + original := append([]string(nil), input...) + want := []string{ + "GıT_DIR=distinct", "GIT_ſHALLOW_FILE=distinct", + "KEEP=first", "KEEP=second", "KEEP=GIT_DIR=value", + "GIT_OPTIONAL_LOCKS=1", "GIT_NO_REPLACE_OBJECTS=1", "MALFORMED", `=C:=C:\work`, + } + if runtime.GOOS != "windows" { + want = append([]string{"git_dir=mixed", "GİT_DİR=conservative", + "GIT_WORK_TREE=lookup-alias", "gİt_config_count=conservative"}, want...) + } + if got := ScrubRouting(input); !reflect.DeepEqual(got, want) { + t.Fatalf("native routing environment = %q, want %q", got, want) + } + if !reflect.DeepEqual(input, original) { + t.Fatalf("input environment mutated: %q", input) + } +} + +func TestClearRoutingPreservesNonRoutingGitControls(t *testing.T) { + type envEntry struct { + key string + value string + } + var inherited []envEntry + for _, entry := range os.Environ() { + key := EntryKey(entry) + if !IsRoutingKeyForOS(key, runtime.GOOS) { + continue + } + value, _ := os.LookupEnv(key) + inherited = append(inherited, envEntry{key: key, value: value}) + } + t.Cleanup(func() { + for _, entry := range os.Environ() { + key := EntryKey(entry) + if IsRoutingKeyForOS(key, runtime.GOOS) { + if err := os.Unsetenv(key); err != nil { + t.Errorf("unset %s during cleanup: %v", key, err) + } + } + } + for _, entry := range inherited { + if err := os.Setenv(entry.key, entry.value); err != nil { + t.Errorf("restore %s during cleanup: %v", entry.key, err) + } + } + }) + + t.Setenv("GIT_DIR", "/wrong") + t.Setenv("GIT_CONFIG_COUNT", "1") + t.Setenv("GIT_OPTIONAL_LOCKS", "1") + t.Setenv("GIT_NO_REPLACE_OBJECTS", "1") + + removed, err := ClearRouting() + if err != nil { + t.Fatal(err) + } + if !removed { + t.Fatal("ClearRouting() did not report removing routing entries") + } + for _, key := range []string{"GIT_DIR", "GIT_CONFIG_COUNT"} { + if _, ok := os.LookupEnv(key); ok { + t.Fatalf("%s remains set", key) + } + } + for _, key := range []string{"GIT_OPTIONAL_LOCKS", "GIT_NO_REPLACE_OBJECTS"} { + if value := os.Getenv(key); value != "1" { + t.Fatalf("%s = %q, want 1", key, value) + } + } +} diff --git a/internal/githooksenv/githooksenv.go b/internal/githooksenv/githooksenv.go index 1af5351b7..2f23f118f 100644 --- a/internal/githooksenv/githooksenv.go +++ b/internal/githooksenv/githooksenv.go @@ -19,8 +19,9 @@ package githooksenv import ( "os" - "strings" "sync" + + "github.com/steveyegge/beads/internal/execenv" ) // ParametersEnv is git's environment variable for injecting one-off config @@ -45,14 +46,8 @@ func AppendParameter(existing, param string) string { // Extract returns the GIT_CONFIG_PARAMETERS value from an environment slice, // using exec's last-wins semantics for duplicate keys. func Extract(env []string) string { - prefix := ParametersEnv + "=" - var val string - for _, e := range env { - if v, ok := strings.CutPrefix(e, prefix); ok { - val = v - } - } - return val + value, _ := execenv.Lookup(env, ParametersEnv) + return value } // DisabledEnv returns env with git client-side hooks disabled, for callers @@ -61,14 +56,8 @@ func Extract(env []string) string { // with the no-hooks override appended. The input slice is not modified. func DisabledEnv(env []string) []string { merged := AppendParameter(Extract(env), NoHooksParam) - prefix := ParametersEnv + "=" - out := make([]string, 0, len(env)+1) - for _, e := range env { - if !strings.HasPrefix(e, prefix) { - out = append(out, e) - } - } - return append(out, prefix+merged) + out := execenv.Without(env, ParametersEnv) + return append(out, ParametersEnv+"="+merged) } // Process-environment state for WithDisabled. A refcount rather than a plain diff --git a/internal/githooksenv/githooksenv_test.go b/internal/githooksenv/githooksenv_test.go index 437985b39..57b164a2a 100644 --- a/internal/githooksenv/githooksenv_test.go +++ b/internal/githooksenv/githooksenv_test.go @@ -2,6 +2,7 @@ package githooksenv import ( "os" + "runtime" "slices" "testing" ) @@ -37,6 +38,37 @@ func TestDisabledEnv(t *testing.T) { } } +func TestDisabledEnvUsesHostKeySemantics(t *testing.T) { + nearCollision := "GIT_CONFIG_PARAMETERſ='near=3'" + in := []string{ + ParametersEnv + "='canonical=1'", + "git_config_parameters='mixed=2'", + nearCollision, + "MALFORMED", + `=C:=C:\work`, + } + + got := DisabledEnv(in) + want := []string{ + "git_config_parameters='mixed=2'", + nearCollision, + "MALFORMED", + `=C:=C:\work`, + ParametersEnv + "='canonical=1' " + NoHooksParam, + } + if runtime.GOOS == "windows" { + want = []string{ + nearCollision, + "MALFORMED", + `=C:=C:\work`, + ParametersEnv + "='mixed=2' " + NoHooksParam, + } + } + if !slices.Equal(got, want) { + t.Fatalf("DisabledEnv() = %q, want %q on %s", got, want, runtime.GOOS) + } +} + func TestAppendParameter(t *testing.T) { tests := []struct { name string diff --git a/internal/gittraceenv/gittraceenv.go b/internal/gittraceenv/gittraceenv.go index 6ee3af5c4..a1cb20f60 100644 --- a/internal/gittraceenv/gittraceenv.go +++ b/internal/gittraceenv/gittraceenv.go @@ -36,6 +36,8 @@ import ( "runtime" "strings" "sync" + + "github.com/steveyegge/beads/internal/execenv" ) // pathCapableVars are git tracing variables that accept a file target (an @@ -100,15 +102,6 @@ func stderrDirected(name, value string) bool { return true } -// envNameEquals compares environment variable names: exact on POSIX, -// case-insensitive on Windows to match Win32 (and git's) env lookup. -func envNameEquals(a, b string) bool { - if runtime.GOOS == "windows" { - return strings.EqualFold(a, b) - } - return a == b -} - // Process-environment state for WithScrubbed. A refcount rather than a plain // mutex held across fn, for the same reason as githooksenv: remote operations // are network-bound and can take minutes, overlapping operations all want the @@ -183,12 +176,12 @@ func ScrubEnv(env []string) []string { func shouldScrub(name, value string) bool { for _, n := range alwaysStderrVars { - if envNameEquals(name, n) { + if execenv.KeyEqual(name, n) { return true } } for _, n := range pathCapableVars { - if envNameEquals(name, n) { + if execenv.KeyEqual(name, n) { return stderrDirected(n, value) } } diff --git a/internal/gittraceenv/gittraceenv_test.go b/internal/gittraceenv/gittraceenv_test.go index 6a99e8201..e0f115f4d 100644 --- a/internal/gittraceenv/gittraceenv_test.go +++ b/internal/gittraceenv/gittraceenv_test.go @@ -180,6 +180,18 @@ func TestScrubEnvWindowsCaseInsensitiveNames(t *testing.T) { } } +func TestScrubEnvDoesNotEqualFoldUnicodeKeys(t *testing.T) { + // EqualFold considers the Unicode long s equivalent to ASCII s. os/exec's + // Windows key identity uses strings.ToLower and keeps them distinct. + // The required Windows helper lane runs this: restoring EqualFold cannot + // be detected by this test's POSIX execution alone. + nearCollision := "GIT_TRACE_ſETUP=1" + got := ScrubEnv([]string{nearCollision}) + if !slices.Equal(got, []string{nearCollision}) { + t.Fatalf("ScrubEnv() = %q, want Unicode near-collision preserved", got) + } +} + // Git on Windows treats a leading dir separator as absolute (is_dir_sep), so // a Git-Bash-style file target like /c/temp/git.trace never touches stderr // and must be kept, even though filepath.IsAbs rejects it. diff --git a/internal/metrics/metrics_test.go b/internal/metrics/metrics_test.go index 51e5736a0..50e8a8f57 100644 --- a/internal/metrics/metrics_test.go +++ b/internal/metrics/metrics_test.go @@ -4,6 +4,7 @@ import ( "context" "os" "path/filepath" + "runtime" "strings" "testing" "time" @@ -201,6 +202,36 @@ func TestFlusherChildEnvPinsSanctionedEndpoint(t *testing.T) { } } +func TestFlusherChildEnvUsesHostKeySemantics(t *testing.T) { + parent := []string{ + "beads_metrics_endpoint=https://attacker.example/collect", + "bd_is_flusher=stale", + "BEADſ_METRICS_ENDPOINT=near-collision", + "MALFORMED", + `=C:=C:\work`, + } + const sanctioned = "https://gastownhall-eventsapi.com/mp/collect" + + got := flusherChildEnv(parent, sanctioned) + for _, entry := range []string{"BEADſ_METRICS_ENDPOINT=near-collision", "MALFORMED", `=C:=C:\work`} { + if !envContains(got, entry) { + t.Errorf("flusherChildEnv dropped unrelated entry %q: %q", entry, got) + } + } + for _, entry := range []string{ + "beads_metrics_endpoint=https://attacker.example/collect", + "bd_is_flusher=stale", + } { + wantContains := runtime.GOOS != "windows" + if gotContains := envContains(got, entry); gotContains != wantContains { + t.Errorf("flusherChildEnv retained %q = %v, want %v on %s", entry, gotContains, wantContains, runtime.GOOS) + } + } + if !envContains(got, EnvEndpoint+"="+sanctioned) || !envContains(got, EnvIsFlusher+"=1") { + t.Errorf("flusherChildEnv did not append canonical values: %q", got) + } +} + // TestMaybeSpawnFlusherNoOpInsideFlusher guards the structural no-recursion // guard: a process already marked as the flusher must never spawn another one, // independent of send-metrics' os.Exit. diff --git a/internal/metrics/spawn.go b/internal/metrics/spawn.go index f8caf9fd2..afe7f925c 100644 --- a/internal/metrics/spawn.go +++ b/internal/metrics/spawn.go @@ -6,6 +6,8 @@ import ( "path/filepath" "strings" "time" + + "github.com/steveyegge/beads/internal/execenv" ) const SendMetricsSubcommand = "send-metrics" @@ -224,13 +226,7 @@ func startDetached(cmd *exec.Cmd) (int, error) { // so the detached flusher cannot be redirected by project-controlled // environment. func flusherChildEnv(env []string, endpoint string) []string { - out := make([]string, 0, len(env)+2) - for _, kv := range env { - if strings.HasPrefix(kv, EnvEndpoint+"=") || strings.HasPrefix(kv, EnvIsFlusher+"=") { - continue - } - out = append(out, kv) - } + out := execenv.Without(env, EnvEndpoint, EnvIsFlusher) if endpoint != "" { out = append(out, EnvEndpoint+"="+endpoint) } diff --git a/internal/storage/dolt/credentials.go b/internal/storage/dolt/credentials.go index 7a72a7f96..700e71c8a 100644 --- a/internal/storage/dolt/credentials.go +++ b/internal/storage/dolt/credentials.go @@ -17,6 +17,7 @@ import ( "strings" "sync" + "github.com/steveyegge/beads/internal/execenv" "github.com/steveyegge/beads/internal/githooksenv" "github.com/steveyegge/beads/internal/storage" ) @@ -451,36 +452,29 @@ func (c *remoteCredentials) applyToCmd(cmd *exec.Cmd) { if c.empty() { return } - // Start with current process env, filtering out any existing credential vars + cmd.Env = c.childEnv(os.Environ()) +} + +func (c *remoteCredentials) childEnv(base []string) []string { + // Start with the base environment, filtering out any existing credential vars // to prevent stale values from leaking into the subprocess. - env := make([]string, 0, len(os.Environ())+2) - for _, e := range os.Environ() { - if !strings.HasPrefix(e, "DOLT_REMOTE_USER=") && !strings.HasPrefix(e, "DOLT_REMOTE_PASSWORD=") { - env = append(env, e) - } - } + env := execenv.Without(base, "DOLT_REMOTE_USER", "DOLT_REMOTE_PASSWORD") if c.username != "" { env = append(env, "DOLT_REMOTE_USER="+c.username) } if c.password != "" { env = append(env, "DOLT_REMOTE_PASSWORD="+c.password) } - cmd.Env = env + return env } func setCmdEnv(cmd *exec.Cmd, key, value string) { - prefix := key + "=" base := cmd.Env if base == nil { base = os.Environ() } - env := make([]string, 0, len(base)+1) - for _, e := range base { - if !strings.HasPrefix(e, prefix) { - env = append(env, e) - } - } - cmd.Env = append(env, prefix+value) + env := execenv.Without(base, key) + cmd.Env = append(env, key+"="+value) } func applyS3ChecksumEnvToCmd(cmd *exec.Cmd) { @@ -512,8 +506,7 @@ func applyNoGitHooksToCmd(cmd *exec.Cmd) { // Append rather than replace: a caller that set its own // GIT_CONFIG_PARAMETERS (a test harness pinning user.email, say) would // otherwise have it silently dropped by this call. - setCmdEnv(cmd, githooksenv.ParametersEnv, - githooksenv.AppendParameter(githooksenv.Extract(base), githooksenv.NoHooksParam)) + cmd.Env = githooksenv.DisabledEnv(base) } // saveEnv captures the current state of key and returns a function that puts @@ -827,15 +820,11 @@ func (s *DoltStore) prepareCLIRouteForCloudAuth(ctx context.Context, remote stri if len(prefixes) == 0 { return false, nil // unknown scheme — not a cloud remote } - for _, e := range os.Environ() { - for _, prefix := range prefixes { - if strings.HasPrefix(e, prefix) { - if err := s.ensureMatchingCLIRemote(remote, remoteURL); err != nil { - return false, fmt.Errorf("remote %q has cloud credentials and requires CLI routing: %w", remote, err) - } - return true, nil - } + if execenv.ContainsKeyWithPrefix(os.Environ(), prefixes...) { + if err := s.ensureMatchingCLIRemote(remote, remoteURL); err != nil { + return false, fmt.Errorf("remote %q has cloud credentials and requires CLI routing: %w", remote, err) } + return true, nil } return false, nil } diff --git a/internal/storage/dolt/credentials_test.go b/internal/storage/dolt/credentials_test.go index b6b58d65c..62c12d4be 100644 --- a/internal/storage/dolt/credentials_test.go +++ b/internal/storage/dolt/credentials_test.go @@ -70,6 +70,68 @@ func TestApplyS3ChecksumEnvToCmd(t *testing.T) { } } +func TestSetCmdEnvUsesHostKeySemantics(t *testing.T) { + nearCollision := "DOLT_REMOTE_PAſSWORD=near-collision" + cmd := exec.Command("dolt", "push") // #nosec G204 -- test command is not executed + cmd.Env = []string{ + "dolt_remote_password=mixed-stale", + "DOLT_REMOTE_PASSWORD=canonical-stale", + nearCollision, + "MALFORMED", + `=C:=C:\work`, + } + + setCmdEnv(cmd, "DOLT_REMOTE_PASSWORD", "fresh") + want := []string{ + "dolt_remote_password=mixed-stale", + nearCollision, + "MALFORMED", + `=C:=C:\work`, + "DOLT_REMOTE_PASSWORD=fresh", + } + if runtime.GOOS == "windows" { + want = want[1:] + } + if !slices.Equal(cmd.Env, want) { + t.Fatalf("setCmdEnv() = %q, want %q on %s", cmd.Env, want, runtime.GOOS) + } +} + +func TestRemoteCredentialsChildEnvUsesHostKeySemantics(t *testing.T) { + nearCollision := "DOLT_REMOTE_PAſSWORD=near-collision" + base := []string{ + "dolt_remote_user=mixed-stale-user", + "DOLT_REMOTE_USER=canonical-stale-user", + "dolt_remote_password=mixed-stale-password", + "DOLT_REMOTE_PASSWORD=canonical-stale-password", + nearCollision, + "MALFORMED", + `=C:=C:\work`, + } + original := slices.Clone(base) + creds := &remoteCredentials{username: "fresh-user", password: "fresh-password"} + + got := creds.childEnv(base) + want := []string{ + "dolt_remote_user=mixed-stale-user", + "dolt_remote_password=mixed-stale-password", + nearCollision, + "MALFORMED", + `=C:=C:\work`, + "DOLT_REMOTE_USER=fresh-user", + "DOLT_REMOTE_PASSWORD=fresh-password", + } + if runtime.GOOS == "windows" { + want = want[2:] + } + if !slices.Equal(got, want) { + t.Fatalf("childEnv() = %q, want %q on %s", got, want, runtime.GOOS) + } + if !slices.Equal(base, original) { + t.Fatal("childEnv modified its input") + } +} + func TestPrepareDoltCLITransferCommandAppliesCredentialsAndS3Env(t *testing.T) { t.Setenv(awsResponseChecksumValidationEnv, "when_supported") creds := &remoteCredentials{username: "user", password: "pass"} diff --git a/scripts/ci/test-windows-env-helpers.sh b/scripts/ci/test-windows-env-helpers.sh new file mode 100644 index 000000000..31894452b --- /dev/null +++ b/scripts/ci/test-windows-env-helpers.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Run the actual helper packages on Windows, including their native-only tests. +set -euo pipefail + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +cd "$root" +# These environment helpers are pure Go; no C compiler is needed for this lane. +export CGO_ENABLED=0 +# shellcheck source=../../.buildflags +source .buildflags + +go_bin=$(command -v go) || { echo 'Go is required for Windows environment tests' >&2; exit 1; } +host=$("$go_bin" env GOHOSTOS GOOS) || exit $? +if [[ "$host" != $'windows\nwindows' ]]; then + echo 'Environment helper tests require native Windows Go host and target' >&2 + exit 1 +fi + +log=$(mktemp) +trap 'rm -f "$log"' EXIT +if "$go_bin" test -count=1 -v ./internal/execenv ./internal/githooksenv ./internal/gittraceenv ./internal/gitenv >"$log" 2>&1; then + cat "$log" +else + status=$? + cat "$log" + exit "$status" +fi + +# Additional passing cases are welcome; these Windows boundaries must execute. +required=( + TestEnvironmentOperationsForBothHosts/Windows + TestKeyEqualUsesHostSemantics + TestDisabledEnvUsesHostKeySemantics + TestScrubEnvWindowsCaseInsensitiveNames + TestScrubEnvDoesNotEqualFoldUnicodeKeys + TestStderrDirectedWindowsLeadingSlashIsFileTarget + TestScrubRoutingUsesHostKeySemantics +) +for name in "${required[@]}"; do + count=$(grep -Ec "^[[:space:]]*--- PASS: $name \\(" "$log" || true) + if [[ "$count" != 1 ]]; then + echo "Required Windows test did not pass exactly once: $name" >&2 + exit 1 + fi +done diff --git a/scripts/ci_workflow_test.go b/scripts/ci_workflow_test.go index 61450e3e3..da606b381 100644 --- a/scripts/ci_workflow_test.go +++ b/scripts/ci_workflow_test.go @@ -165,6 +165,22 @@ func TestPRWorkflowExercisesWindowsBenchmarkEnvScrubbing(t *testing.T) { } } +func TestPRWorkflowExercisesWindowsEnvironmentHelpers(t *testing.T) { + workflow := readCIWorkflow(t, "pr.yml") + // The benchmark test owns this shared job's matrix and CI Gate propagation. + job := workflow.job(t, "pr-preflight-platforms") + step := job.step(t, "Check shared environment key semantics") + if step.If != "matrix.os == 'windows-latest'" || step.Shell != "bash" { + t.Errorf("environment helpers need native Windows Bash: if=%q shell=%q", step.If, step.Shell) + } + if step.ContinueOnError != nil && step.ContinueOnError != false { + t.Error("environment helper step may not continue on error") + } + if got := strings.TrimSpace(step.Run); got != "bash scripts/ci/test-windows-env-helpers.sh" { + t.Errorf("environment helper entrypoint = %q", got) + } +} + func TestPRCIGateRequiresJSWasmHookExecution(t *testing.T) { workflow := readCIWorkflow(t, "pr.yml") job := workflow.job(t, "check-cmd-bd-puregeo-tests") diff --git a/scripts/repro-dolt-prod-timeouts/main.go b/scripts/repro-dolt-prod-timeouts/main.go index 8d73547e3..c9ee44d66 100644 --- a/scripts/repro-dolt-prod-timeouts/main.go +++ b/scripts/repro-dolt-prod-timeouts/main.go @@ -21,7 +21,6 @@ import ( "os" "os/exec" "path/filepath" - "runtime" "sort" "strconv" "strings" @@ -29,6 +28,7 @@ import ( "time" _ "github.com/go-sql-driver/mysql" + "github.com/steveyegge/beads/internal/execenv" "github.com/steveyegge/beads/internal/storage/depid" "github.com/steveyegge/beads/internal/storage/doltutil" ) @@ -1135,31 +1135,7 @@ func subprocessEnv(extra ...string) []string { } func cleanEnv(env []string, keys ...string) []string { - drop := make(map[string]struct{}, len(keys)) - for _, key := range keys { - drop[environmentKeyIdentity(key)] = struct{}{} - } - out := env[:0] - for _, e := range env { - key, _, ok := strings.Cut(e, "=") - if ok { - if _, skip := drop[environmentKeyIdentity(key)]; skip { - continue - } - } - out = append(out, e) - } - return out -} - -// environmentKeyIdentity mirrors the key comparison used by os/exec when it -// prepares a child environment. strings.ToLower is intentional: EqualFold -// would collapse Unicode near-collisions that os/exec keeps distinct. -func environmentKeyIdentity(key string) string { - if runtime.GOOS == "windows" { - return strings.ToLower(key) - } - return key + return execenv.Without(env, keys...) } func tail(s string, max int) string { diff --git a/scripts/repro-dolt-prod-timeouts/main_test.go b/scripts/repro-dolt-prod-timeouts/main_test.go index 5e8f4f114..967dde1b1 100644 --- a/scripts/repro-dolt-prod-timeouts/main_test.go +++ b/scripts/repro-dolt-prod-timeouts/main_test.go @@ -17,6 +17,7 @@ import ( "time" "github.com/DATA-DOG/go-sqlmock" + "github.com/steveyegge/beads/internal/execenv" "github.com/steveyegge/beads/internal/storage/depid" "github.com/steveyegge/beads/internal/storage/doltutil" "github.com/steveyegge/beads/internal/storage/schema" @@ -238,7 +239,7 @@ func TestBenchmarkCommandBuildersStripDoltEnvOverrides(t *testing.T) { for _, key := range subprocessEnvDenylist { for _, entry := range cmd.Env { gotKey, _, _ := strings.Cut(entry, "=") - if environmentKeyIdentity(gotKey) == environmentKeyIdentity(key) { + if execenv.KeyEqual(gotKey, key) { t.Fatalf("Env retained ambient denied override %q", entry) } }