fix(gitenv): retain explicit null config suppression (#6461)

* 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 <ewencuthiell@gmail.com>

* 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(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(config): isolate role readers from inherited Git routing (saa-cgh.109.1)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(doctor): isolate role lookups from inherited Git routing (saa-cgh.109.2)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(git): isolate domain role configuration from inherited routing (saa-cgh.109.5)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(doctor): isolate explicit-path worktree fallback from Git routing (saa-cgh.109.6)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): probe the selected repository before configuring roles (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(beads): cover common-directory role routing (saa-cgh.109.1)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(git): explain system config routing flags (saa-cgh.109.6)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(init): explain role probe discovery ceiling behavior (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(beads): scope stable worktree probes to selected path (saa-cgh.109.13)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* Clarify selected discovery probes and cover separate routing vectors (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Keep init role operations on the captured selected Git context (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Observe inline Git configuration directly in linked-worktree fixture (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Align selected-tail fixtures with captured role authority (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(beads): select explicit directory discovery context (GH#6384) (saa-cgh.120.6)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitenv): retain explicit Git config suppression (saa-cgh.120.7)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(config): pin identity under null config suppression (saa-cgh.120.7)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitenv): keep role authority off inherited config suppression

Maintainer review fixes for PR #6461 (adopt-pr iterations 1-2). Addresses the
three major findings raised against the contributor branch, plus the major,
three minors and nit that iteration 2 raised against the first fixup; each fix
is pinned by a test that was mutation-proved against the pre-fix source.

F1 (major, security) — the leaf exempts GIT_CONFIG_GLOBAL=/dev/null,
GIT_CONFIG_SYSTEM=/dev/null and GIT_CONFIG_NOSYSTEM from ScrubRouting. Null
suppression cannot redirect a read, but it can blind one, and DetectUserRole
answers a missed read with detectFromURL, whose no-remote and SSH arms both
return Maintainer. Reproduced on this branch: a global beads.role=contributor
with GIT_CONFIG_GLOBAL=/dev/null resolved to maintainer, where the leaf's
parent fb7a93ad4 scrubbed the entry and read contributor.

Taken the synthesis's alternative arm (a): keep the exemption where the value
has no authority, drop it where it does. New ScrubRoutingAndSuppression
applies at every beads.role reader — internal/routing, doctor/role.go,
config_show.go, RepoContext.Role, bd config get/set/unset/set-many, and the
domain adapter's key-specific arms (see A1: iteration 1 claimed that last site
and did not actually reach it). Arm (b), making roleFromGitConfig's miss
non-permissive, was declined: "no beads.role and no remote implies maintainer"
is documented base behavior for local projects, so closing it there would
reclassify every such user rather than the blinded slice this PR introduced.

F2 (major, blast radius) — the stack hardened every role reader and left four
writer/reader sites fully inherited, a divergence that did not exist at base:
an inherited GIT_DIR sends setBeadsRole's write to another repository while
the scrubbed readers look at the one the user is standing in. All four now
share the same boundary (init.go's getBeadsRole/setBeadsRole,
init_contributor.go, hooks.go's uninstall --get/--unset pair).

The required fix also asked for cmd.Dir = repoRoot on the init.go pair. Still
not taken, but not on the grounds iteration 1 recorded (see A2). What holds is
the measurement against the vector the fix targets: with GIT_DIR, GIT_WORK_TREE
and GIT_COMMON_DIR gone, no production path chdirs away from the invocation
directory — `grep -rn 'os\.Chdir' --include='*.go'` over production cmd/bd
returns nothing and `bd init` takes no path argument — so threading a repoRoot
through both signatures and their eight call sites buys no behavior change
against a redirect.

F3 (major, security) — this PR converted internal/config's isGitTracked probe
from inherited to scrub-only. The guard is fail-open by construction, so in a
legitimately routed checkout (bare repo.git, GIT_DIR/GIT_WORK_TREE exported,
no in-tree .git) the probe stopped answering and `bd config set
linear.api_key` would have written the credential into a tracked file.
Restored the two-probe shape sibling #6464 applied to the structural twin:
scrubbed probe first, inherited second, either "tracked" refuses.

F5 (minor) — disclose that scrubbing GIT_CEILING_DIRECTORIES widens upward
discovery rather than bounding it, in the worktree comment and the docs
paragraph that asserted only the narrowing effect. F2's fix extends that
trade-off to two more sites, so the disclosure is now load-bearing.

F7 (minor) — renamed isConfigSuppression to isConfigSuppressionControl and
documented why the NOSYSTEM arm is deliberately value-blind. Took the
rename/document arm rather than restricting the arm to git-true values, which
would have contradicted the PR's own pinned table.

F10 (nit) — pinned both suppression tables in the windows-latest required
list; verified each name matches the gate's grep exactly once.

--- Iteration 2 ---

The first fixup's F1 census named a site it did not reach, and its cmd.Dir
rationale named a mechanism that does not hold. Both are corrected here.

A1 (major, security) — the domain adapter's key-specific arm was guarded by
`key == "beads.role" && r.env == nil`, which is dead on the only production
role path: runInitProxiedServerTail rebinds the use case to
NewInitGitRepository whenever t.workDir != "" (its sole construction site
passes cwd), and that constructor captures ScrubRouting(os.Environ()) —
non-nil, suppression retained. The nil-env constructor has no
BeadsRole/SetBeadsRole caller, so the arm could only fire from tests, while
`bd init` under an inherited GIT_CONFIG_GLOBAL=/dev/null still missed a global
role, took hasRole=false, and persisted beads.role=maintainer into
repository-local config, where it outranks the global value for every later
read in a clean environment. Iteration 1 therefore left F1's escalation not
just alive but durable, on the one path the fix was supposed to close.

Fixed by keying the strict scrub on the config key alone and applying it to
whichever environment the repository already carries (roleAuthorityEnv). That
preserves capture semantics — NewInitGitRepository keeps its captured HOME,
the property git_test.go's captured_home case pins — and removes only the
suppression entries. Codex's alternative of rebuilding the constructor's whole
env was declined: it moves every key for no gain on this finding.

A2 (minor, contract fidelity) — iteration 1 justified declining cmd.Dir with
"repository selection is left to the working directory — the one input the
scrub keeps". That is false, and false in the file a future reader consults
before deciding whether to bound the pair: GIT_CEILING_DIRECTORIES is a routing
key too, so the scrub removes a bound rather than installing one. Measured from
a non-repository directory nested under a repository: `git config beads.role
<value>` fails "not in a git directory" while a ceiling below that repository is
inherited, and writes that repository's local config once the ceiling is
scrubbed. The decline itself stands, since the measurement behind it was made
against the GIT_DIR vector; getBeadsRole now records selection as the working
directory *or a containing ancestor*, which is also what makes
clearWorktreeGitRoutingEnv's existing cross-reference to "init's role probe"
true.

A3 (minor, consistency) — `bd config unset beads.role` and `bd config set-many
beads.role=` were the two spellings of that mutation still on ScrubRouting, in
the same file as the two that moved. Both measured inert: `git config <key>
<value>` and `--unset <key>` target the repository-local file, which the
suppression variables cannot select. Moved for parity rather than annotated,
because a divergence inside one file is how the next one starts.

Test evidence (minor) — the writer pair's two subtests both pass on the
redirect alone, so downgrading getBeadsRole back to ScrubRouting left them
green even though suppression is the load-bearing half at those sites
(init.go treats a getBeadsRole miss as permission to write a default role).
Added a global_null blinding subtest with the same unblinded fixture guard.

A4 (nit) — doctor/role.go's isGitRepo was the last probe in that file on the
suppression-retaining scrub, and it gates the "beads.role not configured"
warning. rev-parse is config-sensitive through safe.directory, which lives in
global config, so a retained GIT_CONFIG_GLOBAL=/dev/null can downgrade that
warning to "N/A (not a git repository)". Moved onto the same boundary as its
two siblings. As the finding records, the safe.directory precondition was not
reproduced end to end; the change is uniformity within the file.

Tests. Every pin reds only on its own defect:
- routing: reverting to ScrubRouting reds only the blinded-read subtest; the
  unblinded fixture guard and the PR's inject-vector table stay green.
- gitenv: keeping suppression reds 10 of 16 new subtests, none of the PR's.
- cmd/bd: restoring the inherited env reds both redirect subtests and names
  both halves ("the write did not land where bd is standing" / "an inherited
  GIT_DIR captured the write"), while the PR's own role roundtrip stays green
  — it followed the same redirect on both sides, so it never saw this.
- config: the two arms are proved separately. Scrub-only reds only the
  legitimate-routing subtest; inherited-only reds only the poisoned-routing
  subtest, so the new fallback cannot be read as a way around the scrub.
- domain/git (A1): restoring the r.env == nil provenance guard reds
  global_null only; unblinded stays green, and no other test in the package
  moves — which is the same measurement that confirms the arm had no coverage
  before this iteration.

Deferred to follow-up, recorded for the approval summary: F4 (delete
isRoleGitRepo and resolve the dead else-if), F6 (user.name degrading to
hostname, which needs the PR's own subtest re-pointed), F8 (execenv fold
divergence), F9 and F11 (GetIdentity hostname degradation under inherited
suppression). F9's mechanism is confirmed — identity supplied only via
GIT_CONFIG_COUNT is lost when GIT_CONFIG_* is stripped, git reports "Please
tell me who you are", while GIT_AUTHOR_*/GIT_COMMITTER_* survive — but its
"leave artifact commits on the inherited environment" arm would re-open the
GIT_DIR redirect this PR's tail swap closed, and the non-regressing arm
(re-injecting inline identity pre-scrub) is a design change with no observed
victim in this repo.

Validation (iteration 2): internal/{gitenv,routing,storage/domain/git} full
packages green; cmd/bd/doctor full package run; targeted cmd/bd run over the
role, config and init blast radius green at 54 tests; go build ./... clean; go
vet plus CGO_ENABLED=0 and GOOS=windows CGO_ENABLED=0 vet clean on every
changed package. Remaining local reds are base-parity, each matching the
recorded cause: cmd/bd/doctor's seven (the launcher's global
beads.role=maintainer short-circuits CheckBeadsRole before isGitRepo is
reached, plus Dolt server availability) and
TestInitContributorSetsBeadsRoleContributor ("--contributor requires
interactive prompts", this session's stdin is not a TTY).

--- Iteration 3 ---

Iteration 3 reviewed 0220eed32 and approved it: claude filed no findings,
codex's six fix validations all came back correct, synthesis recorded
Decision: approve, and the scorecard scored 881/1000 with Required Changes:
None. The residual was two minors and a nit, none of them merge gates. All
three are taken here because they are comment-and-constant scope, so nothing
in the approved behavior moves.

B1 (minor, blast radius; codex filed it as major, demoted at synthesis) — the
isGitRepo() gate that decides whether the role pair runs is still fully
inherited while the pair it guards is now strict, so from a non-repository
directory with an inherited GIT_DIR the gate opens, the scrubbed read misses,
and the safety-net write fails "not in a git directory". Recorded at the
GH#2950 safety net rather than restructured, for the three reasons the
demotion rests on. The achievable outcome is base parity: sync_git.go is
byte-identical at base and the pair was inherited there too, so a GIT_DIR
holder already reached Maintainer before this PR — more directly, by pointing
at a repository whose beads.role is maintainer. The failure is not silent:
init prints "Warning: failed to set beads.role" unless --quiet, and every
later detection prints "beads.role not configured (GH#2950)" with two Fix
lines. And the prescribed roleRepoAvailable() gate provably does not close it:
all five gate sites are bare `if isGitRepo()` with no else, so a strict gate
answers false in exactly the described band, nothing is written, the role
stays unset, and detection still falls to detectFromURL. The optional
hardening is therefore declined rather than deferred — it would delete a
warning and change no role — and the comment says so, so the next reader does
not mistake a gate change for closing the fail-open path.

B2 (minor, contract fidelity) — the getBeadsRole rationale iteration 2 wrote
to close A2 introduced a new overstatement in its closing sentence: "bd init
takes no path argument — the residual is upward discovery from an unintended
cwd, not a redirect". `bd -C <dir>` is a redirect and takes no path argument.
Verified in tree rather than from the finding: applyChangeDirSelection
(main.go) resolves the target's .beads dir and sets BEADS_DIR with no chdir,
it runs from the root PersistentPreRunE ahead of every init-related early
return in that hook, and init honors BEADS_DIR for workspace selection — so
`bd -C other init` acts on other/.beads while the pair reads and writes
beads.role in the invocation repository. init.go's own "PersistentPreRun
doesn't run for init command" note is about the later skipsStoreInit return,
not about -C, which is what made this vector easy to miss twice. Reachability
is bounded: -C requires an existing beads project at the target, so the
pairing arises on re-init rather than first init. Comment narrowed to name the
residual; threading init's resolved project root through the pair is the
stronger arm and stays out of scope as a behavior change.

B3 (nit, architectural consistency) — the adapter selected the role-authority
boundary on a bare "beads.role" literal while the use case passed the
unexported beadsRoleConfigKey, two spellings of one contract the compiler
could not couple. Exported it as domain.BeadsRoleConfigKey and compared
against it at both adapter arms; no new import edge, since package git already
imports domain. Mutation-proved rather than asserted: replacing the
comparison with the case-variant "Beads.Role" the finding names reds
TestInitGitRepositoryRoleIgnoresInheritedConfigSuppression/global_null alone
while unblinded stays green, so the drift the nit describes is caught by an
existing pin. The comparison is still exact, not case-folded: git config names
are case-insensitive, so a caller hand-writing a variant spelling would bypass
roleAuthorityEnv, but folding widens which keys take the strict environment
and no production caller passes anything but the const — a behavior change the
nit did not ask for.

Validation (iteration 3): go build ./... clean; go vet plus CGO_ENABLED=0 and
GOOS=windows CGO_ENABLED=0 vet clean on cmd/bd, cmd/bd/doctor,
internal/storage/domain, internal/storage/domain/git and internal/gitenv;
internal/storage/domain/... full packages green (domain, db, fs, git); targeted
cmd/bd role run green at 19 subtests with no skips
(TestBeadsRoleCommandsIgnoreInheritedGitRouting and
TestBeadsRoleWriterIgnoresInheritedGitRouting, including the suppression
subtest added in iteration 2); gofmt and git diff --check clean. Full cmd/bd is
still not run locally: it times out at base as well. The iteration-1 deferrals
are unchanged and still owed follow-up bead ids at finalize (F4, F6/F11, F8,
F9).

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Bee <bee@ghosttrack.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
ecuthiell 2026-09-27 16:59:08 -06:00 • committed by GitHub
commit cefcabb1e3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
28 changed files with 1355 additions and 53 deletions

View file

@ -119,12 +119,15 @@ var forceGitTracked bool
// newRoleConfigWriter captures fresh cwd and scrubbed routing once per write
// operation. The process-wide Git cache and Beads storage do not select it.
// Routing is scrubbed along with the suppression ScrubRouting deliberately
// keeps: beads.role is an authority value, and the reader it feeds treats a
// missing value as maintainer, so a suppressed config file would fail open.
func newRoleConfigWriter() (func(...string) error, error) {
dir, err := os.Getwd()
if err != nil {
return nil, err
}
env := gitenv.ScrubRouting(os.Environ())
env := gitenv.ScrubRoutingAndSuppression(os.Environ())
probe := exec.Command("git", "rev-parse", "--git-common-dir")
probe.Dir, probe.Env = dir, env
out, err := probe.Output()
@ -237,12 +240,14 @@ var configSetCmd = &cobra.Command{
}
// bd config's own beads.role reads and writes ignore inherited Git
// routing, including GIT_CONFIG_GLOBAL, so the value lands in the
// repository this command selected. The scope is this command set,
// not role resolution as a whole: routing.DetectUserRole,
// `bd config show`, `bd doctor` and `bd hooks uninstall` still
// resolve beads.role through the inherited environment, and
// beads.RepoContext.Role pins GIT_DIR/GIT_WORK_TREE last-wins but
// still inherits GIT_CONFIG_*.
// repository this command selected. beads.role is an authority
// value and the reader it feeds treats a missing value as
// maintainer, so these planes also discard the explicit suppression
// ScrubRouting deliberately keeps -- otherwise a blinded read fails
// open instead of erroring. That boundary is uniform across
// routing.DetectUserRole, `bd config show`, `bd doctor`,
// `bd hooks uninstall` and beads.RepoContext.Role, which re-pins
// GIT_DIR/GIT_WORK_TREE last-wins on top of it.
write, err := newRoleConfigWriter()
if err != nil {
return HandleError("setting beads.role in git config: %v", err)
@ -567,8 +572,9 @@ var configGetCmd = &cobra.Command{
}
if key == "beads.role" {
// Same role-authority boundary as `bd config set` above.
cmd := exec.Command("git", "config", "--get", "beads.role")
cmd.Env = gitenv.ScrubRouting(os.Environ())
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
output, err := cmd.Output()
value := strings.TrimSpace(string(output))
if err != nil {
@ -845,6 +851,9 @@ var configUnsetCmd = &cobra.Command{
}
if key == "beads.role" {
// Same role-authority boundary as `bd config set`/`get` above: every
// spelling of a beads.role mutation resolves the repository the same
// way, so the next reader has one boundary to reason about.
write, err := newRoleConfigWriter()
if err != nil {
return HandleError("unsetting beads.role in git config: %v", err)
@ -1140,6 +1149,8 @@ Examples:
}
if len(gitPairs) > 0 {
// set-many is the batch alias for `bd config set`, so it runs on the
// same role-authority boundary that verb does.
write, err := newRoleConfigWriter()
if err != nil {
return HandleError("setting beads.role in git config: %v", err)

View file

@ -11,6 +11,7 @@ import (
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/gitenv"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/workapi"
)
@ -334,6 +335,7 @@ func collectGitConfigEntries() []configEntry {
// beads.role is the only git config key currently
cmd := exec.Command("git", "config", "--get", "beads.role")
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
output, err := cmd.Output()
if err == nil {
value := strings.TrimSpace(string(output))

View file

@ -3,11 +3,14 @@ package main
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/gitenv"
)
// TestViperSourceLabel verifies source label formatting for different config sources.
@ -437,3 +440,79 @@ func TestCollectViperEntriesMetricsUserGlobalProvenance(t *testing.T) {
t.Errorf("config show --json entry %s misattributes user-global value to project config.yaml", encoded)
}
}
func TestCollectGitConfigEntriesIgnoresInheritedRouting(t *testing.T) {
for _, entry := range os.Environ() {
key := gitenv.EntryKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
}
}
pinJSONOutput(t, false)
runGit := func(t *testing.T, repo string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = repo
cmd.Env = gitenv.ScrubRouting(os.Environ())
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("fixture git %v: %v: %s", args, err, out)
}
}
for _, tc := range []struct {
name, local, global, want string
}{
{"repository", "maintainer", "", "maintainer"},
{"inline", "maintainer", "", "maintainer"},
{"default_global", "", "contributor", "contributor"},
{"absent", "", "", ""},
} {
t.Run(tc.name, func(t *testing.T) {
home, target, decoy := t.TempDir(), t.TempDir(), t.TempDir()
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
t.Setenv(key, home)
}
if tc.global != "" {
if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\nrole = "+tc.global+"\n"), 0o600); err != nil {
t.Fatal(err)
}
}
for _, repo := range []string{target, decoy} {
runGit(t, repo, "init", "--quiet")
}
runGit(t, decoy, "config", "beads.role", "decoy-role")
if tc.local != "" {
runGit(t, target, "config", "beads.role", tc.local)
}
t.Chdir(target)
poison := map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "beads.role", "GIT_CONFIG_VALUE_0": "injected-role"}
if tc.name == "repository" {
poison = map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy}
}
for key, value := range poison {
t.Setenv(key, value)
}
entries := collectGitConfigEntries()
wantGet := tc.want
if tc.want == "" {
wantGet = "beads.role (not set in git config)"
if len(entries) != 0 {
t.Errorf("absent role produced entries: %+v", entries)
}
} else if len(entries) != 1 || entries[0] != (configEntry{Key: "beads.role", Value: tc.want, Source: "git"}) {
t.Errorf("Git entries = %+v; want role=%q with source=git", entries, tc.want)
}
out := captureStdout(t, func() error { return configGetCmd.RunE(configGetCmd, []string{"beads.role"}) })
if strings.TrimSpace(out) != wantGet {
t.Errorf("config get = %q; want %q", out, wantGet)
}
for key, value := range poison {
if os.Getenv(key) != value {
t.Errorf("reader changed parent environment %s", key)
}
}
})
}
}

View file

@ -4,9 +4,11 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/steveyegge/beads/internal/gitenv"
"github.com/steveyegge/beads/internal/utils"
)
@ -155,3 +157,66 @@ func runGitInDirForDoctorTest(t *testing.T, dir string, args ...string) string {
return strings.TrimSpace(string(output))
}
func TestDoctorWorktreeFallbackIgnoresInheritedRouting(t *testing.T) {
clearResolveBeadsDirCache()
t.Cleanup(clearResolveBeadsDirCache)
for _, entry := range os.Environ() {
key := gitenv.EntryKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
}
}
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
t.Setenv(key, t.TempDir())
}
// Production ScrubRouting retains this explicit system-config suppression.
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
targetParent, target := setupBareParentWorktreeForDoctorTest(t)
decoyParent, decoy := setupBareParentWorktreeForDoctorTest(t)
want := utils.CanonicalizePath(filepath.Join(targetParent, ".beads"))
for _, dir := range []string{want, filepath.Join(decoyParent, ".beads")} {
if err := os.MkdirAll(dir, 0o750); err != nil {
t.Fatal(err)
}
}
if _, err := os.Stat(filepath.Join(target, ".beads")); !os.IsNotExist(err) {
t.Fatalf("fixture must require common-parent fallback: %v", err)
}
decoyGitDir := runGitInDirForDoctorTest(t, decoy, "rev-parse", "--absolute-git-dir")
for _, name := range []string{"decoy", "invalid_git_dir"} {
t.Run(name, func(t *testing.T) {
gitDir := decoyGitDir
if name == "invalid_git_dir" {
gitDir = filepath.Join(t.TempDir(), "missing.git")
}
t.Setenv("GIT_DIR", gitDir)
t.Setenv("GIT_WORK_TREE", decoy)
t.Setenv("GIT_COMMON_DIR", decoyParent)
before := strings.Join(os.Environ(), "\x00")
clearResolveBeadsDirCache()
if got := ResolveBeadsDirForRepo(target); !utils.PathsEqual(got, want) {
t.Errorf("cold ResolveBeadsDirForRepo() = %q, want target %q", got, want)
}
clearResolveBeadsDirCache() // Exercise the constructor's own cold resolution.
ss := NewSharedStore(target)
defer ss.Close()
if got := ss.BeadsDir(); !utils.PathsEqual(got, want) {
t.Errorf("cold NewSharedStore().BeadsDir() = %q, want target %q", got, want)
}
// Empty .beads proves path selection only, not a database or role read.
if ss.Store() != nil {
t.Error("empty fixture unexpectedly opened a database")
}
if entries, err := os.ReadDir(want); err != nil || len(entries) != 0 {
t.Errorf("empty target .beads changed: entries=%v, err=%v", entries, err)
}
if strings.Join(os.Environ(), "\x00") != before {
t.Error("doctor changed inherited environment")
}
})
}
}

View file

@ -3,9 +3,11 @@ package doctor
import (
"context"
"fmt"
"os"
"os/exec"
"strings"
"github.com/steveyegge/beads/internal/gitenv"
"github.com/steveyegge/beads/internal/storage/dolt"
)
@ -18,6 +20,7 @@ import (
func CheckBeadsRole(path string) DoctorCheck {
// Read beads.role from git config (canonical location)
cmd := exec.Command("git", "config", "--get", "beads.role")
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
if path != "" {
cmd.Dir = path
}
@ -42,6 +45,7 @@ func CheckBeadsRole(path string) DoctorCheck {
func CheckBeadsRoleWithStore(path string, ss *SharedStore) DoctorCheck {
// Read beads.role from git config (canonical location)
cmd := exec.Command("git", "config", "--get", "beads.role")
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
if path != "" {
cmd.Dir = path
}
@ -85,8 +89,15 @@ func checkBeadsRoleNotInGit(path string) DoctorCheck {
}
// isGitRepo checks whether the given path is inside a git repository.
//
// Shares the boundary of the two role reads above, which is what this probe
// gates: rev-parse is config-sensitive through safe.directory, so retaining
// suppression here could answer false for a repository that is only reachable
// via a global safe.directory entry and silently downgrade the "beads.role not
// configured" warning to "N/A (not a git repository)".
func isGitRepo(path string) bool {
cmd := exec.Command("git", "rev-parse", "--git-dir")
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
if path != "" {
cmd.Dir = path
}

View file

@ -4,7 +4,10 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"github.com/steveyegge/beads/internal/gitenv"
)
func TestCheckBeadsRole_NotConfigured(t *testing.T) {
@ -114,3 +117,90 @@ func TestCheckBeadsRole_NonexistentPath(t *testing.T) {
t.Errorf("expected status %s, got %s", StatusOK, check.Status)
}
}
func TestCheckBeadsRoleIgnoresInheritedRouting(t *testing.T) {
for _, entry := range os.Environ() {
key := gitenv.EntryKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
}
}
t.Setenv("BEADS_DIR", "")
clearResolveBeadsDirCache()
t.Cleanup(clearResolveBeadsDirCache)
for _, tc := range []struct {
name, role, global, status, message string
}{
{"repository", "maintainer", "", StatusOK, "Configured as maintainer"},
{"inline", "maintainer", "", StatusOK, "Configured as maintainer"},
{"global_override", "", "maintainer", StatusOK, "Configured as maintainer"},
{"invalid", "admin", "", StatusWarning, "Invalid beads.role value: \"admin\""},
{"absent", "", "", StatusWarning, "beads.role not configured"},
{"nonrepository", "", "", StatusOK, "N/A (not a git repository)"},
{"default_global", "", "contributor", StatusOK, "Configured as contributor"},
} {
t.Run(tc.name, func(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
if tc.global != "" {
if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\nrole = "+tc.global+"\n"), 0600); err != nil {
t.Fatal(err)
}
}
target, decoy := newGitRepo(t), newGitRepo(t)
runGit := func(repo string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir, cmd.Env = repo, gitenv.ScrubRouting(os.Environ())
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("fixture git %v: %v: %s", args, err, out)
}
}
if tc.role != "" {
runGit(target, "config", "beads.role", tc.role)
}
if tc.name != "nonrepository" {
runGit(decoy, "config", "beads.role", "decoy-role")
} else {
target = t.TempDir()
}
poison := map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy}
switch tc.name {
case "inline", "default_global":
poison = map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "beads.role", "GIT_CONFIG_VALUE_0": "injected-role"}
case "global_override":
config := filepath.Join(home, "nondefault")
if err := os.WriteFile(config, []byte("[beads]\nrole = injected-role\n"), 0600); err != nil {
t.Fatal(err)
}
poison = map[string]string{"GIT_CONFIG_GLOBAL": config}
}
for key, value := range poison {
t.Setenv(key, value)
}
for _, api := range []struct {
name string
run func(string) DoctorCheck
}{
{"standalone", CheckBeadsRole},
{"nil shared store", func(path string) DoctorCheck { return CheckBeadsRoleWithStore(path, nil) }},
{"empty shared store", func(path string) DoctorCheck { return CheckBeadsRoleWithStore(path, &SharedStore{}) }},
} {
check := api.run(target)
if check.Status != tc.status || check.Message != tc.message || check.Name != "Role Configuration" || check.Category != CategoryData {
t.Errorf("%s: got %+v; want status=%q message=%q", api.name, check, tc.status, tc.message)
}
}
for key, value := range poison {
if os.Getenv(key) != value {
t.Errorf("doctor changed parent environment %s", key)
}
}
})
}
}

View file

@ -1438,6 +1438,9 @@ func resetHooksPathIfBeadsManaged() error {
return fmt.Errorf("empty Git common directory for role reset")
}
configEnv := gitenv.ScrubRouting(os.Environ())
// beads.role is an authority value, unlike core.hooksPath, so its own
// commands drop inherited suppression too (see the role pair below).
roleConfigEnv := gitenv.ScrubRoutingAndSuppression(os.Environ())
var failures []string
cmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--get", "core.hooksPath")
@ -1474,13 +1477,18 @@ func resetHooksPathIfBeadsManaged() error {
// Keep the selected main/common config, including bare repositories with an
// external worktree, while dropping routing overrides from both commands.
// The presence query must use the same local scope as the unset.
//
// Both role commands additionally discard the explicit config suppression
// ScrubRouting keeps: beads.role is an authority value whose absence reads
// as maintainer, so a suppressed config file would report a clean uninstall
// while leaving the key set here.
getRoleCmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--get", "beads.role")
getRoleCmd.Dir = repoRoot
getRoleCmd.Env = configEnv
getRoleCmd.Env = roleConfigEnv
if out, err := getRoleCmd.CombinedOutput(); err == nil {
roleCmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--unset", "beads.role")
roleCmd.Dir = repoRoot
roleCmd.Env = configEnv
roleCmd.Env = roleConfigEnv
if output, err := roleCmd.CombinedOutput(); err != nil {
failures = append(failures, fmt.Sprintf("beads.role: %v (output: %s)", err, strings.TrimSpace(string(output))))
}

View file

@ -1940,6 +1940,13 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
// Earlier code paths may skip role-setting when BEADS_DIR is set,
// promptContributorMode fails, or edge-case flag combinations are used.
// This guarantees every init leaves a usable role-configured state.
//
// The gate and the pair answer on the same boundary: isInitRoleGitRepo
// scrubs inherited routing and config suppression exactly as
// getBeadsRole/setBeadsRole do, so the gate cannot open on a repository
// the write will then fail to reach. Gating on the inherited isGitRepo()
// instead is what used to make this safety net write the role into a
// redirected repository.
if isInitRoleGitRepo(ctx) {
if _, hasRole := getBeadsRole(); !hasRole {
fallbackRole := "maintainer"
@ -2933,20 +2940,49 @@ func shouldPromptForRole() bool {
return term.IsTerminal(int(os.Stdin.Fd()))
}
// isInitRoleGitRepo uses the same CWD and routing policy as getBeadsRole/setBeadsRole.
// isInitRoleGitRepo uses the same CWD and routing policy as getBeadsRole/setBeadsRole,
// including their suppression scrub: rev-parse is config-sensitive through
// safe.directory, so retaining suppression here could answer false for a
// repository that is only reachable via a global safe.directory entry and skip
// the role write the pair would have completed.
func isInitRoleGitRepo(ctx context.Context) bool {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-dir")
cmd.Env = gitenv.ScrubRouting(os.Environ())
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
return cmd.Run() == nil
}
// getBeadsRole reads the beads.role git config value.
// Returns the role and true if configured, or empty string and false if not set.
//
// Both halves of the pair run on the same authority boundary as every role
// reader so init cannot report a role it wrote into a different repository:
// an inherited GIT_DIR would redirect setBeadsRole's write, and inherited
// config suppression would blind the read that decides whether to write at
// all.
//
// Selection is then the working directory or a containing ancestor. The scrub
// drops GIT_CEILING_DIRECTORIES along with the redirects, so it removes a
// bound rather than installing one: measured from a non-repository directory
// nested under a repository, `git config beads.role <value>` fails "not in a
// git directory" while a ceiling below that repository is inherited, and
// writes the repository's local config once the ceiling is scrubbed. cmd.Dir
// is still not threaded through the pair, because no production path chdirs
// away from the invocation directory before these run. Two residuals remain:
// upward discovery from an unintended cwd, and `bd -C <dir>`, which redirects
// project selection by setting BEADS_DIR without chdir-ing
// (applyChangeDirSelection), so init can act on another project's workspace
// while the pair still reads and writes beads.role in the invocation
// repository; -C requires an existing beads project at the target, so that
// pairing arises on re-init rather than first init, and the GH#2950 safety net
// records the same BEADS_DIR skew. Threading init's resolved project root
// through the pair would close that one, but it is a behavior change rather
// than a boundary fix. clearWorktreeGitRoutingEnv discloses the same widening
// for the bd worktree commands.
func getBeadsRole() (string, bool) {
cmd := exec.Command("git", "config", "--get", "beads.role")
cmd.Env = gitenv.ScrubRouting(os.Environ())
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
output, err := cmd.Output()
if err != nil {
return "", false
@ -2958,10 +2994,11 @@ func getBeadsRole() (string, bool) {
return role, true
}
// setBeadsRole writes the beads.role git config value.
// setBeadsRole writes the beads.role git config value. See getBeadsRole for
// why the pair shares the role-authority environment boundary.
func setBeadsRole(role string) error {
cmd := exec.Command("git", "config", "beads.role", role)
cmd.Env = gitenv.ScrubRouting(os.Environ())
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
return cmd.Run()
}

View file

@ -347,6 +347,9 @@ func autoConfigureForkContributor(ctx context.Context, store storage.DoltStorage
return fmt.Errorf("failed to set sync.remote: %w", err)
}
// setBeadsRole carries the shared role-authority boundary: an inherited
// GIT_DIR or a suppressed config file would otherwise land this write in a
// different repository than every beads.role reader consults.
if err := setBeadsRole("contributor"); err != nil && !quiet {
fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role=contributor: %v\n", err)
}

View file

@ -0,0 +1,133 @@
package main
import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/steveyegge/beads/internal/gitenv"
)
// TestBeadsRoleWriterIgnoresInheritedGitRouting pins the init role pair to the
// same boundary as every beads.role reader. The reader half of the stack was
// hardened first, which is what makes the writer half load-bearing: with the
// writer still inherited, `GIT_DIR=<other repo>/.git bd init` writes the role
// into that other repository, then reports success while every scrubbed reader
// looks at the repository the user is actually standing in and finds nothing.
//
// Both subtests must assert *where* the value landed. A roundtrip assertion is
// vacuous here: before the fix the write and the read followed the same
// redirect, so they agreed with each other about the wrong repository.
func TestBeadsRoleWriterIgnoresInheritedGitRouting(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("role routing fixture requires Git")
}
for _, entry := range os.Environ() {
key := gitenv.EntryKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
}
}
// localRole reads repo's own config file directly, so it reports where a
// value physically landed rather than what discovery would resolve to.
localRole := func(t *testing.T, repo string) string {
t.Helper()
cmd := exec.Command("git", "config", "--local", "--get", "beads.role")
cmd.Dir = repo
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
out, err := cmd.Output()
if err != nil {
return ""
}
return strings.TrimSpace(string(out))
}
setLocalRole := func(t *testing.T, repo, role string) {
t.Helper()
cmd := exec.Command("git", "config", "--local", "beads.role", role)
cmd.Dir = repo
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("fixture git config: %v: %s", err, out)
}
}
poison := func(t *testing.T, decoy string) {
t.Helper()
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
t.Setenv("GIT_WORK_TREE", decoy)
}
t.Run("write stays in the selected repository", func(t *testing.T) {
target, decoy := newGitRepo(t), newGitRepo(t)
t.Chdir(target)
poison(t, decoy)
if err := setBeadsRole("contributor"); err != nil {
t.Fatalf("setBeadsRole: %v", err)
}
if got := localRole(t, target); got != "contributor" {
t.Errorf("target beads.role = %q, want %q: the write did not land where bd is standing", got, "contributor")
}
if got := localRole(t, decoy); got != "" {
t.Errorf("decoy beads.role = %q, want unset: an inherited GIT_DIR captured the write", got)
}
})
t.Run("read ignores a redirected repository", func(t *testing.T) {
target, decoy := newGitRepo(t), newGitRepo(t)
setLocalRole(t, decoy, "maintainer")
t.Chdir(target)
poison(t, decoy)
// Fixture guard: the decoy really does hold a readable role, so a
// "not maintainer" result below can only come from ignoring it.
if got := localRole(t, decoy); got != "maintainer" {
t.Fatalf("decoy fixture beads.role = %q, want %q", got, "maintainer")
}
role, hasRole := getBeadsRole()
if hasRole {
t.Errorf("getBeadsRole() = %q, true; want unset: the read followed an inherited GIT_DIR", role)
}
})
// A redirect is not the only way to defeat the pair, and the two subtests
// above cannot tell the two vectors apart: they pass on the GIT_DIR half
// alone, so downgrading getBeadsRole to gitenv.ScrubRouting leaves them
// green. Suppression is the load-bearing half here — init.go treats a
// getBeadsRole miss as permission to write a default role — so it needs a
// pin of its own.
t.Run("read ignores inherited config suppression", func(t *testing.T) {
home, target := t.TempDir(), newGitRepo(t)
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
t.Setenv(key, home)
}
if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\n\trole = contributor\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Chdir(target)
for _, tc := range []struct{ name, blind string }{
// Fixture guard: the global role must be readable at all, and must
// not be shadowed by a local one, or the blinded case below would
// pass for the wrong reason.
{"unblinded", ""},
{"global_null", os.DevNull},
} {
t.Run(tc.name, func(t *testing.T) {
if tc.blind != "" {
t.Setenv("GIT_CONFIG_GLOBAL", tc.blind)
}
role, hasRole := getBeadsRole()
if !hasRole || role != "contributor" {
t.Errorf("getBeadsRole() = %q, %t; want %q, true: a blinded read is what makes init write a default role", role, hasRole, "contributor")
}
})
}
})
}

View file

@ -672,9 +672,9 @@ func scrubWorktreeGitRoutingEnv(env []string) []string {
}
// scrubWorktreeGitRoutingEnvForOS removes inherited Git repository, index,
// object, namespace, executable, template, and config routing. It deliberately
// preserves non-routing controls such as GIT_OPTIONAL_LOCKS; the removal runner
// applies its stricter policy separately.
// object, namespace, executable, template, and custom config routing. It keeps
// explicit null config suppression, GIT_CONFIG_NOSYSTEM and non-routing controls
// such as GIT_OPTIONAL_LOCKS; the removal runner applies its stricter policy separately.
func scrubWorktreeGitRoutingEnvForOS(env []string, goos string) []string {
return gitenv.ScrubRoutingForOS(env, goos)
}
@ -709,10 +709,18 @@ func worktreeGitEnvKey(entry string) string {
// clearWorktreeGitRoutingEnv establishes the command working directory as the
// repository-selection boundary without changing process identity or signal
// semantics. Startup config discovery applies the same scrub to its pre-hook
// config-path probe only; the .beads database discovery probes in
// internal/beads still honor inherited routing, so the two planes can resolve
// different repositories.
// semantics. Startup config discovery applies the same boundary to its one
// pre-hook Git probe, and the .beads discovery probes that run against an
// already selected path share it too (beads.selectedBeadsGitOutput and
// ResolveBeadsDirForRepo). The generic internal/beads gitOutput probes and
// internal/git/gitdir.go still honor inherited routing, so those planes can
// still resolve a different repository than this one (bd-p4che).
//
// The boundary removes inherited discovery *redirects*. It is not a floor:
// GIT_CEILING_DIRECTORIES is a routing key too, so dropping it also re-enables
// upward discovery, and a `bd worktree` command run outside a repository can
// then select a containing parent that an inherited ceiling would have hidden
// (init's role probe records the same trade-off).
func clearWorktreeGitRoutingEnv(cmd *cobra.Command) error {
if !hasWorktreeCommandAncestor(cmd) {
return nil

View file

@ -79,6 +79,10 @@ func TestGitRevParse(t *testing.T) {
func TestGitCmdInDirSuppressesHooksViaGitConfig(t *testing.T) {
t.Setenv("GIT_DIR", "/wrong")
t.Setenv("GIT_OPTIONAL_LOCKS", "1")
suppression := map[string]string{"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.DevNull, "GIT_CONFIG_SYSTEM": os.DevNull}
for key, value := range suppression {
t.Setenv(key, value)
}
cmd := gitCmdInDir(t.Context(), "/tmp/example", "status", "--porcelain")
if cmd.Dir != "/tmp/example" {
t.Fatalf("cmd.Dir = %q, want /tmp/example", cmd.Dir)
@ -104,6 +108,14 @@ func TestGitCmdInDirSuppressesHooksViaGitConfig(t *testing.T) {
if env == "GIT_OPTIONAL_LOCKS=1" {
hasOptionalLocks = true
}
key := worktreeGitEnvKey(env)
if want, ok := suppression[key]; ok {
if env != key+"="+want {
t.Fatalf("changed config suppression: %q", env)
}
delete(suppression, key)
continue
}
if gitenv.IsRoutingKeyForOS(worktreeGitEnvKey(env), runtime.GOOS) && env != "GIT_TEMPLATE_DIR=" {
t.Fatalf("cmd.Env retains Git routing state: %q", env)
}
@ -114,6 +126,9 @@ func TestGitCmdInDirSuppressesHooksViaGitConfig(t *testing.T) {
if !hasOptionalLocks {
t.Fatal("cmd.Env did not preserve GIT_OPTIONAL_LOCKS")
}
if len(suppression) != 0 {
t.Fatalf("cmd.Env dropped explicit config suppression: %v", suppression)
}
}
func TestScrubWorktreeRemovalGitEnvUsesSharedWindowsKeyIdentity(t *testing.T) {

View file

@ -25,6 +25,12 @@ and the `.beads` database discovery probes in `internal/beads`, so those
variables can still select which workspace `bd` opens. Clearing those variables
from the `bd` process environment applies only to `bd worktree` commands.
`GIT_CEILING_DIRECTORIES` is scrubbed along with the redirects. That removes a
*bound* rather than a redirect, so discovery from the working directory is
widened, not narrowed: run in a directory that is not itself a repository, `bd`
can select a containing parent repository that an inherited ceiling would have
hidden.
```
project/
├── .git/ # Shared Git directory

View file

@ -21,6 +21,7 @@ import (
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/gitenv"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/backends"
"github.com/steveyegge/beads/internal/utils"
@ -228,12 +229,12 @@ func preferStableBranchWorktreeBeadsDir(beadsDir string) string {
return ""
}
branch, err := gitOutput(repoRoot, "rev-parse", "--abbrev-ref", "HEAD")
branch, err := selectedBeadsGitOutput(repoRoot, "rev-parse", "--abbrev-ref", "HEAD")
if err != nil || branch != "HEAD" {
return ""
}
head, err := gitOutput(repoRoot, "rev-parse", "HEAD")
head, err := selectedBeadsGitOutput(repoRoot, "rev-parse", "HEAD")
if err != nil || head == "" {
return ""
}
@ -282,9 +283,21 @@ func isDetachedCommitWorktreePath(path string) bool {
}
func gitOutput(dir string, args ...string) (string, error) {
return gitOutputEnv(nil, dir, args...)
}
// selectedBeadsGitOutput probes the repository of an already selected .beads path.
// The shared filter retains NOSYSTEM and null GLOBAL/SYSTEM suppression,
// while discarding custom config paths and inline config overrides.
func selectedBeadsGitOutput(dir string, args ...string) (string, error) {
return gitOutputEnv(gitenv.ScrubRouting(os.Environ()), dir, args...)
}
func gitOutputEnv(env []string, dir string, args ...string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "git", append([]string{"-C", dir}, args...)...) //nolint:gosec // args are internal, not user-supplied
cmd.Env = env
output, err := cmd.Output()
if err != nil {
return "", err
@ -293,7 +306,7 @@ func gitOutput(dir string, args ...string) (string, error) {
}
func listWorktrees(repoRoot string) ([]worktreeInfo, error) {
output, err := gitOutput(repoRoot, "worktree", "list", "--porcelain")
output, err := selectedBeadsGitOutput(repoRoot, "worktree", "list", "--porcelain")
if err != nil {
return nil, err
}
@ -643,7 +656,7 @@ func FindBeadsDirFrom(startDir string) string {
startDir = utils.CanonicalizePath(startDir)
repoRoot := ""
if out, err := gitOutput(startDir, "rev-parse", "--show-toplevel"); err == nil {
if out, err := selectedBeadsGitOutput(startDir, "rev-parse", "--show-toplevel"); err == nil {
repoRoot = utils.CanonicalizePath(out)
}
@ -1174,6 +1187,7 @@ func ResolveBeadsDirForRepo(repoPath string) string {
func worktreeFallbackBeadsDirForRepo(repoPath string) string {
cmd := exec.Command("git", "-C", repoPath, "rev-parse", "--git-dir", "--git-common-dir")
cmd.Env = gitenv.ScrubRouting(os.Environ())
output, err := cmd.Output()
if err != nil {
return ""

View file

@ -6,6 +6,7 @@ import (
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"slices"
"strings"
@ -13,6 +14,7 @@ import (
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/gitenv"
"github.com/steveyegge/beads/internal/utils"
)
@ -2695,3 +2697,188 @@ func TestGitPathForRepo(t *testing.T) {
}
})
}
func TestFindBeadsDirFromIgnoresInheritedRouting(t *testing.T) {
for _, entry := range os.Environ() {
key := gitenv.EntryKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
}
}
home := t.TempDir()
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
t.Setenv(key, home)
}
for _, layout := range []string{"regular", "bare"} {
t.Run(layout, func(t *testing.T) {
setup := setupRegularWorktreeRepo
if layout == "bare" {
setup = setupBareParentWorktree
}
main, target := setup(t)
decoyMain, decoy := setup(t)
for _, dir := range []string{main, decoyMain} {
if err := os.MkdirAll(filepath.Join(dir, ".beads", "dolt"), 0755); err != nil {
t.Fatal(err)
}
}
decoyGit := runGitInDir(t, decoy, "rev-parse", "--absolute-git-dir")
start := filepath.Join(target, "sub dir")
if err := os.Mkdir(start, 0755); err != nil {
t.Fatal(err)
}
t.Chdir(decoy)
t.Setenv("BEADS_DIR", filepath.Join(decoyMain, ".beads"))
for _, name := range []string{"ordinary", "decoy", "invalid", "work_tree_only"} {
t.Run(name, func(t *testing.T) {
if name != "ordinary" {
t.Setenv("GIT_WORK_TREE", decoy)
if name != "work_tree_only" {
gitDir := decoyGit
if name == "invalid" {
gitDir = filepath.Join(home, "missing git dir")
}
t.Setenv("GIT_DIR", gitDir)
}
got, err := gitOutput(start, "rev-parse", "--show-toplevel")
if (name == "invalid" && err == nil) || (name != "invalid" && (err != nil || !utils.PathsEqual(got, decoy))) {
t.Fatalf("inherited probe precondition: %q (%v)", got, err)
}
}
before := os.Environ()
if got := FindBeadsDirFrom(start); !utils.PathsEqual(got, filepath.Join(main, ".beads")) {
t.Errorf("explicit discovery = %q, want selected shared .beads", got)
}
cwd, err := os.Getwd()
if err != nil || !utils.PathsEqual(cwd, decoy) || !reflect.DeepEqual(before, os.Environ()) {
t.Errorf("explicit discovery changed process directory/environment: %q (%v)", cwd, err)
}
})
}
})
}
}
func TestSelectedBeadsCanonicalizerIgnoresInheritedRouting(t *testing.T) {
t.Chdir(t.TempDir())
detached, stable, database := setupDetachedCommitBeadsWorktree(t)
_, decoy, _ := setupDetachedCommitBeadsWorktree(t)
decoyGitDir := runGitInDir(t, filepath.Dir(decoy), "rev-parse", "--absolute-git-dir")
decoyCommonDir := runGitInDir(t, filepath.Dir(decoy), "rev-parse", "--path-format=absolute", "--git-common-dir")
redirect := filepath.Join(t.TempDir(), ".beads")
if err := os.Mkdir(redirect, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(redirect, RedirectFileName), []byte(detached), 0600); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
env map[string]string
query []string
}{
{"decoy", map[string]string{"GIT_DIR": decoyGitDir}, []string{"rev-parse", "--abbrev-ref", "HEAD"}},
{"invalid", map[string]string{"GIT_DIR": filepath.Join(t.TempDir(), "missing git dir")}, []string{"rev-parse", "--abbrev-ref", "HEAD"}},
{"work_tree_only", map[string]string{"GIT_WORK_TREE": filepath.Dir(decoy)}, []string{"rev-parse", "--show-toplevel"}},
{"common_dir_only", map[string]string{"GIT_COMMON_DIR": decoyCommonDir}, []string{"rev-parse", "--git-common-dir"}},
// Linked worktrees stay non-bare regardless of core.bare; observe the config itself.
{"inline_config", map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.bare", "GIT_CONFIG_VALUE_0": "false"}, []string{"config", "--get", "core.bare"}},
} {
t.Run(tc.name, func(t *testing.T) {
for key, value := range tc.env {
t.Setenv(key, value)
}
t.Setenv("BEADS_DIR", detached)
t.Setenv("BEADS_DB", "")
// Each vector changes the generic query; selected queries keep their own context.
inherited, inheritedErr := gitOutput(filepath.Dir(detached), tc.query...)
selected, err := selectedBeadsGitOutput(filepath.Dir(detached), tc.query...)
if err != nil || (tc.name == "invalid" && inheritedErr == nil) ||
(tc.name != "invalid" && (inheritedErr != nil || inherited == selected)) {
t.Fatalf("routing precondition: inherited=%q (%v), selected=%q (%v)", inherited, inheritedErr, selected, err)
}
for _, check := range []struct{ name, got, want string }{
{"FollowRedirect", FollowRedirect(redirect), stable},
{"FindBeadsDir", FindBeadsDir(), stable},
{"FindDatabasePath", FindDatabasePath(), database},
} {
if !utils.PathsEqual(check.got, check.want) {
t.Errorf("%s = %q, want selected stable path %q", check.name, check.got, check.want)
}
}
})
}
}
func TestSelectedBeadsCanonicalizerFallbacks(t *testing.T) {
t.Chdir(t.TempDir())
for _, name := range []string{"stable_branch", "different_head", "missing_stable"} {
t.Run(name, func(t *testing.T) {
detached, stable, _ := setupDetachedCommitBeadsWorktree(t)
want := detached
switch name {
case "stable_branch":
want = stable
case "different_head":
runGitInDir(t, filepath.Dir(stable), "commit", "--allow-empty", "-m", "Different branch head")
case "missing_stable":
if err := os.Rename(stable, stable+".saved"); err != nil {
t.Fatal(err)
}
}
if got := canonicalizeBeadsDirPath(want); !utils.PathsEqual(got, want) {
t.Errorf("canonical path = %q, want unchanged %q", got, want)
}
})
}
}
func TestResolveBeadsDirForRepoIgnoresInheritedRouting(t *testing.T) {
for _, entry := range os.Environ() {
key := gitenv.EntryKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
}
}
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
t.Setenv(key, t.TempDir())
}
// Production ScrubRouting retains this explicit system-config suppression.
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
targetParent, target := setupRegularWorktreeRepo(t)
decoyParent, decoy := setupRegularWorktreeRepo(t)
want := utils.CanonicalizePath(filepath.Join(targetParent, ".beads"))
for _, dir := range []string{want, filepath.Join(decoyParent, ".beads")} {
if err := os.MkdirAll(dir, 0o750); err != nil {
t.Fatal(err)
}
}
if _, err := os.Stat(filepath.Join(target, ".beads")); !os.IsNotExist(err) {
t.Fatalf("fixture must require common-parent fallback: %v", err)
}
decoyGitDir := runGitInDir(t, decoy, "rev-parse", "--absolute-git-dir")
for _, name := range []string{"decoy", "invalid_git_dir"} {
t.Run(name, func(t *testing.T) {
gitDir := decoyGitDir
if name == "invalid_git_dir" {
gitDir = filepath.Join(t.TempDir(), "missing.git")
}
t.Setenv("GIT_DIR", gitDir)
t.Setenv("GIT_WORK_TREE", decoy)
t.Setenv("GIT_COMMON_DIR", filepath.Join(decoyParent, ".git"))
before := strings.Join(os.Environ(), "\x00")
if got := ResolveBeadsDirForRepo(target); !utils.PathsEqual(got, want) {
t.Errorf("ResolveBeadsDirForRepo() = %q, want target %q", got, want)
}
if strings.Join(os.Environ(), "\x00") != before {
t.Error("resolver changed inherited environment")
}
})
}
}

View file

@ -30,6 +30,7 @@ import (
"sync"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/gitenv"
)
// UserRole represents the user's relationship to a repository.
@ -234,6 +235,11 @@ func getRepoRootFromPath(path string) (string, error) {
// We explicitly set GIT_DIR and GIT_WORK_TREE to ensure git operates on
// the correct repository (the one containing .beads/).
func (rc *RepoContext) GitCmd(ctx context.Context, args ...string) *exec.Cmd {
return rc.gitCmdWithEnv(ctx, os.Environ(), args...)
}
// gitCmdWithEnv applies the existing repository pins after the caller policy.
func (rc *RepoContext) gitCmdWithEnv(ctx context.Context, env []string, args ...string) *exec.Cmd {
gitArgs := append([]string{"-c", "core.hooksPath="}, args...)
cmd := exec.CommandContext(ctx, "git", gitArgs...)
cmd.Dir = rc.RepoRoot
@ -244,7 +250,7 @@ func (rc *RepoContext) GitCmd(ctx context.Context, args ...string) *exec.Cmd {
// Security: Disable git hooks and templates to prevent code execution
// in potentially malicious repositories (SEC-001, SEC-002)
cmd.Env = append(os.Environ(),
cmd.Env = append(env,
"GIT_TEMPLATE_DIR=", // Disable templates
"GIT_DIR="+gitDir, // Ensure git uses the correct .git directory
"GIT_WORK_TREE="+rc.RepoRoot, // Ensure git uses the correct work tree
@ -573,11 +579,12 @@ func (rc *RepoContext) Role() (UserRole, bool) {
return Contributor, true
}
output, err := rc.GitOutput(context.Background(), "config", "--get", "beads.role")
cmd := rc.gitCmdWithEnv(context.Background(), gitenv.ScrubRoutingAndSuppression(os.Environ()), "config", "--get", "beads.role")
output, err := cmd.Output()
if err != nil {
return "", false // Not configured
}
return UserRole(strings.TrimSpace(output)), true
return UserRole(strings.TrimSpace(string(output))), true
}
// IsContributor returns true if user is configured as contributor.

View file

@ -7,9 +7,11 @@ import (
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/gitenv"
)
// TestGetRepoContextForWorkspace_NormalRepo tests context resolution for a normal git repository
@ -1300,3 +1302,98 @@ func initGitRepoWithCommit(dir string) error {
commitCmd.Dir = dir
return commitCmd.Run()
}
func TestRoleIgnoresInheritedGitRouting(t *testing.T) {
for _, entry := range os.Environ() {
key := gitenv.EntryKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
}
}
home, target, decoy := t.TempDir(), t.TempDir(), t.TempDir()
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
t.Setenv(key, home)
}
runGit := func(t *testing.T, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Env = gitenv.ScrubRouting(os.Environ())
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("fixture git %v: %v: %s", args, err, out)
}
}
for _, repo := range []string{target, decoy} {
runGit(t, "-C", repo, "init", "--quiet")
}
runGit(t, "-C", target, "config", "beads.role", "maintainer")
runGit(t, "-C", decoy, "config", "beads.role", "contributor")
t.Chdir(decoy)
rc := &RepoContext{RepoRoot: target} // The caller has already selected this repo.
for _, inline := range []bool{false, true} {
name, generic := "repository", "maintainer"
poison := map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy}
if inline {
name, generic = "inline", "injected-role"
poison = map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "beads.role", "GIT_CONFIG_VALUE_0": generic}
}
t.Run(name, func(t *testing.T) {
for key, value := range poison {
t.Setenv(key, value)
}
if role, ok := rc.Role(); !ok || role != Maintainer {
t.Errorf("Role() = %q, %v; want maintainer, true", role, ok)
}
if out, err := rc.GitOutput(t.Context(), "config", "--get", "beads.role"); err != nil || strings.TrimSpace(out) != generic {
t.Errorf("generic GitOutput = %q, %v; want %q", out, err, generic)
}
for key, value := range poison {
if os.Getenv(key) != value {
t.Errorf("Role changed parent environment %s", key)
}
}
})
}
t.Run("common_dir", func(t *testing.T) {
commonDir := filepath.Join(decoy, ".git")
t.Setenv("GIT_COMMON_DIR", commonDir)
// Unlike GIT_DIR, this key is not overridden by the generic repository pins.
if role, ok := rc.Role(); !ok || role != Maintainer {
t.Errorf("Role() = %q, %v; want maintainer, true", role, ok)
}
if out, err := rc.GitOutput(t.Context(), "config", "--get", "beads.role"); err != nil || strings.TrimSpace(out) != string(Contributor) {
t.Errorf("generic GitOutput = %q, %v; want contributor", out, err)
}
if os.Getenv("GIT_COMMON_DIR") != commonDir {
t.Error("Role changed parent GIT_COMMON_DIR")
}
})
t.Run("live_values", func(t *testing.T) {
for _, value := range []string{"contributor", "invalid", ""} {
runGit(t, "-C", target, "config", "beads.role", value)
if role, ok := rc.Role(); !ok || role != UserRole(value) {
t.Errorf("fresh Role() = %q, %v; want %q, true", role, ok, value)
}
}
})
t.Run("absent_and_global", func(t *testing.T) {
runGit(t, "-C", target, "config", "--unset", "beads.role")
if role, ok := rc.Role(); ok || role != "" {
t.Errorf("absent Role() = %q, %v", role, ok)
}
if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\nrole = contributor\n"), 0o600); err != nil {
t.Fatal(err)
}
if role, ok := rc.Role(); !ok || role != Contributor {
t.Errorf("global Role() = %q, %v", role, ok)
}
})
t.Run("redirected", func(t *testing.T) {
redirected := &RepoContext{RepoRoot: t.TempDir(), IsRedirected: true}
if role, ok := redirected.Role(); !ok || role != Contributor {
t.Errorf("redirected Role() = %q, %v", role, ok)
}
})
}

View file

@ -1031,9 +1031,9 @@ func ResolveExternalProjectPath(projectName string) string {
// 3. git config user.name
// 4. hostname
//
// The Git lookup discards inherited routing overrides, including
// GIT_CONFIG_GLOBAL. Set user.name in the default global config location
// rather than selecting a different file through that environment override.
// The Git lookup discards custom GIT_CONFIG_GLOBAL paths and other routing
// overrides, while retaining explicit config suppression. Set user.name in
// the default global config location when global config is enabled.
func GetIdentity(flagValue string) string {
// 1. Command-line flag takes precedence
if flagValue != "" {

View file

@ -36,6 +36,10 @@ func TestGetIdentityIgnoresInheritedGitRouting(t *testing.T) {
if err := os.WriteFile(poisonConfig, []byte("[user]\n\tname = injected-user\n"), 0o600); err != nil {
t.Fatal(err)
}
hostname, err := os.Hostname()
if err != nil || hostname == "" {
t.Fatalf("hostname fixture: %q, %v", hostname, err)
}
for _, tc := range []struct {
name string
env map[string]string
@ -45,8 +49,11 @@ func TestGetIdentityIgnoresInheritedGitRouting(t *testing.T) {
{name: "repository", env: map[string]string{"GIT_DIR": filepath.Join(decoy, ".git")}, want: "target-user"},
{name: "inline config", env: map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "user.name", "GIT_CONFIG_VALUE_0": "injected-user"}, want: "target-user"},
{name: "global config", env: map[string]string{"GIT_CONFIG_GLOBAL": poisonConfig}, clearLocal: true, want: "home-user"},
{name: "null config suppression", env: map[string]string{"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"}, clearLocal: true, want: hostname},
} {
t.Run(tc.name, func(t *testing.T) {
// Keep each removal case independent of the preceding case.
runConfigProbeGit(t, target, "config", "--local", "user.name", "target-user")
if tc.clearLocal {
runConfigProbeGit(t, target, "config", "--local", "--unset", "user.name")
}

View file

@ -4,10 +4,12 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/spf13/viper"
"github.com/steveyegge/beads/internal/gitenv"
"gopkg.in/yaml.v3"
)
@ -1537,3 +1539,90 @@ func TestMetricsNoticeShownResolvesUserGlobalOnly(t *testing.T) {
}
})
}
// TestCheckSecretKeyGitSafety_RoutedCheckout covers the call site's two
// environment shapes. The guard is fail-open — a probe that cannot answer reads
// as "not tracked" reads as "allow the secret write" — so each shape has to be
// pinned separately: neither probe alone answers both, and the existing tests
// above are all in-tree-repo, which is the one shape that never needed either.
func TestCheckSecretKeyGitSafety_RoutedCheckout(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("routed checkout fixture requires Git")
}
for _, entry := range os.Environ() {
key := gitenv.EntryKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
}
}
runGit := func(t *testing.T, dir string, env []string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir, cmd.Env = dir, env
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("fixture git %v: %v: %s", args, err, out)
}
}
writeConfig := func(t *testing.T, workTree string) string {
t.Helper()
beadsDir := filepath.Join(workTree, ".beads")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatal(err)
}
configPath := filepath.Join(beadsDir, "config.yaml")
if err := os.WriteFile(configPath, []byte("json: false\n"), 0o644); err != nil {
t.Fatal(err)
}
return configPath
}
// The routed layout the scrub-only probe cannot see: the repository lives
// outside the work tree and is reachable only through GIT_DIR/GIT_WORK_TREE,
// so there is no in-tree .git for a scrubbed probe to discover from.
t.Run("legitimate routing refuses a tracked config", func(t *testing.T) {
root := t.TempDir()
gitDir, workTree := filepath.Join(root, "repo.git"), filepath.Join(root, "work")
if err := os.MkdirAll(workTree, 0o755); err != nil {
t.Fatal(err)
}
clean := gitenv.ScrubRoutingAndSuppression(os.Environ())
runGit(t, root, clean, "init", "--quiet", "--bare", gitDir)
configPath := writeConfig(t, workTree)
routed := append(clean, "GIT_DIR="+gitDir, "GIT_WORK_TREE="+workTree)
runGit(t, workTree, routed, "add", "--", ".beads/config.yaml")
t.Setenv("GIT_DIR", gitDir)
t.Setenv("GIT_WORK_TREE", workTree)
err := checkSecretGitTracked(configPath, "linear.api_key")
if err == nil {
t.Fatal("secret write allowed into a tracked config: the guard lost its only view of the repository")
}
if !strings.Contains(err.Error(), "refusing to write secret key") {
t.Fatalf("expected a refusal, got: %v", err)
}
})
// The poisoned layout the inherited probe cannot see. Pinned alongside so
// the fallback above cannot be widened into a way around the scrub.
t.Run("poisoned routing still refuses a tracked config", func(t *testing.T) {
root, decoy := t.TempDir(), t.TempDir()
clean := gitenv.ScrubRoutingAndSuppression(os.Environ())
runGit(t, root, clean, "init", "--quiet")
runGit(t, decoy, clean, "init", "--quiet")
configPath := writeConfig(t, root)
runGit(t, root, clean, "add", "--", ".beads/config.yaml")
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
t.Setenv("GIT_WORK_TREE", decoy)
err := checkSecretGitTracked(configPath, "linear.api_key")
if err == nil {
t.Fatal("secret write allowed into a tracked config: an inherited GIT_DIR hid the file behind a decoy repository")
}
if !strings.Contains(err.Error(), "refusing to write secret key") {
t.Fatalf("expected a refusal, got: %v", err)
}
})
}

View file

@ -83,26 +83,82 @@ func ScrubRouting(env []string) []string {
// ScrubRoutingForOS removes Git routing entries using goos environment-key
// semantics. It preserves non-routing controls such as GIT_OPTIONAL_LOCKS and
// GIT_NO_REPLACE_OBJECTS.
// GIT_NO_REPLACE_OBJECTS, plus explicit system/global config suppression.
// Custom config paths and inline values still lose their routing authority.
//
// Suppression cannot redirect a read, but it can blind one. Callers whose
// result carries authority must use ScrubRoutingAndSuppression instead.
func ScrubRoutingForOS(env []string, goos string) []string {
return scrubRoutingForOS(env, goos, true)
}
// ScrubRoutingAndSuppression removes Git routing entries using the current
// host's environment-key semantics, including the explicit config suppression
// that ScrubRouting deliberately preserves.
func ScrubRoutingAndSuppression(env []string) []string {
return ScrubRoutingAndSuppressionForOS(env, runtime.GOOS)
}
// ScrubRoutingAndSuppressionForOS is ScrubRoutingForOS without the config
// suppression exemption: GIT_CONFIG_GLOBAL=/dev/null, GIT_CONFIG_SYSTEM=/dev/null
// and GIT_CONFIG_NOSYSTEM lose their effect along with every other routing key.
//
// Use it wherever a *missing* config value grants privilege rather than merely
// losing a preference. Suppression is harmless for a command that only reports
// what Git sees, but on an authority lookup such as beads.role an inherited
// GIT_CONFIG_NOSYSTEM=1 lets a caller blind the read, and a permissive
// miss-handler (routing.detectFromURL defaults to maintainer) converts that
// blinding into an escalation. Keeping reads and writes of the same key on this
// boundary also stops them from disagreeing about which config file they mean.
func ScrubRoutingAndSuppressionForOS(env []string, goos string) []string {
return scrubRoutingForOS(env, goos, false)
}
func scrubRoutingForOS(env []string, goos string, keepSuppression bool) []string {
cleaned := make([]string, 0, len(env))
for _, entry := range env {
if IsRoutingKeyForOS(EntryKey(entry), goos) {
continue
if !keepSuppression || !isConfigSuppressionControl(entry, goos) {
continue
}
}
cleaned = append(cleaned, entry)
}
return cleaned
}
// isConfigSuppressionControl recognizes the config controls that cannot
// redirect Git at a file of the caller's choosing. IsRoutingKeyForOS stays
// conservative: a key alone cannot distinguish null suppression from a custom
// file that can redirect selected operations.
//
// GIT_CONFIG_NOSYSTEM is preserved value-blind — unlike the null-path forms
// below there is no value it can take that names a file, so Git is left to
// interpret its Boolean, including the "false"/"0" spellings that re-enable
// system config and any invalid value it should report itself.
func isConfigSuppressionControl(entry, goos string) bool {
key := execenv.KeyIdentityForOS(EntryKey(entry), goos)
_, value, assigned := strings.Cut(entry, "=")
if !assigned {
return false
}
switch key {
case execenv.KeyIdentityForOS("GIT_CONFIG_NOSYSTEM", goos):
return true
case execenv.KeyIdentityForOS("GIT_CONFIG_GLOBAL", goos), execenv.KeyIdentityForOS("GIT_CONFIG_SYSTEM", goos):
return value == "/dev/null" || (goos == "windows" && strings.EqualFold(value, "NUL"))
}
return false
}
// ClearRouting permanently removes Git routing entries from the current
// process. CLI callers use it as a command-lifetime authority boundary. It
// reports whether any entry was removed.
// retains the same config suppression as ScrubRouting and reports any removal.
func ClearRouting() (bool, error) {
removed := false
for _, entry := range os.Environ() {
key := EntryKey(entry)
if !IsRoutingKeyForOS(key, runtime.GOOS) {
if !IsRoutingKeyForOS(key, runtime.GOOS) || isConfigSuppressionControl(entry, runtime.GOOS) {
continue
}
if err := os.Unsetenv(key); err != nil {

View file

@ -2,8 +2,11 @@ package gitenv
import (
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
)
@ -47,6 +50,130 @@ func TestScrubRoutingForOSUsesHostKeySemantics(t *testing.T) {
}
}
func TestScrubRoutingPreservesConfigSuppression(t *testing.T) {
for _, goos := range []string{"linux", "windows"} {
for _, tc := range []struct {
entry string
linux, windows bool
}{
{"GIT_CONFIG_NOSYSTEM=1", true, true},
{"GIT_CONFIG_NOSYSTEM=false", true, true},
{"GIT_CONFIG_NOSYSTEM=invalid", true, true},
{"GIT_CONFIG_NOSYSTEM", false, false},
{"GIT_CONFIG_GLOBAL=/dev/null", true, true},
{"GIT_CONFIG_SYSTEM=/dev/null", true, true},
{"GIT_CONFIG_GLOBAL=nUl", false, true},
{"git_config_system=NUL", true, true}, // Lowercase is a distinct POSIX key.
{"GIT_CONFIG_GLOBAL=", false, false},
{"GIT_CONFIG_SYSTEM=custom.conf", false, false},
{"GIT_CONFIG_GLOBAL=custom.conf", false, false},
{"GIT_CONFIG_COUNT=1", false, false},
} {
t.Run(goos+"/"+tc.entry, func(t *testing.T) {
input := []string{tc.entry, "GIT_DIR=decoy", "KEEP=value"}
want := []string{"KEEP=value"}
if (goos == "linux" && tc.linux) || (goos == "windows" && tc.windows) {
want = append([]string{tc.entry}, want...)
}
if got := ScrubRoutingForOS(input, goos); !reflect.DeepEqual(got, want) || input[0] != tc.entry {
t.Fatalf("filtered environment = %q, want %q; input %q", got, want, input)
}
})
}
}
}
// TestScrubRoutingAndSuppressionDropsSuppression is the inverse of the table
// above: every entry ScrubRouting preserves as suppression must lose its effect
// on the authority boundary, because a caller who can blind an authority lookup
// can steer its miss-handler. Non-routing controls still survive both scrubs.
func TestScrubRoutingAndSuppressionDropsSuppression(t *testing.T) {
for _, goos := range []string{"linux", "windows"} {
for _, entry := range []string{
"GIT_CONFIG_NOSYSTEM=1",
"GIT_CONFIG_NOSYSTEM=false",
"GIT_CONFIG_NOSYSTEM=invalid",
"GIT_CONFIG_GLOBAL=/dev/null",
"GIT_CONFIG_SYSTEM=/dev/null",
"GIT_CONFIG_GLOBAL=custom.conf",
"GIT_CONFIG_COUNT=1",
"GIT_DIR=decoy",
} {
t.Run(goos+"/"+entry, func(t *testing.T) {
input := []string{entry, "GIT_OPTIONAL_LOCKS=1", "KEEP=value"}
want := []string{"GIT_OPTIONAL_LOCKS=1", "KEEP=value"}
// Lowercase POSIX keys are distinct names, so only the
// case-insensitive host drops a folded spelling.
if goos == "linux" && strings.HasPrefix(entry, "git_") {
want = append([]string{entry}, want...)
}
got := ScrubRoutingAndSuppressionForOS(input, goos)
if !reflect.DeepEqual(got, want) || input[0] != entry {
t.Fatalf("filtered environment = %q, want %q; input %q", got, want, input)
}
// The suppression-preserving scrub must be unaffected.
if kept := ScrubRoutingForOS(input, goos); len(kept) < len(got) {
t.Fatalf("ScrubRoutingForOS() = %q dropped more than the authority scrub %q", kept, got)
}
})
}
}
}
func TestScrubRoutingGitConfigSuppressionEffects(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("real Git config isolation test requires Git")
}
for _, entry := range os.Environ() {
key := EntryKey(entry)
if IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
}
}
home := t.TempDir()
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
t.Setenv(key, home)
}
custom := filepath.Join(home, "custom.config")
for path, value := range map[string]string{filepath.Join(home, ".gitconfig"): "home", custom: "custom"} {
if err := os.WriteFile(path, []byte("[beads-isolation-fixture]\n\tvalue = "+value+"\n"), 0600); err != nil {
t.Fatal(err)
}
}
query := func(t *testing.T, env []string, want string) {
t.Helper()
cmd := exec.Command("git", "config", "--get", "beads-isolation-fixture.value")
cmd.Dir, cmd.Env = home, env
out, err := cmd.Output()
if want == "" {
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 || len(out) != 0 {
t.Fatalf("suppressed config = %q (%v), want absence", out, err)
}
} else if err != nil || strings.TrimSpace(string(out)) != want {
t.Fatalf("config value = %q (%v), want %q", out, err, want)
}
}
base := ScrubRouting(os.Environ())
t.Run("global_null", func(t *testing.T) {
// Pin a null system file separately so the HOME observation is owned.
query(t, append(base, "GIT_CONFIG_SYSTEM="+os.DevNull), "home")
query(t, append(ScrubRouting(append(base, "GIT_CONFIG_GLOBAL="+os.DevNull)), "GIT_CONFIG_SYSTEM="+os.DevNull), "")
})
t.Run("custom_global_still_rejected", func(t *testing.T) {
query(t, append(base, "GIT_CONFIG_GLOBAL="+custom, "GIT_CONFIG_SYSTEM="+os.DevNull), "custom")
query(t, append(ScrubRouting(append(base, "GIT_CONFIG_GLOBAL="+custom)), "GIT_CONFIG_SYSTEM="+os.DevNull), "home")
})
t.Run("nosystem", func(t *testing.T) {
// An owned system-file override models system config after filtering;
// only NOSYSTEM's preservation is under test in this real Git query.
query(t, append(base, "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_SYSTEM="+custom, "GIT_CONFIG_NOSYSTEM=0"), "custom")
query(t, append(ScrubRouting(append(base, "GIT_CONFIG_NOSYSTEM=1")), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_SYSTEM="+custom), "")
})
}
func TestRoutingUnicodeKeysFollowSubprocessIdentity(t *testing.T) {
for _, goos := range []string{"linux", "windows"} {
for _, tc := range []struct {
@ -156,6 +283,9 @@ func TestClearRoutingPreservesNonRoutingGitControls(t *testing.T) {
t.Setenv("GIT_CONFIG_COUNT", "1")
t.Setenv("GIT_OPTIONAL_LOCKS", "1")
t.Setenv("GIT_NO_REPLACE_OBJECTS", "1")
for key, value := range map[string]string{"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.DevNull, "GIT_CONFIG_SYSTEM": os.DevNull} {
t.Setenv(key, value)
}
removed, err := ClearRouting()
if err != nil {
@ -174,4 +304,9 @@ func TestClearRoutingPreservesNonRoutingGitControls(t *testing.T) {
t.Fatalf("%s = %q, want 1", key, value)
}
}
for key, want := range map[string]string{"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.DevNull, "GIT_CONFIG_SYSTEM": os.DevNull} {
if got := os.Getenv(key); got != want {
t.Errorf("config suppression %s = %q, want %q", key, got, want)
}
}
}

View file

@ -9,10 +9,15 @@ import (
"strings"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/gitenv"
)
// Role detection is an authority lookup, so it also discards inherited config
// suppression: detectFromURL below answers a missed read with Maintainer, which
// would let a caller escalate by blinding the lookup rather than forging it.
var gitCommandRunner = func(repoPath string, args ...string) ([]byte, error) {
cmd := exec.Command("git", args...)
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
if repoPath != "" {
cmd.Dir = repoPath
}

View file

@ -4,12 +4,15 @@ import (
"errors"
"io"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/gitenv"
)
func TestDetermineTargetRepo(t *testing.T) {
@ -461,3 +464,143 @@ func TestDetectUserRole_JJSecondaryWorkspace_NonCwdRepoPath(t *testing.T) {
t.Errorf("expected no role-not-configured warning, got stderr:\n%s", stderr)
}
}
func TestDetectUserRoleIgnoresInheritedGitRouting(t *testing.T) {
for _, entry := range os.Environ() {
key := gitenv.EntryKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
}
}
t.Chdir(t.TempDir()) // The explicit target must also work outside CWD.
runGit := func(t *testing.T, repo string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = repo
cmd.Env = gitenv.ScrubRouting(os.Environ())
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("fixture git %v: %v: %s", args, err, out)
}
}
for _, tc := range []struct {
name, role, global string
inline, warning bool
want UserRole
}{
{"repository", "maintainer", "", false, false, Maintainer},
{"inline", "maintainer", "", true, false, Maintainer},
{"missing_remote", "", "", false, true, Contributor},
{"invalid_remote", "invalid", "", false, true, Contributor},
{"default_global", "", "maintainer", true, false, Maintainer},
} {
t.Run(tc.name, func(t *testing.T) {
home, target, decoy := t.TempDir(), t.TempDir(), t.TempDir()
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
t.Setenv(key, home)
}
if tc.global != "" {
if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\nrole = "+tc.global+"\n"), 0o600); err != nil {
t.Fatal(err)
}
}
for _, repo := range []string{target, decoy} {
runGit(t, repo, "init", "--quiet")
}
runGit(t, decoy, "config", "beads.role", "contributor")
runGit(t, decoy, "remote", "add", "origin", "git@example.invalid:owner/decoy.git")
runGit(t, target, "remote", "add", "origin", "https://example.invalid/owner/target.git")
if tc.role != "" {
runGit(t, target, "config", "beads.role", tc.role)
}
poison := map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy}
if tc.inline {
poison = map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "beads.role", "GIT_CONFIG_VALUE_0": "contributor"}
}
for key, value := range poison {
t.Setenv(key, value)
}
var got UserRole
var err error
stderr := captureStderr(t, func() { got, err = DetectUserRole(target) })
if err != nil || got != tc.want {
t.Errorf("DetectUserRole(target) = %q, %v; want %q", got, err, tc.want)
}
if strings.Contains(stderr, "beads.role not configured") != tc.warning {
t.Errorf("fallback warning = %q; want warning=%v", stderr, tc.warning)
}
for key, value := range poison {
if os.Getenv(key) != value {
t.Errorf("reader changed parent environment %s", key)
}
}
})
}
}
// TestDetectUserRoleIgnoresInheritedConfigSuppression is the deny-direction
// counterpart to the test above. Injecting a role is not the only way to steer
// role detection: an inherited config-suppression entry blinds the lookup
// instead, and DetectUserRole answers a miss with detectFromURL, whose
// no-remote arm returns Maintainer. So the reader must discard suppression too,
// not just redirects.
//
// Only the global-file vector is observable end to end: repository config is
// never suppressed by these variables, and a system file cannot be planted
// hermetically because GIT_CONFIG_SYSTEM=<path> is itself scrubbed. The
// GIT_CONFIG_NOSYSTEM and GIT_CONFIG_SYSTEM forms are pinned one level down, in
// gitenv.TestScrubRoutingAndSuppressionDropsSuppression.
func TestDetectUserRoleIgnoresInheritedConfigSuppression(t *testing.T) {
for _, entry := range os.Environ() {
key := gitenv.EntryKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
}
}
t.Chdir(t.TempDir())
home, target := t.TempDir(), t.TempDir()
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
t.Setenv(key, home)
}
if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\nrole = contributor\n"), 0o600); err != nil {
t.Fatal(err)
}
// No local role and no origin: the only arms left after a blinded read are
// detectFromURL's permissive ones, so an escalation would be visible.
initCmd := exec.Command("git", "init", "--quiet")
initCmd.Dir = target
initCmd.Env = gitenv.ScrubRouting(os.Environ())
if out, err := initCmd.CombinedOutput(); err != nil {
t.Fatalf("fixture git init: %v: %s", err, out)
}
for _, tc := range []struct {
name, blind string
}{
// Fixture guard: without blinding the global role must be readable at
// all, otherwise every case below would pass for the wrong reason.
{"unblinded", ""},
{"global_null", os.DevNull},
} {
t.Run(tc.name, func(t *testing.T) {
if tc.blind != "" {
t.Setenv("GIT_CONFIG_GLOBAL", tc.blind)
}
var got UserRole
var err error
captureStderr(t, func() { got, err = DetectUserRole(target) })
if err != nil {
t.Fatalf("DetectUserRole(target) error: %v", err)
}
if got != Contributor {
t.Errorf("DetectUserRole(target) = %q, want %q: a blinded role read must not escalate", got, Contributor)
}
})
}
}

View file

@ -76,7 +76,11 @@ type CommitInitArtifactsResult struct {
DidCommit bool
}
const beadsRoleConfigKey = "beads.role"
// BeadsRoleConfigKey is the git config key that carries role authority.
// It is exported because the GitRepository adapters select the strict
// role-authority environment on this key, so the two sides must not drift into
// separate spellings of one contract.
const BeadsRoleConfigKey = "beads.role"
func NewGitUseCase(workDir string, repo GitRepository) GitUseCase {
return &gitUseCaseImpl{workDir: workDir, repo: repo}
@ -149,14 +153,14 @@ func (u *gitUseCaseImpl) DetectFork(ctx context.Context) (bool, string, error) {
}
func (u *gitUseCaseImpl) BeadsRole(ctx context.Context) (string, bool, error) {
return u.repo.GetConfig(ctx, beadsRoleConfigKey)
return u.repo.GetConfig(ctx, BeadsRoleConfigKey)
}
func (u *gitUseCaseImpl) SetBeadsRole(ctx context.Context, role string) error {
if role == "" {
return fmt.Errorf("SetBeadsRole: role must not be empty")
}
return u.repo.SetConfig(ctx, beadsRoleConfigKey, role)
return u.repo.SetConfig(ctx, BeadsRoleConfigKey, role)
}
func (u *gitUseCaseImpl) HasAnyRemotes(ctx context.Context) bool {

View file

@ -21,6 +21,8 @@ func NewGitRepository(workDir string) domain.GitRepository {
// NewInitGitRepository binds init artifact operations to the selected workDir.
// The generic constructor retains inherited routing for its existing callers.
// beads.role reads and writes re-scrub this captured environment for config
// suppression as well; see roleAuthorityEnv for why that is not optional here.
func NewInitGitRepository(workDir string) domain.GitRepository {
return &gitRepositoryImpl{workDir: workDir, env: gitenv.ScrubRouting(os.Environ())}
}
@ -102,13 +104,33 @@ func (r *gitRepositoryImpl) Init(ctx context.Context) error {
return nil
}
// roleAuthorityEnv returns the environment for a beads.role read or write.
// The role grants privilege, so this boundary drops the explicit config
// suppression that ScrubRouting deliberately preserves: an inherited
// GIT_CONFIG_GLOBAL=/dev/null blinds the lookup, and the proxied init tail
// answers a missing role by persisting "maintainer" into repository-local
// config, where it then outranks the global value for every later read.
//
// The strict scrub applies to whichever environment this repository already
// carries, not to os.Environ(), so a captured environment keeps its own HOME
// and loses only the suppression entries. Testing r.env for nil instead would
// leave the arm dead on the one production role path, which always arrives
// through NewInitGitRepository and therefore always carries a captured env.
func (r *gitRepositoryImpl) roleAuthorityEnv() []string {
env := r.env
if env == nil {
env = os.Environ()
}
return gitenv.ScrubRoutingAndSuppression(env)
}
func (r *gitRepositoryImpl) GetConfig(ctx context.Context, key string) (string, bool, error) {
if key == "" {
return "", false, fmt.Errorf("git: GetConfig: key must not be empty")
}
cmd := r.gitCmd(ctx, "config", "--get", key)
if key == "beads.role" && r.env == nil {
cmd.Env = gitenv.ScrubRouting(os.Environ())
if key == domain.BeadsRoleConfigKey {
cmd.Env = r.roleAuthorityEnv()
}
out, err := cmd.Output()
if err != nil {
@ -134,8 +156,8 @@ func (r *gitRepositoryImpl) SetConfig(ctx context.Context, key, value string) er
return fmt.Errorf("git: SetConfig: key must not be empty")
}
cmd := r.gitCmd(ctx, "config", key, value)
if key == "beads.role" && r.env == nil {
cmd.Env = gitenv.ScrubRouting(os.Environ())
if key == domain.BeadsRoleConfigKey {
cmd.Env = r.roleAuthorityEnv()
}
out, err := cmd.CombinedOutput()
if err != nil {

View file

@ -72,14 +72,17 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() {
original, err := os.ReadFile(configPath)
s.Require().NoError(err)
for _, tc := range []struct {
name, key string
exitCode int
name, key string
exitCode int
roleReadFails bool
}{
{"malformed_config", "beads.role", 128},
{"invalid_key", "invalid", 1},
// beads.role reads now scrub GIT_CONFIG* routing, so a routing poison can
// only reach a key that is not role-scoped.
{"invalid_routing_boolean", "test.marker", 128},
{"malformed_config", "beads.role", 128, true},
{"invalid_key", "invalid", 1, false},
// A beads.role read scrubs inherited config suppression, so a bad
// GIT_CONFIG_NOSYSTEM value never reaches that one key. Read a key that
// still inherits it, so the env-borne failure stays covered, and pin the
// role read's immunity below rather than dropping the case.
{"invalid_routing_boolean", "core.bare", 128, false},
} {
s.Run(tc.name, func() {
switch tc.name {
@ -104,10 +107,14 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() {
diagnostic := strings.TrimSpace(string(exitErr.Stderr))
s.Require().NotEmpty(diagnostic)
s.Contains(err.Error(), diagnostic)
if tc.name == "malformed_config" {
if tc.roleReadFails {
_, _, roleErr := domain.NewGitUseCase(s.tmpDir, s.repo).BeadsRole(s.Ctx())
s.Require().Error(roleErr)
s.ErrorAs(roleErr, &exitErr)
} else if tc.name == "invalid_routing_boolean" {
_, found, roleErr := domain.NewGitUseCase(s.tmpDir, s.repo).BeadsRole(s.Ctx())
s.Require().NoError(roleErr)
s.False(found)
}
if tc.name == "invalid_routing_boolean" {
// The same poison that fails the read above cannot reach beads.role,
@ -467,9 +474,12 @@ func TestInitGitRepositoryUsesSelectedDirectory(t *testing.T) {
t.Setenv(key, changedHome)
}
role, found, err := inherited.GetConfig(t.Context(), "beads.role")
// The generic reader runs under the caller's current environment, so the
// broken HOME config surfaces as a preserved read failure, not absence.
// changedHome is the only HOME here holding a .gitconfig, so Git's
// refusal to parse that file is what proves the generic reader used
// the current caller environment rather than a captured one. The
// reader surfaces such read failures instead of reporting absence.
require.Error(t, err, "generic role reads still use the current caller environment")
require.ErrorContains(t, err, ".gitconfig")
require.False(t, found)
require.Empty(t, role)
require.Error(t, inherited.SetConfig(t.Context(), "beads.role", "decoy"))
@ -482,3 +492,59 @@ func TestInitGitRepositoryUsesSelectedDirectory(t *testing.T) {
})
}
}
// TestInitGitRepositoryRoleIgnoresInheritedConfigSuppression pins the role
// boundary on the environment the production path actually carries. cmd/bd's
// proxied init tail always rebinds the use case to NewInitGitRepository
// (cmd/bd/init_proxied_server.go), so the *captured* environment — not
// os.Environ() — is the one a beads.role lookup has to be strict about. An
// inherited GIT_CONFIG_GLOBAL=/dev/null that survives into that capture blinds
// the read, and the tail answers a missing role by writing "maintainer" into
// repository-local config, where it outranks the global value from then on. A
// guard keyed on the environment's provenance would therefore be dead exactly
// where the escalation happens.
//
// Only the global-file vector is observable end to end here, for the reasons
// internal/routing's counterpart test records: repository config is never
// suppressed by these variables, and GIT_CONFIG_SYSTEM=<path> is itself
// scrubbed. The remaining forms are pinned in gitenv's suppression table.
func TestInitGitRepositoryRoleIgnoresInheritedConfigSuppression(t *testing.T) {
for _, entry := range os.Environ() {
key := gitenv.EntryKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, "")
require.NoError(t, os.Unsetenv(key))
}
}
home, target := t.TempDir(), t.TempDir()
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
t.Setenv(key, home)
}
require.NoError(t, os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\n\trole = contributor\n"), 0600))
// No local role in the target: the global file is the only place the answer
// can come from, so blinding it is visible as a miss.
initCmd := exec.Command("git", "init", "--quiet")
initCmd.Dir, initCmd.Env = target, gitenv.ScrubRouting(os.Environ())
out, err := initCmd.CombinedOutput()
require.NoError(t, err, "fixture git init: %s", out)
for _, tc := range []struct{ name, blind string }{
// Fixture guard: the global role must be readable at all, otherwise the
// blinded case below would pass for the wrong reason.
{"unblinded", ""},
{"global_null", os.DevNull},
} {
t.Run(tc.name, func(t *testing.T) {
if tc.blind != "" {
t.Setenv("GIT_CONFIG_GLOBAL", tc.blind)
}
// Constructed inside the subtest: the constructor captures the
// environment, so the suppression entry has to be present first.
useCase := domain.NewGitUseCase(target, NewInitGitRepository(target))
role, found, err := useCase.BeadsRole(t.Context())
require.NoError(t, err)
require.True(t, found, "a blinded role read makes the init tail persist a maintainer default")
require.Equal(t, "contributor", role)
})
}
}

View file

@ -35,6 +35,8 @@ required=(
TestScrubEnvDoesNotEqualFoldUnicodeKeys
TestStderrDirectedWindowsLeadingSlashIsFileTarget
TestScrubRoutingUsesHostKeySemantics
TestScrubRoutingPreservesConfigSuppression
TestScrubRoutingAndSuppressionDropsSuppression
)
for name in "${required[@]}"; do
count=$(grep -Ec "^[[:space:]]*--- PASS: $name \\(" "$log" || true)