fix(init): use selected hook context in embedded initialization (#6464)
* 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 * fix(config): share subprocess key identity for Git routing (saa-cgh.93) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * 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> * 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 * test(execenv): exercise exported host policy wiring (saa-cgh.78) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(worktree): explain startup Git environment scope (saa-cgh.23) 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(init): isolate role configuration from inherited Git routing (saa-cgh.109.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): use the selected origin in contributor setup (saa-cgh.109.7) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): isolate Git writes in planning repositories (saa-cgh.109.9) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(init): retain inherited planning commit author (saa-cgh.109.9) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): align embedded role gates with selected Git context (saa-cgh.109.12) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): scope embedded artifact Git operations to selected directory (saa-cgh.109.15) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(init): cover selected optional artifacts and explain refused commits (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Honor role-probe cancellation and exercise actual fork planning (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * fix(init): warn when automatic contributor role write fails (saa-cgh.109.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(init): cover successful nonquiet contributor role writes (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Assert the automatic contributor setup banner alongside warnings (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * test(init): read persisted role routing from the store (saa-cgh.120) Agent-Signature: Codex-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(init): probe the selected repository before configuring roles (saa-cgh.109.8) 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(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): preserve CRLF when appending project rules (saa-cgh.96) Reported by bee-ghosttrack in gastownhall/beads#6343. Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(gitignore): pin detector edge cases and clarify append behavior (saa-cgh.96) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): preserve line endings in Git exclude appends (saa-cgh.104) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(gitignore): clarify exclude fixture path variable (saa-cgh.104) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): refuse exclude writes after read errors (saa-cgh.110) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(gitignore): share append byte composition (saa-cgh.105) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(gitignore): explain append aliasing and trailing CR completion (saa-cgh.105) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(gitignore): use shared composition for exclude rules (saa-cgh.111) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): omit the empty exclude leading separator (saa-cgh.112) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): bind exclude writers to the selected Git directory (saa-cgh.109.16) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): isolate tracked-file guard from Git routing (saa-cgh.98) Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6356. Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): retain legitimate inherited tracking context (saa-cgh.98) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(hooks): isolate trusted global configuration fixture (saa-cgh.98) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(hooks): explain conservative tracked-file guard (saa-cgh.98) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(git): resolve hooks paths in an explicit read-only context (saa-cgh.109.17.1) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * Bind init hook operations to the selected repository (saa-cgh.109.17) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * Give the hooks tail fixture an explicit remote context (saa-cgh.109.17) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(git): canonicalize the hooks fixture repository root (saa-cgh.109.17.1) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): complete selected hook options and alias handling (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Clarify hooks resolver ownership and preserve work-tree diagnostics (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Explain restoration of absent routing variables in selected exclude tests (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 * Align selected-tail fixtures with captured role authority (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * fix(init): keep embedded hook setup in the selected project (saa-cgh.120.12) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * 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 onto511849496): - 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. * test(init): retarget the bare row to the work-tree-less install policy This PR's TestInitEmbeddedHooksSelectedTail/bare row (authored 2026-09-09) asserted that a bare repository fails to resolve hooks and installs nothing. #6457 (6a4b4aa14e, 2026-09-27) added git.ResolveWorkTreelessHooksContext specifically to end that behavior -- its own comment calls out "turning a supported repository into a warning and no install at all" as the defect it fixes -- so the row pinned a policy main had deliberately superseded by the time the two met. Retargeted in place rather than deleted, so the bare shape keeps coverage through the embedded-init entry point (main's new bare/git_dir_cwd rows cover only the proxied path): bare now installs like any other selected repository, and being its own common directory, its hooks path lands in its own config. Mutation-proved load-bearing: removing the work-tree-less fallback reds this row alone (the other eight rows stay green) with ".../hooks/pre-commit: no such file or directory" -- i.e. it reproduces the original expectation exactly. --------- Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com> Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
This commit is contained in:
parent
43a526b828
commit
beed11c7f4
15 changed files with 360 additions and 60 deletions
|
|
@ -239,7 +239,7 @@ var configSetCmd = &cobra.Command{
|
|||
if !validRoles[value] {
|
||||
return HandleError("invalid role %q (valid values: maintainer, contributor)", value)
|
||||
}
|
||||
// bd config's own beads.role reads and writes ignore inherited Git
|
||||
// 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. beads.role is an authority
|
||||
// value and the reader it feeds treats a missing value as
|
||||
|
|
|
|||
|
|
@ -790,6 +790,8 @@ func EnsureProjectGitignore(repoPath string) error {
|
|||
return nil // All patterns already present
|
||||
}
|
||||
|
||||
// A fresh .gitignore must not start with a blank line; the separator only
|
||||
// belongs between existing content and the appended block.
|
||||
lines := make([]string, 0, len(toAdd)+2)
|
||||
if len(content) > 0 {
|
||||
lines = append(lines, "")
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -2375,6 +2375,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
|
||||
|
|
@ -2413,6 +2420,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
|
||||
|
|
|
|||
|
|
@ -2036,6 +2036,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
|
||||
|
|
|
|||
|
|
@ -373,6 +373,106 @@ func readInitHooksFile(t *testing.T, path string) []byte {
|
|||
return data
|
||||
}
|
||||
|
||||
func TestInitEmbeddedHooksSelectedTail(t *testing.T) {
|
||||
for _, name := range []string{"missing", "skip", "nonrepo", "pure_jj", "quiet_pure_jj", "colocated", "bare", "config_lock", "quiet_config_lock"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
selected, decoy, storage, common := newInitHooksFixture(t)
|
||||
preserveInitRoleInputs(t, filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "index"))
|
||||
if name == "nonrepo" || strings.Contains(name, "pure_jj") || name == "bare" {
|
||||
selected = t.TempDir()
|
||||
}
|
||||
if name == "bare" {
|
||||
initExcludeGit(t, selected, "init", "--bare")
|
||||
}
|
||||
if strings.Contains(name, "pure_jj") || name == "colocated" {
|
||||
require.NoError(t, os.Mkdir(filepath.Join(selected, ".jj"), 0755))
|
||||
}
|
||||
if name == "colocated" {
|
||||
initExcludeGit(t, selected, "config", "--local", "core.hooksPath", filepath.Join(common, "hooks"))
|
||||
}
|
||||
locked, quiet := strings.Contains(name, "config_lock"), strings.HasPrefix(name, "quiet")
|
||||
if locked {
|
||||
require.NoError(t, os.WriteFile(filepath.Join(common, "config.lock"), []byte("owned lock"), 0600))
|
||||
preserveInitRoleInputs(t, filepath.Join(common, "config"))
|
||||
}
|
||||
run := func() { runEmbeddedInitHooks(t.Context(), selected, storage, name == "skip", quiet) }
|
||||
if locked {
|
||||
stderr := captureStderr(t, run)
|
||||
require.Equal(t, !quiet, strings.Contains(stderr, "Failed to install git hooks"))
|
||||
require.Equal(t, !quiet, strings.Contains(stderr, "bd hooks install --beads"))
|
||||
} else {
|
||||
stdout := captureStdout(t, func() error { run(); return nil })
|
||||
require.Equal(t, name == "pure_jj", strings.Contains(stdout, "Jujutsu repository detected"))
|
||||
}
|
||||
destination := filepath.Join(storage, "hooks")
|
||||
if name == "colocated" {
|
||||
destination = filepath.Join(common, "hooks")
|
||||
}
|
||||
if name == "skip" || name == "nonrepo" || strings.Contains(name, "pure_jj") {
|
||||
_, err := os.Stat(destination)
|
||||
require.ErrorIs(t, err, os.ErrNotExist)
|
||||
return
|
||||
}
|
||||
require.Contains(t, string(readInitHooksFile(t, filepath.Join(destination, "pre-commit"))), hookSectionBeginPrefix)
|
||||
if !locked && name != "colocated" {
|
||||
// A bare repository has no work tree to anchor, so it resolves
|
||||
// through the work-tree-less hooks context (GH#6457) and is its own
|
||||
// common directory. It installs like any other selected repository
|
||||
// rather than degrading to a warning and no install at all.
|
||||
configRoot := common
|
||||
if name == "bare" {
|
||||
configRoot = selected
|
||||
}
|
||||
got := initExcludeGit(t, selected, "config", "--file", filepath.Join(configRoot, "config"), "--get", "core.hooksPath")
|
||||
require.Equal(t, filepath.Clean(destination), filepath.Clean(got))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitEmbeddedHooksSelectedStatus(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("hook current-status checks require POSIX executable bits")
|
||||
}
|
||||
for _, name := range []string{"decoy_current", "target_current", "target_outdated"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
selected, decoy, storage, common := newInitHooksFixture(t)
|
||||
current := filepath.Join(decoy, ".git", "hooks")
|
||||
configuredRepo := decoy
|
||||
if name != "decoy_current" {
|
||||
current = filepath.Join(common, "hooks")
|
||||
configuredRepo = selected
|
||||
}
|
||||
initExcludeGit(t, configuredRepo, "config", "--local", "core.hooksPath", current)
|
||||
require.NoError(t, os.MkdirAll(current, 0755))
|
||||
for _, hook := range managedHookNames {
|
||||
content := "#!/bin/sh\n" + generateHookSection(hook)
|
||||
if name == "target_outdated" {
|
||||
content = "#!/bin/sh\n" + hookVersionPrefix + "0.0.0\n# bd (beads) " + hook + " hook\n"
|
||||
}
|
||||
require.NoError(t, os.WriteFile(filepath.Join(current, hook), []byte(content), 0755))
|
||||
}
|
||||
require.True(t, hooksInstalledAt(current))
|
||||
require.Equal(t, name == "target_outdated", hookStatusesNeedUpdate(checkGitHooksAt(current)))
|
||||
if name == "decoy_current" {
|
||||
require.True(t, hooksInstalled() && !hooksNeedUpdate(), "inherited decoy hooks must be current")
|
||||
}
|
||||
preserveInitRoleInputs(t, filepath.Join(current, "pre-commit"), filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "index"))
|
||||
stdout := captureStdout(t, func() error {
|
||||
runEmbeddedInitHooks(t.Context(), selected, storage, false, false)
|
||||
return nil
|
||||
})
|
||||
require.Equal(t, name == "target_outdated", strings.Contains(stdout, "Updating hooks to version"))
|
||||
if name == "target_current" {
|
||||
_, err := os.Stat(filepath.Join(storage, "hooks"))
|
||||
require.ErrorIs(t, err, os.ErrNotExist)
|
||||
} else {
|
||||
require.Contains(t, string(readInitHooksFile(t, filepath.Join(storage, "hooks", "pre-commit"))), hookSectionBeginLine())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func preserveStandaloneHookInputs(t *testing.T, paths ...string) {
|
||||
t.Helper()
|
||||
beforeEnv := os.Environ()
|
||||
|
|
|
|||
|
|
@ -2051,41 +2051,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
}
|
||||
}
|
||||
|
||||
// Check if we're in a git repo and hooks aren't installed
|
||||
// Install by default unless --skip-hooks is passed
|
||||
// Hooks are installed to .beads/hooks/ (uses git config core.hooksPath)
|
||||
// For jujutsu colocated repos, use simplified hooks (no staging needed)
|
||||
hooksExist := hooksInstalled()
|
||||
if !skipHooks && (!hooksExist || hooksNeedUpdate()) {
|
||||
if hooksExist && !quiet {
|
||||
fmt.Printf(" Updating hooks to version %s...\n", Version)
|
||||
}
|
||||
isJJ := git.IsJujutsuRepo()
|
||||
isColocated := git.IsColocatedJJGit()
|
||||
|
||||
if isJJ && !isColocated {
|
||||
// Pure jujutsu repo (no git) - print alias instructions
|
||||
if !quiet {
|
||||
printJJAliasInstructions()
|
||||
}
|
||||
} else if isColocated {
|
||||
// Colocated jj+git repo - use simplified hooks
|
||||
if err := installJJHooks(); err != nil && !quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to install jj hooks: %v\n", ui.RenderWarn("⚠"), err)
|
||||
fmt.Fprintf(os.Stderr, "You can try again with: %s\n\n", ui.RenderAccent("bd doctor --fix"))
|
||||
} else if !quiet {
|
||||
fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n")
|
||||
}
|
||||
} else if isGitRepo() {
|
||||
// Regular git repo - install hooks to .beads/hooks/
|
||||
if err := installHooksWithOptions(managedHookNames, false, false, false, true); err != nil && !quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to install git hooks to .beads/hooks/: %v\n", ui.RenderWarn("⚠"), err)
|
||||
fmt.Fprintf(os.Stderr, "You can try again with: %s\n\n", ui.RenderAccent("bd hooks install --beads"))
|
||||
} else if !quiet {
|
||||
fmt.Printf(" Hooks installed to: .beads/hooks/\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
runEmbeddedInitHooks(rootCtx, cwd, beadsDir, skipHooks, quiet)
|
||||
|
||||
// Initialize version tracking: create .local_version file during bd init
|
||||
// instead of deferring it to the first bd command.
|
||||
|
|
|
|||
|
|
@ -22,8 +22,48 @@ import (
|
|||
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
|
||||
"github.com/steveyegge/beads/internal/storage/schema"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestEmbeddedInitHooksRouting(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests")
|
||||
}
|
||||
bd := buildEmbeddedBD(t)
|
||||
target, decoy, home := newInitRoleFixture(t)
|
||||
global := filepath.Join(home, ".gitconfig")
|
||||
initRoleFixtureGit(t, target, "config", "--file", global, "user.name", "Hook Fixture")
|
||||
initRoleFixtureGit(t, target, "config", "--file", global, "user.email", "hooks@example.invalid")
|
||||
require.NoError(t, os.WriteFile(filepath.Join(decoy, "seed"), []byte("decoy\n"), 0600))
|
||||
initRoleFixtureGit(t, decoy, "add", "seed")
|
||||
t.Setenv("GIT_DIR", filepath.Join(home, "missing.git"))
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
t.Setenv("GIT_INDEX_FILE", filepath.Join(decoy, ".git", "index"))
|
||||
preserveInitRoleInputs(t, filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "index"), global)
|
||||
storage := filepath.Join(home, "separate storage", ".beads")
|
||||
require.NoError(t, os.MkdirAll(filepath.Dir(storage), 0750))
|
||||
cmd := exec.Command(bd, "init", "--prefix", "hookfixture", "--quiet", "--non-interactive", "--skip-agents", "--role", "maintainer")
|
||||
env := bdEnv(home)
|
||||
for _, key := range []string{"BEADS_DIR", "BEADS_DB", "BD_DB", "BD_DOLT_HOST", "BD_DOLT_PORT"} {
|
||||
env = envWithout(env, key)
|
||||
}
|
||||
cmd.Dir, cmd.Env = target, append(env, "BEADS_DIR="+storage, "DOLT_ROOT_PATH="+home, "BD_DOLT_MODE=embedded", "BD_EVENTS_JOURNAL=false")
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, "embedded hook init: %s", out)
|
||||
cfg, err := configfile.Load(storage)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cfg)
|
||||
require.Equal(t, configfile.DoltModeEmbedded, cfg.DoltMode)
|
||||
info, err := os.Stat(filepath.Join(storage, "embeddeddolt", "hookfixture", ".dolt"))
|
||||
require.NoError(t, err)
|
||||
require.True(t, info.IsDir())
|
||||
for _, name := range managedHookNames {
|
||||
require.Contains(t, string(readInitHooksFile(t, filepath.Join(storage, "hooks", name))), hookSectionBeginPrefix)
|
||||
}
|
||||
got := initRoleFixtureGit(t, target, "config", "--local", "--get", "core.hooksPath")
|
||||
require.Equal(t, filepath.Clean(filepath.Join(storage, "hooks")), filepath.Clean(got))
|
||||
}
|
||||
|
||||
var (
|
||||
embeddedBDOnce sync.Once
|
||||
embeddedBD string
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
|
@ -10,9 +11,58 @@ import (
|
|||
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"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/ui"
|
||||
)
|
||||
|
||||
// runEmbeddedInitHooks uses the project for Git and the captured storage for hooks.
|
||||
func runEmbeddedInitHooks(ctx context.Context, workDir, beadsDir string, skip, quiet bool) {
|
||||
if skip {
|
||||
return
|
||||
}
|
||||
gitUC := domain.NewGitUseCase(workDir, domaingit.NewInitGitRepository(workDir))
|
||||
isColocated := gitUC.IsColocatedJJGit(ctx)
|
||||
if gitUC.IsJujutsuRepo(ctx) && !isColocated {
|
||||
if !quiet {
|
||||
printJJAliasInstructions()
|
||||
}
|
||||
return
|
||||
}
|
||||
if !isColocated && !gitUC.IsGitRepo(ctx) {
|
||||
return
|
||||
}
|
||||
hooks, err := resolveInitHooksContext(workDir, beadsDir)
|
||||
if err != nil {
|
||||
if !quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to resolve git hooks: %v\n", ui.RenderWarn("⚠"), err)
|
||||
}
|
||||
return
|
||||
}
|
||||
hooksExist := hooks.installed()
|
||||
if hooksExist && !hooks.needsUpdate() {
|
||||
return
|
||||
}
|
||||
if hooksExist && !quiet {
|
||||
fmt.Printf(" Updating hooks to version %s...\n", Version)
|
||||
}
|
||||
if isColocated {
|
||||
if err := installHooksWithContext(jjHookNames, false, false, false, false, hooks); err != nil && !quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to install jj hooks: %v\n", ui.RenderWarn("⚠"), err)
|
||||
fmt.Fprintf(os.Stderr, "You can try again with: %s\n\n", ui.RenderAccent("bd doctor --fix"))
|
||||
} else if !quiet {
|
||||
fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n")
|
||||
}
|
||||
} else {
|
||||
if err := installHooksWithContext(managedHookNames, false, false, false, true, hooks); err != nil && !quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to install git hooks to .beads/hooks/: %v\n", ui.RenderWarn("⚠"), err)
|
||||
fmt.Fprintf(os.Stderr, "You can try again with: %s\n\n", ui.RenderAccent("bd hooks install --beads"))
|
||||
} else if !quiet {
|
||||
fmt.Printf(" Hooks installed to: .beads/hooks/\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// preCommitFrameworkPattern matches pre-commit or prek framework hooks.
|
||||
// Uses same patterns as hookManagerPatterns in doctor/fix/hooks.go for consistency.
|
||||
// Includes all detection patterns: pre-commit run, prek run/hook-impl, config file refs, and pre-commit env vars.
|
||||
|
|
@ -375,6 +425,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()
|
||||
|
|
|
|||
|
|
@ -718,11 +718,31 @@ func worktreeGitEnvKey(entry string) string {
|
|||
// 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).
|
||||
// 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 boundary
|
||||
// removes inherited discovery redirects, but it is not a floor: 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 (init's role
|
||||
// probe records the same trade-off).
|
||||
// - 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 redirecting members of
|
||||
// the GIT_CONFIG* family — a custom GIT_CONFIG_GLOBAL or GIT_CONFIG_SYSTEM
|
||||
// path, GIT_CONFIG_COUNT and its numbered key/value pairs — are dropped for
|
||||
// the command's lifetime rather than for one child probe. The explicit
|
||||
// suppression forms are the exception: ClearRouting keeps
|
||||
// GIT_CONFIG_NOSYSTEM and the /dev/null spellings of GIT_CONFIG_GLOBAL and
|
||||
// GIT_CONFIG_SYSTEM, which can blind a read but cannot redirect one.
|
||||
func clearWorktreeGitRoutingEnv(cmd *cobra.Command) error {
|
||||
if !hasWorktreeCommandAncestor(cmd) {
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -127,6 +127,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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A checkout reachable only through inherited Git routing is the case a
|
||||
|
|
|
|||
|
|
@ -193,18 +193,42 @@ func IsSecretKey(key string) bool {
|
|||
// named only by GIT_DIR/GIT_WORK_TREE — so the inherited context is consulted
|
||||
// before declaring the file untracked. Mirrors isGitTrackedFile in cmd/bd.
|
||||
func isGitTracked(path string) bool {
|
||||
dir := filepath.Dir(path)
|
||||
inherited := os.Environ()
|
||||
for _, env := range [][]string{gitenv.ScrubRouting(inherited), inherited} {
|
||||
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 = env
|
||||
cmd.Env = probe
|
||||
cmd.Stdout = nil
|
||||
cmd.Stderr = nil
|
||||
err := cmd.Run()
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
// Exit 1 is git's "repository reached, path is not tracked" answer and
|
||||
// is final, so a later probe runs only when this one failed for a
|
||||
// configuration reason (no reachable repository).
|
||||
if exit, ok := err.(*exec.ExitError); ok && exit.ExitCode() == 1 {
|
||||
return false
|
||||
}
|
||||
|
|
|
|||
|
|
@ -156,7 +156,8 @@ func normalizeHooksWorkDir(workDir string) (string, error) {
|
|||
//
|
||||
// This is the explicit-context sibling of GetGitHooksDir. It returns a struct
|
||||
// instead of following this file's GetXFrom(startDir) convention because all
|
||||
// four paths must come from one resolution of one directory.
|
||||
// four paths must come from one resolution of one directory. The first in-repo
|
||||
// caller is the selected-hook setup in cmd/bd/init_git_hooks.go (GH#6440).
|
||||
func ResolveHooksContext(workDir string, env []string) (HooksContext, error) {
|
||||
if workDir == "" {
|
||||
return HooksContext{}, fmt.Errorf("hooks context requires a working directory")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue