fix(init,config): maintainer fixup for #6464
Pre-review CI repair:
- Annotate #nosec G702 on the selected hooks-path git invocation. No shell
is involved, every path is passed as its own argv element, and both values
reach that line absolute via resolveInitHooksContext.
Review iteration 1, blocking:
- internal/config: give the secret-config guard the inherited-env fallback
that the structurally identical hook guard in cmd/bd/hooks.go already has.
isGitTracked is the fail-open half of "refuse to write a secret key into a
git-tracked config.yaml", and the scrub alone narrowed it to upward
discovery from the config file's directory: under a detached work tree
(GIT_DIR + GIT_WORK_TREE with no in-tree .git) the probe reported
"untracked" and the secret was written into the tracked file. Probe the
scrubbed environment first so inherited routing cannot hide a tracked
file, then the inherited one; either probe reporting the path as tracked
refuses the write. Adds the legitimate-routing subtest that the
poisoned-routing matrix could not express.
- cmd/bd/config.go: the new comment claimed "All role commands ignore
inherited Git routing". Only the writers were hardened -
routing.DetectUserRole, beads.RepoContext.Role, `bd config show` and
`bd doctor` still resolve beads.role through the inherited environment, so
`bd config get beads.role` and `bd config show` can disagree under one
environment. Narrow the comment to the four verbs it covers; widening the
boundary to the readers is a separate change.
Review iteration 1, non-blocking:
- cmd/bd/worktree_cmd.go: disclose that ClearRouting unsets the variables on
the bd process itself, and state what clearing the discovery-scope
controls does to repository selection. The comment previously claimed the
opposite of what the init path's own note admits.
- cmd/bd/init_proxied_server.go: drop isRoleGitRepo. With workDir set, gitUC
is NewInitGitRepository(workDir), whose IsGitRepo runs the same
`git rev-parse --git-dir` with the same Dir and scrubbed env; with workDir
empty the helper returned its fallback. It was isRepo in both arms, plus a
second git subprocess per `bd init --proxied`.
- cmd/bd/doctor/gitignore.go: omit the leading blank line when creating a
fresh .gitignore, matching the two sibling writers this PR already
conditionalized in cff94aa43.
Review iteration 2, non-blocking:
- cmd/bd/worktree_cmd.go: iteration 1's own rewrite lumped
GIT_DISCOVERY_ACROSS_FILESYSTEM in with GIT_CEILING_DIRECTORIES as
"removes an inherited stop". That is backwards. git(1) documents that
discovery "does not cross filesystem boundaries" by default and that this
variable "can be set to true to tell Git not to stop at filesystem
boundaries" - it only ever permits, so clearing it *adds* a stop and
narrows the walk. Split the clause per control: the ceiling widens,
GIT_DISCOVERY_ACROSS_FILESYSTEM narrows (a repository reachable only
across a mount point is no longer found by any `bd worktree` verb, with no
opt-out), and ClearRouting's GIT_CONFIG prefix match drops the whole
GIT_CONFIG* family for the command's lifetime rather than for one child
probe. This comment is the only in-tree assertion about the variable's
direction; export_auto.go:1083-1085 groups the two without claiming one.
- cmd/bd/config.go: "bd config's own beads.role reads and writes" covered
`bd config show`, which the very next sentence lists as an exception. Name
the four verbs that do scrub (get/set/unset/set-many, at config.go:209,
:355, :609 and :902 - the only four git invocations in the file).
- internal/config: make the guard's fail-open default unspellable. The
mirrored helper took `envs ...[]string`, so a future zero-probe call would
fall through to "untracked" and write the secret with no compiler
backstop. Promote the first environment to a required parameter. The tail
stays variadic rather than matching the twin's fixed (clean, inherited)
arity because the fallback's fixture guard has to probe one environment
alone, and exec treats a nil Env as "inherit the current process" rather
than as a disabled probe.
Pre-approval CI repair:
- Annotate the four gosec taint findings this PR newly introduces in package
cmd/bd: G704 on the two connectivity probes in dolt.go, G702 on the
staged-deletion probe in hooks.go and on the ls-remote probe in
sync_git.go. None of the four is reported by the PR lane, whose lint is
scoped to the diff (only-new-issues / --new-from-merge-base), and all four
sit on lines this PR does not otherwise touch - but main.yml runs the same
wrapper with BD_LINT_NEW_FROM_MERGE_BASE unset and sweeps the whole tree,
so merging as-is turns main's Lint and PR Lint jobs red. Measured
whole-tree at pr.yml's pinned golangci-lint v2.10.1 with
--build-tags=gms_pure_go: origin/main 0 issues, this head 4, this head
with the annotations 0. The findings are taint over-approximation rather
than new exposure: gosec's analysis is not field-sensitive, so routing
config discovery through env-derived paths marks the whole store value
tainted and every remote URL read back off it inherits that. Each
annotation states why its own call site is safe; the additions are
comment-only, with no deletions and no behaviour change.
The hooks.go annotation sits on the isExportFileStagedForDeletion
declaration rather than on the exec.Command call. main has since rewritten
that body to address the export file through nearestExistingDir +
filepath.Rel, so a call-site comment both conflicted with the merge and
described an argument the merged body no longer builds. On the declaration
it merges cleanly and its justification holds for either body.
Pre-approval base refresh (rebased onto 511849496):
- Reconcile this PR with gastownhall/beads#6477, which landed on main after
this branch was first rebased and which changes the same reader. The two
changes collide in both directions, and neither side's CI can see it: the
PR lane builds this branch against its own base, main's lane never has the
PR, and only the merged tree fails.
- #6477 direction: its new subtest
TestConfig_ReadFailuresAreNotMissing/invalid_routing_boolean poisons
GIT_CONFIG_NOSYSTEM and expects the beads.role read to exit 128. This PR
scrubs GIT_CONFIG* for exactly that key, so git never sees the poison and
the read succeeds. Replaced that row with
TestConfig_BeadsRoleScrubsInheritedRoutingEnv, which pins both halves of
the new contract: beads.role reads through the scrub, and a key outside it
(user.name) still surfaces the same poison as an exit-128 read error
rather than as an absent key. #6477's general guarantee is untouched -
malformed_config still proves it for beads.role through the repository's
own config file.
- Opposite direction: this PR's own
TestInitGitRepositoryUsesSelectedDirectory/captured_home asserted
require.NoError on a generic-constructor read, commented "The existing
reader maps Git exit errors to absence" - the precise behaviour #6477
removed. Expect the propagated exit error instead. The test's intent is
unchanged and in fact better served: only the current caller environment
can see the changed HOME's broken .gitconfig, so that error is itself the
proof that generic role reads still use it.
This commit is contained in:
parent
84f76b6b2b
commit
0fe9369446
12 changed files with 231 additions and 35 deletions
|
|
@ -199,7 +199,12 @@ var configSetCmd = &cobra.Command{
|
|||
if !validRoles[value] {
|
||||
return HandleError("invalid role %q (valid values: maintainer, contributor)", value)
|
||||
}
|
||||
// All role commands ignore inherited Git routing, including GIT_CONFIG_GLOBAL.
|
||||
// bd config get/set/unset/set-many beads.role ignore inherited Git
|
||||
// routing, including GIT_CONFIG_GLOBAL, so the value lands in the
|
||||
// repository this command selected. The scope is those four verbs,
|
||||
// not role resolution as a whole: routing.DetectUserRole,
|
||||
// beads.RepoContext.Role, `bd config show` and `bd doctor` still
|
||||
// resolve beads.role through the inherited environment.
|
||||
cmd := exec.Command("git", "config", "beads.role", value) //nolint:gosec // value is validated against allowlist above
|
||||
cmd.Env = gitenv.ScrubRouting(os.Environ())
|
||||
if err := cmd.Run(); err != nil {
|
||||
|
|
|
|||
|
|
@ -788,8 +788,13 @@ func EnsureProjectGitignore(repoPath string) error {
|
|||
return nil // All patterns already present
|
||||
}
|
||||
|
||||
lines := append([]string{"", ProjectGitignoreHeader}, toAdd...)
|
||||
newContent := gitignore.AppendLines(content, lines)
|
||||
// A fresh .gitignore must not start with a blank line; the separator only
|
||||
// belongs between existing content and the appended block.
|
||||
lines := []string{ProjectGitignoreHeader}
|
||||
if len(content) > 0 {
|
||||
lines = []string{"", ProjectGitignoreHeader}
|
||||
}
|
||||
newContent := gitignore.AppendLines(content, append(lines, toAdd...))
|
||||
|
||||
// #nosec G306 -- gitignore needs to be readable by git and collaborators
|
||||
if err := os.WriteFile(gitignorePath, newContent, 0644); err != nil {
|
||||
|
|
|
|||
|
|
@ -1924,6 +1924,36 @@ func TestEnsureProjectGitignore_CreatesFile(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestEnsureProjectGitignore_LeadingSeparatorOnlyAfterExistingContent(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
existing string
|
||||
want string
|
||||
}{
|
||||
{name: "fresh file", existing: "", want: ProjectGitignoreHeader + "\n"},
|
||||
{name: "existing content", existing: "build/\n", want: "build/\n\n" + ProjectGitignoreHeader + "\n"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
if tc.existing != "" {
|
||||
if err := os.WriteFile(".gitignore", []byte(tc.existing), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := EnsureProjectGitignore("."); err != nil {
|
||||
t.Fatalf("EnsureProjectGitignore() error = %v", err)
|
||||
}
|
||||
content, err := os.ReadFile(".gitignore")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := string(content); !strings.HasPrefix(got, tc.want) {
|
||||
t.Errorf(".gitignore starts with %q, want prefix %q", got[:min(len(got), len(tc.want)+16)], tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureProjectGitignore_AppendsToExisting(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
oldDir, err := os.Getwd()
|
||||
|
|
@ -1968,7 +1998,11 @@ func TestEnsureProjectGitignore_AppendsToExisting(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestEnsureProjectGitignore_PreservesAppendLineEndings(t *testing.T) {
|
||||
lfBlock := "\n" + ProjectGitignoreHeader + "\n" + strings.Join(ProjectGitignorePatterns, "\n") + "\n"
|
||||
// freshBlock is the block with no leading separator: an empty file has no
|
||||
// existing content to separate from, matching fs.WriteProjectGitignore and
|
||||
// the exclude writer.
|
||||
freshBlock := ProjectGitignoreHeader + "\n" + strings.Join(ProjectGitignorePatterns, "\n") + "\n"
|
||||
lfBlock := "\n" + freshBlock
|
||||
crlfBlock := "\r\n" + ProjectGitignoreHeader + "\r\n" + strings.Join(ProjectGitignorePatterns, "\r\n") + "\r\n"
|
||||
partial := ProjectGitignoreHeader + "\r\n" + ProjectGitignorePatterns[0] + "\r\n"
|
||||
remaining := "\r\n" + ProjectGitignoreHeader + "\r\n" + strings.Join(ProjectGitignorePatterns[1:], "\r\n") + "\r\n"
|
||||
|
|
@ -1976,7 +2010,7 @@ func TestEnsureProjectGitignore_PreservesAppendLineEndings(t *testing.T) {
|
|||
for _, tc := range []struct {
|
||||
name, existing, want string
|
||||
}{
|
||||
{"empty", "", lfBlock},
|
||||
{"empty", "", freshBlock},
|
||||
{"delimiter-free", "local", "local\n" + lfBlock},
|
||||
{"LF", "local\n", "local\n" + lfBlock},
|
||||
{"CRLF", "local\r\n", "local\r\n" + crlfBlock},
|
||||
|
|
|
|||
|
|
@ -2354,6 +2354,13 @@ func extractSSHHost(url string) string {
|
|||
// Bare dial+close (no doltserver.ProbeSQLServer): SSH, not MySQL — there is
|
||||
// no handshake greeting to drain here.
|
||||
func testSSHConnectivity(host string) bool {
|
||||
// #nosec G704 -- host is extractSSHHost(r.URL) over the remotes this repo's
|
||||
// own store returns, i.e. operator-configured local state, not request data.
|
||||
// The probe dials and immediately closes: nothing is sent and no response is
|
||||
// read, so there is no forgeable request. gosec only reaches this call after
|
||||
// this PR routed config discovery through env-derived paths; its taint
|
||||
// analysis is not field-sensitive, so one env-derived path marks the whole
|
||||
// store value tainted and every URL read back off it inherits that.
|
||||
conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, "22"), 5*time.Second)
|
||||
if err != nil {
|
||||
return false
|
||||
|
|
@ -2392,6 +2399,9 @@ func httpURLToTCPAddr(url string) string {
|
|||
// is no handshake greeting to drain here.
|
||||
func testHTTPConnectivity(url string) bool {
|
||||
addr := httpURLToTCPAddr(url)
|
||||
// #nosec G704 -- same probe shape and same taint path as testSSHConnectivity
|
||||
// above: url is a remote URL from this repo's own store, and the dial is
|
||||
// closed without sending or reading anything.
|
||||
conn, err := net.DialTimeout("tcp", addr, 5*time.Second)
|
||||
if err != nil {
|
||||
return false
|
||||
|
|
|
|||
|
|
@ -1847,6 +1847,14 @@ func hookSubprocessEnv(env []string) []string {
|
|||
// the pending index — where the staged deletion lives — so scrubbing it
|
||||
// here would make git fall back to the on-disk index and miss the
|
||||
// deletion. Reimplements gastownhall/beads#3838 (ckumar1).
|
||||
//
|
||||
// #nosec G702 -- no shell is involved: the binary is the literal "git" and
|
||||
// every argument is its own argv element. The only variable argument is the
|
||||
// export file's own path, and it sits after the "--" terminator, so git
|
||||
// always reads it as a pathspec and never as an option. Annotated on the
|
||||
// function rather than on the call so it stays correct however the body
|
||||
// addresses that path. Mirrors the annotation on configureHooksPath in
|
||||
// init_git_hooks.go.
|
||||
func isExportFileStagedForDeletion(fullPath string) bool {
|
||||
// The export file's directory is not guaranteed to exist — hookJSONLDir
|
||||
// can retarget into a worktree with no .beads yet, and a nested
|
||||
|
|
|
|||
|
|
@ -413,6 +413,11 @@ func (c *initHooksContext) needsUpdate() bool {
|
|||
}
|
||||
|
||||
func (c *initHooksContext) configureHooksPath(hooksDir string) error {
|
||||
// #nosec G702 -- no shell is involved: the binary is the literal "git" and
|
||||
// every path is passed as its own argv element, so neither c.paths.CommonDir
|
||||
// nor hooksDir can inject a command. Both reach here from the selected hooks
|
||||
// context and are absolute, and this mirrors the pre-existing
|
||||
// configureBeadsHooksPath in hooks.go.
|
||||
cmd := exec.Command("git", "--git-dir", c.paths.CommonDir, "config", "--local", "core.hooksPath", hooksDir)
|
||||
cmd.Dir, cmd.Env = c.workDir, c.env
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import (
|
|||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
|
@ -15,7 +14,6 @@ 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/storage/domain"
|
||||
domaingit "github.com/steveyegge/beads/internal/storage/domain/git"
|
||||
"github.com/steveyegge/beads/internal/storage/fs"
|
||||
|
|
@ -521,27 +519,21 @@ type runInitTailContext struct {
|
|||
gitUC domain.GitUseCase
|
||||
}
|
||||
|
||||
func (t runInitTailContext) isRoleGitRepo(ctx context.Context, fallback bool) bool {
|
||||
// Isolated tail contexts without a selected path retain their supplied use case.
|
||||
if t.workDir == "" {
|
||||
return fallback
|
||||
}
|
||||
// Dropping discovery ceilings can select a containing parent repository,
|
||||
// matching the role adapter's existing scrubbed reads and writes.
|
||||
probe := exec.CommandContext(ctx, "git", "rev-parse", "--git-dir")
|
||||
probe.Dir, probe.Env = t.workDir, gitenv.ScrubRouting(os.Environ())
|
||||
return probe.Run() == nil
|
||||
}
|
||||
|
||||
func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput, t runInitTailContext) error {
|
||||
gitUC := t.gitUC
|
||||
if t.workDir != "" {
|
||||
// Only the selected tail uses this scope; earlier bootstrap keeps its provider.
|
||||
// NewInitGitRepository runs `git rev-parse --git-dir` with Dir=workDir and
|
||||
// scrubbed routing, so dropping discovery ceilings can select a containing
|
||||
// parent repository, matching the role adapter's scrubbed reads and writes.
|
||||
gitUC = domain.NewGitUseCase(t.workDir, domaingit.NewInitGitRepository(t.workDir))
|
||||
}
|
||||
// One probe answers both the role gate and the artifact gates: gitUC is the
|
||||
// scrubbed selected-directory repository whenever workDir is set, and the
|
||||
// supplied use case otherwise, so a separate role probe could only repeat it.
|
||||
isRepo := gitUC.IsGitRepo(ctx)
|
||||
|
||||
if t.isRoleGitRepo(ctx, isRepo) {
|
||||
if isRepo {
|
||||
role := in.roleFlag
|
||||
if role == "" {
|
||||
role = "maintainer"
|
||||
|
|
|
|||
|
|
@ -121,6 +121,12 @@ func gitOriginHasDoltDataRefStatus() (bool, error) {
|
|||
func gitRemoteHasDoltDataRefStatus(remote string) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), gitDoltDataProbeTimeout)
|
||||
defer cancel()
|
||||
// #nosec G702 -- no shell is involved: the binary is the literal "git" and
|
||||
// the remote URL is its own argv element, so it cannot inject a command.
|
||||
// The value is this repo's configured sync remote, local operator state
|
||||
// rather than request data; gosec only reaches it because this PR routed
|
||||
// config discovery through env-derived paths (see testSSHConnectivity in
|
||||
// dolt.go for the same taint path).
|
||||
cmd := exec.CommandContext(ctx, "git", "ls-remote", gitRemoteURLForLsRemote(remote), "refs/dolt/data")
|
||||
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
|
||||
output, err := cmd.Output()
|
||||
|
|
|
|||
|
|
@ -707,10 +707,31 @@ func normalizeWorktreeGitEnvKey(key, goos string) string {
|
|||
return key
|
||||
}
|
||||
|
||||
// clearWorktreeGitRoutingEnv establishes the command working directory as the
|
||||
// repository-selection boundary without changing process identity or signal
|
||||
// semantics. Startup config discovery applies the same boundary to its one
|
||||
// pre-hook Git probe.
|
||||
// clearWorktreeGitRoutingEnv makes the command working directory the only
|
||||
// inherited input to repository selection, without changing process identity
|
||||
// or signal semantics. Unlike the child-process scrubs elsewhere in this
|
||||
// package, ClearRouting unsets the variables on the bd process itself, so bd's
|
||||
// own discovery — getGitContext, GetMainRepoRoot, FindBeadsDir and startup
|
||||
// config discovery — runs under the cleared environment for the whole command.
|
||||
// The trade-off is that the discovery-scope controls go with the redirection
|
||||
// ones, and they do not all move discovery the same way:
|
||||
//
|
||||
// - GIT_CEILING_DIRECTORIES is a stop, so clearing it widens the walk: a
|
||||
// stale inherited ceiling can no longer hide the repository the command is
|
||||
// standing in, but with no repository at or below the working directory the
|
||||
// walk can now reach a containing parent that ceiling excluded.
|
||||
// - GIT_DISCOVERY_ACROSS_FILESYSTEM only ever permits — git stops at a
|
||||
// filesystem boundary unless this is true — so clearing it narrows the
|
||||
// walk: a repository reachable from the working directory only by crossing
|
||||
// a mount point is no longer found by any bd worktree verb, and there is no
|
||||
// opt-out.
|
||||
// - ClearRouting matches GIT_CONFIG by prefix, so the whole GIT_CONFIG*
|
||||
// family — GIT_CONFIG_GLOBAL, GIT_CONFIG_SYSTEM, GIT_CONFIG_COUNT and its
|
||||
// numbered key/value pairs — is dropped for the command's lifetime rather
|
||||
// than for one child probe.
|
||||
//
|
||||
// Startup config discovery applies the same boundary to its one pre-hook Git
|
||||
// probe.
|
||||
func clearWorktreeGitRoutingEnv(cmd *cobra.Command) error {
|
||||
if !hasWorktreeCommandAncestor(cmd) {
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -120,6 +120,52 @@ func TestSecretGitTrackingIgnoresInheritedGitRouting(t *testing.T) {
|
|||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The scrub alone narrows the probe to upward discovery from the config
|
||||
// file's directory. A detached work tree — GIT_DIR plus GIT_WORK_TREE with
|
||||
// no in-tree .git beside the config — is reachable only through the
|
||||
// inherited context, so without the inherited fallback the guard reports
|
||||
// "untracked" and writes the secret into a tracked file.
|
||||
t.Run("legitimate routing", func(t *testing.T) {
|
||||
gitDir := filepath.Join(t.TempDir(), "repo.git")
|
||||
if err := os.MkdirAll(gitDir, 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runConfigProbeGit(t, gitDir, "init", "--bare", "--quiet")
|
||||
work := t.TempDir()
|
||||
beadsDir := filepath.Join(work, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detachedTracked := filepath.Join(beadsDir, "config.yaml")
|
||||
detachedUntracked := filepath.Join(beadsDir, "untracked.yaml")
|
||||
for _, path := range []string{detachedTracked, detachedUntracked} {
|
||||
if err := os.WriteFile(path, []byte("json: false\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
runConfigProbeGit(t, work, "--git-dir", gitDir, "--work-tree", work, "add", "--", detachedTracked)
|
||||
|
||||
t.Setenv("GIT_DIR", gitDir)
|
||||
t.Setenv("GIT_WORK_TREE", work)
|
||||
// Guard the fixture: the scrubbed probe must not see this repository at
|
||||
// all, or the fallback below would be satisfied by discovery instead.
|
||||
if isGitTrackedWithEnv(detachedTracked, gitenv.ScrubRouting(os.Environ())) {
|
||||
t.Fatal("scrubbed discovery reached the detached work tree; fixture cannot exercise the fallback")
|
||||
}
|
||||
if !isGitTracked(detachedTracked) {
|
||||
t.Error("legitimate routing lost the tracked file; the secret guard would write into it")
|
||||
}
|
||||
if isGitTracked(detachedUntracked) {
|
||||
t.Error("untracked file reported as tracked")
|
||||
}
|
||||
if err := checkSecretGitTracked(detachedTracked, "linear.api_key"); err == nil || !strings.Contains(err.Error(), "refusing to write secret key") {
|
||||
t.Errorf("tracked secret refusal = %v", err)
|
||||
}
|
||||
if err := checkSecretGitTracked(detachedUntracked, "linear.api_key"); err != nil {
|
||||
t.Errorf("untracked secret refused: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Fixture setup uses the same routing boundary before any per-case poison is set.
|
||||
|
|
|
|||
|
|
@ -182,12 +182,40 @@ func IsSecretKey(key string) bool {
|
|||
// isGitTracked returns true if the file at path is tracked by git
|
||||
// (i.e., has been git-added). Uses `git ls-files --error-unmatch`.
|
||||
func isGitTracked(path string) bool {
|
||||
cmd := exec.Command("git", "ls-files", "--error-unmatch", path)
|
||||
cmd.Dir = filepath.Dir(path)
|
||||
cmd.Env = gitenv.ScrubRouting(os.Environ())
|
||||
cmd.Stdout = nil
|
||||
cmd.Stderr = nil
|
||||
return cmd.Run() == nil
|
||||
inherited := os.Environ()
|
||||
return isGitTrackedWithEnv(path, gitenv.ScrubRouting(inherited), inherited)
|
||||
}
|
||||
|
||||
// isGitTrackedWithEnv probes path under env, then under each fallback in
|
||||
// order, stopping at the first that reports it as tracked. Callers pass the
|
||||
// scrubbed environment as env so inherited routing cannot hide a tracked
|
||||
// config file, and the inherited one as the fallback: that preserves bare work
|
||||
// trees and trusted config, where the repository is reachable only through the
|
||||
// inherited context. Either probe reporting the path as tracked is sufficient
|
||||
// to refuse the write. This mirrors the hook guard in cmd/bd/hooks.go.
|
||||
//
|
||||
// The first environment is a separate parameter rather than part of the
|
||||
// variadic so that a zero-probe call, which would fall through to "untracked"
|
||||
// and write the secret, cannot be spelled. The tail stays variadic because a
|
||||
// test needs to probe one environment alone; the twin's fixed (clean,
|
||||
// inherited) arity cannot express that, since exec treats a nil Env as
|
||||
// "inherit the current process" rather than as a disabled probe.
|
||||
//
|
||||
// Every probe failing counts as untracked, so the guard only blocks writes it
|
||||
// can prove are unsafe.
|
||||
func isGitTrackedWithEnv(path string, env []string, fallbacks ...[]string) bool {
|
||||
dir := filepath.Dir(path)
|
||||
for _, probe := range append([][]string{env}, fallbacks...) {
|
||||
cmd := exec.Command("git", "ls-files", "--error-unmatch", path)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = probe
|
||||
cmd.Stdout = nil
|
||||
cmd.Stderr = nil
|
||||
if cmd.Run() == nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var secretKeyEnvVarHints = map[string]string{ //nolint:gosec // Values are environment variable names, not credentials.
|
||||
|
|
|
|||
|
|
@ -77,7 +77,6 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() {
|
|||
}{
|
||||
{"malformed_config", "beads.role", 128},
|
||||
{"invalid_key", "invalid", 1},
|
||||
{"invalid_routing_boolean", "beads.role", 128},
|
||||
} {
|
||||
s.Run(tc.name, func() {
|
||||
switch tc.name {
|
||||
|
|
@ -89,8 +88,6 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() {
|
|||
t.Errorf("restore repository config: %v", err)
|
||||
}
|
||||
})
|
||||
case "invalid_routing_boolean":
|
||||
s.T().Setenv("GIT_CONFIG_NOSYSTEM", "not-a-boolean")
|
||||
}
|
||||
value, found, err := s.repo.GetConfig(s.Ctx(), tc.key)
|
||||
s.Require().Error(err)
|
||||
|
|
@ -111,6 +108,36 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() {
|
|||
}
|
||||
}
|
||||
|
||||
// TestConfig_ReadFailuresAreNotMissing used to carry an "invalid_routing_boolean"
|
||||
// row that poisoned GIT_CONFIG_NOSYSTEM and expected the beads.role read to fail.
|
||||
// beads.role reads now scrub inherited Git routing, so that poison never reaches
|
||||
// git for this key and the read succeeds. The row is replaced by the pair below,
|
||||
// which pins both halves of the new contract. The general "a read failure is an
|
||||
// error, not an absent key" guard is unaffected: malformed_config still proves it
|
||||
// for the same key through the repository's own config file.
|
||||
func (s *testSuite) TestConfig_BeadsRoleScrubsInheritedRoutingEnv() {
|
||||
s.gitInit()
|
||||
s.Require().NoError(s.repo.SetConfig(s.Ctx(), "beads.role", "maintainer"))
|
||||
s.T().Setenv("GIT_CONFIG_NOSYSTEM", "not-a-boolean")
|
||||
|
||||
// beads.role is read with routing scrubbed, so the poisoned value is gone
|
||||
// before git parses its environment.
|
||||
value, found, err := s.repo.GetConfig(s.Ctx(), "beads.role")
|
||||
s.Require().NoError(err)
|
||||
s.True(found)
|
||||
s.Equal("maintainer", value)
|
||||
|
||||
// Keys outside that scrub keep the inherited environment, so the same poison
|
||||
// still surfaces as a read error rather than as an absent key.
|
||||
value, found, err = s.repo.GetConfig(s.Ctx(), "user.name")
|
||||
s.Require().Error(err)
|
||||
s.False(found)
|
||||
s.Empty(value)
|
||||
var exitErr *exec.ExitError
|
||||
s.Require().ErrorAs(err, &exitErr)
|
||||
s.Equal(128, exitErr.ExitCode())
|
||||
}
|
||||
|
||||
// Regression guard: pre-canceled contexts already propagated before the config fix.
|
||||
func (s *testSuite) TestConfig_CancellationIsNotMissing() {
|
||||
ctx, cancel := context.WithCancel(s.Ctx())
|
||||
|
|
@ -454,9 +481,18 @@ func TestInitGitRepositoryUsesSelectedDirectory(t *testing.T) {
|
|||
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
|
||||
t.Setenv(key, changedHome)
|
||||
}
|
||||
// gastownhall/beads#6477 made the reader propagate Git's exit
|
||||
// error instead of mapping it to absence, so the generic
|
||||
// constructor now surfaces the changed HOME's broken .gitconfig
|
||||
// rather than reporting the key missing. The failure is itself
|
||||
// the proof that generic role reads still use the current caller
|
||||
// environment: only that environment can see this .gitconfig.
|
||||
role, found, err := inherited.GetConfig(t.Context(), "beads.role")
|
||||
require.NoError(t, err) // The existing reader maps Git exit errors to absence.
|
||||
require.False(t, found, "generic role reads still use the current caller environment")
|
||||
require.Error(t, err, "generic role reads still use the current caller environment")
|
||||
var inheritedExit *exec.ExitError
|
||||
require.ErrorAs(t, err, &inheritedExit)
|
||||
require.Equal(t, 128, inheritedExit.ExitCode())
|
||||
require.False(t, found)
|
||||
require.Empty(t, role)
|
||||
require.Error(t, inherited.SetConfig(t.Context(), "beads.role", "decoy"))
|
||||
require.NoError(t, selected.SetConfig(t.Context(), "beads.role", "contributor"))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue