fix(hooks): refuse symlinked and git-tracked hook writes, back up foreign hooks (bd-5vdt8) (#5284)
* fix(hooks): refuse symlinked and git-tracked hook writes, back up foreign hooks (bd-5vdt8) The hook installer wrote through symlinked .git/hooks/* files (O_TRUNC follows the link), rewriting the link target — in the reported case a git-tracked team script, re-dirtying 36 clones (wy-81fnur). It also injected the bd section into hooks it knows it does not own with no backup, and would happily write hook files that are themselves tracked by git. - guardHookWritePath: Lstat-refuse symlinked hook paths (with the resolved target named in the error) and refuse writes to git-tracked hook files; shared installs (.beads-hooks/) stay exempt from the tracked check because that directory is deliberately committed. - installHooksWithOptions: preflight all targets before writing any, so a refusal cannot leave a half-installed hook set; take a one-time .backup sidecar before first injecting into a non-bd hook (the sidecar is inert for the migration state machine — a marker-managed hook classifies as marker_managed regardless of sidecars). - applyHookMigrationExecution: same guard on migrated hook writes. - Flag help for --force/--chain now states they are no-ops instead of advertising behavior the installer never had. Agent-Signature: claude-code-fable-5-high on behalf of Steve Yegge Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(hooks): tracked-file refusal applies only to hooks bd does not own CI's TestEmbeddedHooks caught the guard being too broad: bd init's flow leaves .beads/hooks/* tracked, and teams commit that directory exactly like shared .beads-hooks/. Refusing there breaks every reinstall and upgrade. The wy-81fnur hazard is writing into a tracked file bd does NOT own — so the refusal now exempts bd-managed hooks (section markers or legacy bd shim/inline), matching the shared-install policy. Symlink refusal is unchanged and absolute. Agent-Signature: claude-code-fable-5-high on behalf of Steve Yegge Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
0d301514b2
commit
67f812a23d
3 changed files with 339 additions and 3 deletions
|
|
@ -768,6 +768,70 @@ var hooksListCmd = &cobra.Command{
|
|||
},
|
||||
}
|
||||
|
||||
// guardHookWritePath refuses hook writes that would silently modify files
|
||||
// bd does not own (bd-5vdt8):
|
||||
// - a symlinked hook path: os.WriteFile follows the link (O_TRUNC) and
|
||||
// rewrites the target inode — e.g. a repo-tracked script the hook
|
||||
// points at, dirtying every clone that shares it
|
||||
// - a hook file tracked by git: writing it dirties the working tree.
|
||||
// allowTracked exempts shared installs (.beads-hooks/ is deliberately
|
||||
// committed).
|
||||
func guardHookWritePath(hookPath string, allowTracked bool) error {
|
||||
fi, err := os.Lstat(hookPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil // creating a new file — nothing to clobber
|
||||
}
|
||||
return fmt.Errorf("failed to stat %s: %w", hookPath, err)
|
||||
}
|
||||
if fi.Mode()&os.ModeSymlink != 0 {
|
||||
target := "unresolvable target"
|
||||
if resolved, rerr := filepath.EvalSymlinks(hookPath); rerr == nil {
|
||||
target = resolved
|
||||
} else if link, lerr := os.Readlink(hookPath); lerr == nil {
|
||||
target = link
|
||||
}
|
||||
return fmt.Errorf("%s is a symlink to %s; writing would rewrite the link target, not the hook\nRemove the symlink (or leave that hook to its owner) and re-run", hookPath, target)
|
||||
}
|
||||
if allowTracked {
|
||||
return nil
|
||||
}
|
||||
// A tracked file is refused only when bd does NOT own it: writing into a
|
||||
// foreign tracked file dirties every clone that shares it (the wy-81fnur
|
||||
// incident). A bd-owned hook the user chose to commit (e.g. a team-shared
|
||||
// .beads/hooks/) is bd's to maintain — same policy as shared installs.
|
||||
if isGitTrackedFile(hookPath) && !isBdOwnedHookFile(hookPath) {
|
||||
return fmt.Errorf("%s is tracked by git and not a bd-managed hook; bd will not modify committed files it does not own\nUntrack it (git rm --cached) or move hooks to an untracked directory and re-run", hookPath)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// isBdOwnedHookFile reports whether the hook file at path is bd-managed:
|
||||
// either section-marker format or a legacy bd hook (shim or inline).
|
||||
func isBdOwnedHookFile(path string) bool {
|
||||
content, err := os.ReadFile(path) // #nosec G304 -- path is a hook location bd resolved
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(string(content), hookSectionBeginPrefix) {
|
||||
return true
|
||||
}
|
||||
versionInfo, err := getHookVersion(path)
|
||||
return err == nil && versionInfo.IsBdHook
|
||||
}
|
||||
|
||||
// isGitTrackedFile reports whether path is tracked by git in the repository
|
||||
// containing it. Errors (not a repo, path inside .git/, no work tree) count
|
||||
// as untracked — the guard only blocks writes it can prove are unsafe.
|
||||
func isGitTrackedFile(path string) bool {
|
||||
dir := filepath.Dir(path)
|
||||
base := filepath.Base(path)
|
||||
// #nosec G204 G702 - fixed "git" command; dir/base come from the hooks
|
||||
// directory bd itself resolved, not user input
|
||||
cmd := exec.Command("git", "-C", dir, "ls-files", "--error-unmatch", "--", base)
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
|
||||
//nolint:unparam // force and chain kept for CLI flag compatibility; section markers make them no-ops
|
||||
func installHooksWithOptions(hookNames []string, force bool, shared bool, chain bool, beadsHooks bool) error {
|
||||
var hooksDir string
|
||||
|
|
@ -813,6 +877,14 @@ func installHooksWithOptions(hookNames []string, force bool, shared bool, chain
|
|||
preservePreexistingHooks(hooksDir)
|
||||
}
|
||||
|
||||
// Refuse the whole install up front if any target is unsafe to write —
|
||||
// stopping midway through the loop would leave hooks half-installed.
|
||||
for _, hookName := range hookNames {
|
||||
if err := guardHookWritePath(filepath.Join(hooksDir, hookName), shared); err != nil {
|
||||
return fmt.Errorf("refusing to install %s hook: %w", hookName, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Install each hook using section markers (GH#1380).
|
||||
// Only the content between markers is managed by beads; user content
|
||||
// outside the markers is preserved across reinstalls and upgrades.
|
||||
|
|
@ -845,7 +917,17 @@ func installHooksWithOptions(hookNames []string, force bool, shared bool, chain
|
|||
// Legacy bd hook — replace entire file with section format
|
||||
newContent = "#!/usr/bin/env sh\n" + section
|
||||
} else {
|
||||
// Non-bd hook — inject section (preserving existing content)
|
||||
// Non-bd hook — this is the one write that modifies a file
|
||||
// bd does not own. Preserve the original as a one-time
|
||||
// .backup sidecar before injecting (bd-5vdt8).
|
||||
backupPath := hookPath + ".backup"
|
||||
if _, statErr := os.Lstat(backupPath); os.IsNotExist(statErr) {
|
||||
// #nosec G306 -- keep executable so a rename restores a working hook
|
||||
if backupErr := os.WriteFile(backupPath, existing, 0755); backupErr != nil {
|
||||
return fmt.Errorf("failed to back up %s before injecting bd section: %w", hookName, backupErr)
|
||||
}
|
||||
}
|
||||
// Inject section, preserving existing content
|
||||
newContent = injectHookSection(existingStr, section)
|
||||
}
|
||||
}
|
||||
|
|
@ -1778,9 +1860,9 @@ installed bd version - upgrading bd automatically updates hook behavior.`,
|
|||
}
|
||||
|
||||
func init() {
|
||||
hooksInstallCmd.Flags().Bool("force", false, "Overwrite existing hooks without backup")
|
||||
hooksInstallCmd.Flags().Bool("force", false, "No-op, kept for compatibility (section markers always preserve non-bd content)")
|
||||
hooksInstallCmd.Flags().Bool("shared", false, "Install hooks to .beads-hooks/ (versioned) instead of .git/hooks/")
|
||||
hooksInstallCmd.Flags().Bool("chain", false, "Chain with existing hooks (run them before bd hooks)")
|
||||
hooksInstallCmd.Flags().Bool("chain", false, "No-op, kept for compatibility (existing hook content always runs alongside the bd section)")
|
||||
hooksInstallCmd.Flags().Bool("beads", false, "Install hooks to .beads/hooks/ (recommended for Dolt backend)")
|
||||
|
||||
hooksCmd.AddCommand(hooksInstallCmd)
|
||||
|
|
|
|||
251
cmd/bd/hooks_guard_test.go
Normal file
251
cmd/bd/hooks_guard_test.go
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
)
|
||||
|
||||
// setupGuardTestRepo creates a git repo with one tracked script and chdirs
|
||||
// into it. Returns the repo dir.
|
||||
func setupGuardTestRepo(t *testing.T) string {
|
||||
t.Helper()
|
||||
repoDir := t.TempDir()
|
||||
|
||||
run := func(args ...string) {
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = repoDir
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Skipf("git %v failed: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
run("init")
|
||||
run("config", "user.email", "test@example.com")
|
||||
run("config", "user.name", "Test User")
|
||||
|
||||
if err := os.MkdirAll(filepath.Join(repoDir, "scripts"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(repoDir, "scripts", "team-pre-push"), []byte("#!/bin/sh\necho team hook\n"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run("add", "scripts/team-pre-push")
|
||||
run("commit", "-m", "add team hook script")
|
||||
|
||||
t.Chdir(repoDir)
|
||||
git.ResetCaches()
|
||||
return repoDir
|
||||
}
|
||||
|
||||
// bd-5vdt8: a symlinked hook file must refuse installation instead of
|
||||
// writing through the link into the target (historically a tracked repo
|
||||
// script, re-dirtying every clone).
|
||||
func TestInstallHooksRefusesSymlinkedHook(t *testing.T) {
|
||||
repoDir := setupGuardTestRepo(t)
|
||||
|
||||
target := filepath.Join(repoDir, "scripts", "team-pre-push")
|
||||
originalContent, err := os.ReadFile(target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
hookPath := filepath.Join(repoDir, ".git", "hooks", "pre-push")
|
||||
if err := os.MkdirAll(filepath.Dir(hookPath), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(target, hookPath); err != nil {
|
||||
t.Skipf("cannot create symlink: %v", err)
|
||||
}
|
||||
|
||||
installErr := installHooksWithOptions(managedHookNames, false, false, false, false)
|
||||
if installErr == nil {
|
||||
t.Fatal("expected install to refuse symlinked hook, got nil error")
|
||||
}
|
||||
if !strings.Contains(installErr.Error(), "symlink") {
|
||||
t.Fatalf("expected symlink refusal, got: %v", installErr)
|
||||
}
|
||||
|
||||
afterContent, err := os.ReadFile(target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(afterContent) != string(originalContent) {
|
||||
t.Fatalf("symlink target was modified:\n%s", afterContent)
|
||||
}
|
||||
|
||||
// Preflight must refuse before writing ANY hook — no partial install.
|
||||
for _, name := range managedHookNames {
|
||||
if name == "pre-push" {
|
||||
continue
|
||||
}
|
||||
if _, statErr := os.Lstat(filepath.Join(repoDir, ".git", "hooks", name)); !os.IsNotExist(statErr) {
|
||||
t.Errorf("hook %s was written despite refusal", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// bd-5vdt8: a hook file tracked by git (e.g. core.hooksPath pointing into
|
||||
// the working tree) must refuse installation instead of dirtying the tree.
|
||||
func TestInstallHooksRefusesTrackedHook(t *testing.T) {
|
||||
repoDir := setupGuardTestRepo(t)
|
||||
|
||||
if err := os.MkdirAll(filepath.Join(repoDir, "hooks"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
trackedHook := filepath.Join(repoDir, "hooks", "pre-commit")
|
||||
if err := os.WriteFile(trackedHook, []byte("#!/bin/sh\necho tracked hook\n"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"add", "hooks/pre-commit"},
|
||||
{"commit", "-m", "add tracked hook"},
|
||||
{"config", "core.hooksPath", "hooks"},
|
||||
} {
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = repoDir
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Skipf("git %v failed: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
git.ResetCaches()
|
||||
|
||||
installErr := installHooksWithOptions(managedHookNames, false, false, false, false)
|
||||
if installErr == nil {
|
||||
t.Fatal("expected install to refuse tracked hook, got nil error")
|
||||
}
|
||||
if !strings.Contains(installErr.Error(), "tracked by git") {
|
||||
t.Fatalf("expected tracked-file refusal, got: %v", installErr)
|
||||
}
|
||||
}
|
||||
|
||||
// A tracked hook that bd OWNS (section markers) must still be maintainable:
|
||||
// teams commit .beads/hooks/ like shared .beads-hooks/, and refusing would
|
||||
// break reinstall/upgrade for them (caught by TestEmbeddedHooks in CI).
|
||||
func TestInstallHooksAllowsTrackedBdOwnedHook(t *testing.T) {
|
||||
repoDir := setupGuardTestRepo(t)
|
||||
|
||||
hooksDir := filepath.Join(repoDir, "hooks")
|
||||
if err := os.MkdirAll(hooksDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bdHook := "#!/usr/bin/env sh\n" + generateHookSection("pre-commit")
|
||||
if err := os.WriteFile(filepath.Join(hooksDir, "pre-commit"), []byte(bdHook), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"add", "hooks/pre-commit"},
|
||||
{"commit", "-m", "commit bd-managed hook"},
|
||||
{"config", "core.hooksPath", "hooks"},
|
||||
} {
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = repoDir
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Skipf("git %v failed: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
git.ResetCaches()
|
||||
|
||||
if err := installHooksWithOptions(managedHookNames, false, false, false, false); err != nil {
|
||||
t.Fatalf("reinstall over a tracked bd-owned hook must succeed, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// bd-5vdt8: injecting the bd section into a hook bd does not own must
|
||||
// preserve the original as a .backup sidecar.
|
||||
func TestInstallHooksBacksUpForeignHook(t *testing.T) {
|
||||
repoDir := setupGuardTestRepo(t)
|
||||
|
||||
userContent := "#!/bin/sh\necho my custom hook\n"
|
||||
hookPath := filepath.Join(repoDir, ".git", "hooks", "pre-commit")
|
||||
if err := os.MkdirAll(filepath.Dir(hookPath), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(hookPath, []byte(userContent), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := installHooksWithOptions(managedHookNames, false, false, false, false); err != nil {
|
||||
t.Fatalf("install failed: %v", err)
|
||||
}
|
||||
|
||||
backup, err := os.ReadFile(hookPath + ".backup")
|
||||
if err != nil {
|
||||
t.Fatalf("expected .backup sidecar: %v", err)
|
||||
}
|
||||
if string(backup) != userContent {
|
||||
t.Fatalf(".backup does not match original content:\n%s", backup)
|
||||
}
|
||||
|
||||
merged, err := os.ReadFile(hookPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(merged), "echo my custom hook") {
|
||||
t.Fatal("user content lost from hook after injection")
|
||||
}
|
||||
if !strings.Contains(string(merged), hookSectionBeginPrefix) {
|
||||
t.Fatal("bd section not injected into hook")
|
||||
}
|
||||
|
||||
// Reinstall must not overwrite the backup with the merged content.
|
||||
if err := installHooksWithOptions(managedHookNames, false, false, false, false); err != nil {
|
||||
t.Fatalf("reinstall failed: %v", err)
|
||||
}
|
||||
backup2, err := os.ReadFile(hookPath + ".backup")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(backup2) != userContent {
|
||||
t.Fatal(".backup was clobbered on reinstall")
|
||||
}
|
||||
}
|
||||
|
||||
// Shared installs (.beads-hooks/) are deliberately committed, so the
|
||||
// tracked-file guard must not fire for them.
|
||||
func TestGuardHookWritePathAllowsTrackedWhenShared(t *testing.T) {
|
||||
repoDir := setupGuardTestRepo(t)
|
||||
|
||||
tracked := filepath.Join(repoDir, "scripts", "team-pre-push")
|
||||
if err := guardHookWritePath(tracked, true); err != nil {
|
||||
t.Fatalf("expected tracked file to be allowed with allowTracked=true, got: %v", err)
|
||||
}
|
||||
if err := guardHookWritePath(tracked, false); err == nil {
|
||||
t.Fatal("expected tracked file to be refused with allowTracked=false")
|
||||
}
|
||||
}
|
||||
|
||||
// The hook-migration apply path shares the same guard: a symlinked hook
|
||||
// must refuse the migrated write.
|
||||
func TestApplyHookMigrationRefusesSymlink(t *testing.T) {
|
||||
repoDir := setupGuardTestRepo(t)
|
||||
|
||||
target := filepath.Join(repoDir, "scripts", "team-pre-push")
|
||||
hooksDir := filepath.Join(repoDir, ".git", "hooks")
|
||||
if err := os.MkdirAll(hooksDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hookPath := filepath.Join(hooksDir, "pre-commit")
|
||||
if err := os.Symlink(target, hookPath); err != nil {
|
||||
t.Skipf("cannot create symlink: %v", err)
|
||||
}
|
||||
|
||||
plan := hookMigrationExecutionPlan{
|
||||
WriteOps: []hookMigrationWriteOp{
|
||||
{
|
||||
HookName: "pre-commit",
|
||||
HookPath: hookPath,
|
||||
State: "missing_no_artifacts",
|
||||
SourceKind: hookMigrationWriteFromTemplate,
|
||||
},
|
||||
},
|
||||
}
|
||||
if _, err := applyHookMigrationExecution(plan); err == nil {
|
||||
t.Fatal("expected migration apply to refuse symlinked hook")
|
||||
} else if !strings.Contains(err.Error(), "symlink") {
|
||||
t.Fatalf("expected symlink refusal, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -257,6 +257,9 @@ func applyHookMigrationExecution(execPlan hookMigrationExecutionPlan) (hookMigra
|
|||
}
|
||||
|
||||
for _, write := range preparedWrites {
|
||||
if err := guardHookWritePath(write.Path, false); err != nil {
|
||||
return summary, fmt.Errorf("refusing to write migrated hook %s: %w", write.HookName, err)
|
||||
}
|
||||
// #nosec G306 -- git hooks must be executable for Git to run them
|
||||
if err := os.WriteFile(write.Path, write.Content, 0755); err != nil {
|
||||
return summary, fmt.Errorf("writing migrated hook %s: %w", write.Path, err)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue