fix(doctor): tighten .beads/.gitignore perms even when patterns are complete (#5634)

* fix(doctor): tighten .beads/.gitignore perms even when patterns are complete

EnsureGitignoreForBeadsDir returned early when the file was already
pattern-complete, skipping the 0600 tightening below - so a complete file
with loose perms (0644 from an old bd, a checkout, or umask) never got
repaired. Hoist the permission repair above the early return and trigger
on any deviation from 0600, not just missing owner-write.

Adds the tests flagged in the #5285 review: pattern-complete-but-0644 gets
tightened with content byte-identical, and FixGitignore twice is
idempotent (no duplicate appends).

Agent-Signature: claude-fable-5-high on behalf of matt wilkie
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G74Vh4USrUkc9przesWyUJ

* fix(doctor): correct permission-warning wording and pin its branch

Maintainer review fixups for PR #5634 (adopt-pr review iteration 1). All
three changes are confined to the files this PR already touches.

- CheckGitignore reported "Loose permissions on .beads/.gitignore" for any
  mode != 0600, which is factually inverted for a mode *stricter* than 0600:
  a 0400 file was reported as loose and then widened to 0600 by --fix.
  Reword to "Unexpected permissions"; Detail ("Mode is 0400, want 0600") and
  Fix are unchanged. The check predicate is deliberately left alone --
  normalizing to exactly 0600 is the stated policy at every writer of this
  file, and EnsureGitignoreForBeadsDir must restore owner-write to keep its
  append route working, so the widening is intended behavior, not a defect.

- TestCheckGitignore_WarnsOnLoosePermsWhenPatternComplete asserted only that
  *a* warning fired. CheckGitignore also warns for a missing file and for
  missing patterns, so if GitignoreTemplate ever drifted out of
  requiredPatterns the test would stay green while the permission branch went
  untested. Pin the branch: assert the message and the observed mode.

- Retarget the trailing os.Chmod comment. With the chmod hoisted above the
  pattern check, its old "the file may predate the 0600 policy" rationale is
  now handled upstream; the residual case it still guards is the hoisted
  block's os.Stat failing (file removed between the ReadFile and the Stat,
  where os.WriteFile then creates it under umask).

Validation: go test ./cmd/bd/doctor/ -run Gitignore green, go build, go vet,
gofmt all clean. The new assertions are mutation-proved: reverting the message
reds the message assert, and drifting requiredPatterns out of the template
reds both new asserts while the pre-fix Status-only shape stays green -- the
exact masking these assertions close.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
This commit is contained in:
matt wilkie 2026-09-30 18:34:19 -07:00 • committed by GitHub
commit c33738d209
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 188 additions and 8 deletions

View file

@ -5,6 +5,7 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/steveyegge/beads/internal/gitignore"
@ -171,6 +172,21 @@ func CheckGitignore(repoPath string) DoctorCheck {
}
}
// A pattern-complete file with loose permissions must still surface as a
// warning: doctor --fix only schedules FixGitignore for non-ok checks, so
// an ok here would leave the permission repair unreachable.
if runtime.GOOS != "windows" {
if info, err := os.Stat(gitignorePath); err == nil && info.Mode().Perm() != 0600 {
return DoctorCheck{
Name: "Gitignore",
Status: "warning",
Message: "Unexpected permissions on .beads/.gitignore",
Detail: fmt.Sprintf("Mode is %04o, want 0600", info.Mode().Perm()),
Fix: "Run: bd doctor --fix or bd init (safe to re-run)",
}
}
}
return DoctorCheck{
Name: "Gitignore",
Status: "ok",
@ -193,19 +209,22 @@ func EnsureGitignoreForBeadsDir(beadsDir string) error {
return fmt.Errorf("read .beads/.gitignore: %w", err)
}
missing := missingGitignorePatterns(string(content))
if len(missing) == 0 {
return nil
}
// Tighten permissions before the pattern check so a pattern-complete
// file with loose perms (e.g. 0644) still gets locked down; the
// early return below must not skip this (flagged post-#5285).
if info, err := os.Stat(gitignorePath); err == nil {
if info.Mode().Perm()&0200 == 0 {
if info.Mode().Perm() != 0600 {
if err := os.Chmod(gitignorePath, 0600); err != nil {
return fmt.Errorf("chmod .beads/.gitignore: %w", err)
}
}
}
missing := missingGitignorePatterns(string(content))
if len(missing) == 0 {
return nil
}
existingContent := string(content)
newContent := existingContent
if len(newContent) > 0 && !strings.HasSuffix(newContent, "\n") {
@ -221,8 +240,11 @@ func EnsureGitignoreForBeadsDir(beadsDir string) error {
return fmt.Errorf("ensure .beads/.gitignore: %w", err)
}
// Tighten permissions on pre-existing files: os.WriteFile's mode argument
// only applies at creation, and the file may predate the 0600 policy.
// Residual guard for the one case the hoisted block above cannot cover: if
// its os.Stat failed, no chmod ran. Either the file was removed between the
// ReadFile and that Stat -- os.WriteFile then creates it, and its 0600 mode
// argument is filtered by umask -- or it still exists at its old mode, which
// os.WriteFile leaves untouched. Both converge to 0600 here.
if err := os.Chmod(gitignorePath, 0600); err != nil {
return fmt.Errorf("chmod .beads/.gitignore: %w", err)
}

View file

@ -1,6 +1,7 @@
package doctor
import (
"bytes"
"os"
"os/exec"
"path/filepath"
@ -411,6 +412,115 @@ func TestEnsureGitignoreForBeadsDir_AppendsMissingRuntimePatterns(t *testing.T)
}
}
// TestEnsureGitignoreForBeadsDir_TightensPermsWhenPatternComplete covers the
// regression flagged (but not fixed) in PR #5285: a pattern-complete
// .beads/.gitignore with loose permissions (0644) must still be tightened to
// 0600. Before the fix, the early return for "no missing patterns" skipped
// the chmod entirely.
func TestEnsureGitignoreForBeadsDir_TightensPermsWhenPatternComplete(t *testing.T) {
// Skip on Windows as it doesn't support Unix-style file permissions
if runtime.GOOS == "windows" {
t.Skip("Skipping file permissions test on Windows")
}
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.Mkdir(beadsDir, 0750); err != nil {
t.Fatal(err)
}
gitignorePath := filepath.Join(beadsDir, ".gitignore")
if err := os.WriteFile(gitignorePath, []byte(GitignoreTemplate), 0644); err != nil {
t.Fatal(err)
}
// WriteFile's mode is filtered by umask; force the loose mode explicitly
// so the scenario holds under restrictive umasks (e.g. 077).
if err := os.Chmod(gitignorePath, 0644); err != nil {
t.Fatal(err)
}
if err := EnsureGitignoreForBeadsDir(beadsDir); err != nil {
t.Fatalf("EnsureGitignoreForBeadsDir failed: %v", err)
}
info, err := os.Stat(gitignorePath)
if err != nil {
t.Fatalf("Failed to stat .gitignore: %v", err)
}
if perm := info.Mode().Perm(); perm != 0600 {
t.Errorf("expected permissions 0600 for pattern-complete file, got %o", perm)
}
content, err := os.ReadFile(gitignorePath)
if err != nil {
t.Fatalf("Failed to read .gitignore: %v", err)
}
if string(content) != GitignoreTemplate {
t.Errorf("content changed when only permissions should have been tightened.\nGot:\n%s", content)
}
}
// TestFixGitignore_IdempotentNoDuplication ensures calling the fix twice in a
// row does not append duplicate pattern blocks: content must be byte-identical
// between the first and second invocation.
func TestFixGitignore_IdempotentNoDuplication(t *testing.T) {
tmpDir := t.TempDir()
oldDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatal(err)
}
defer func() {
if err := os.Chdir(oldDir); err != nil {
t.Error(err)
}
}()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.Mkdir(beadsDir, 0750); err != nil {
t.Fatal(err)
}
initialContent := "# Local additions\ncustom-local/\n*.db\ndaemon.log\n"
gitignorePath := filepath.Join(".beads", ".gitignore")
if err := os.WriteFile(gitignorePath, []byte(initialContent), 0600); err != nil {
t.Fatal(err)
}
if err := FixGitignore(tmpDir); err != nil {
t.Fatalf("FixGitignore (first call) failed: %v", err)
}
firstContent, err := os.ReadFile(gitignorePath)
if err != nil {
t.Fatalf("Failed to read gitignore after first fix: %v", err)
}
if err := FixGitignore(tmpDir); err != nil {
t.Fatalf("FixGitignore (second call) failed: %v", err)
}
secondContent, err := os.ReadFile(gitignorePath)
if err != nil {
t.Fatalf("Failed to read gitignore after second fix: %v", err)
}
if !bytes.Equal(firstContent, secondContent) {
t.Errorf("content changed between first and second FixGitignore call (duplicate append?).\nFirst:\n%s\n\nSecond:\n%s", firstContent, secondContent)
}
if runtime.GOOS != "windows" {
info, err := os.Stat(gitignorePath)
if err != nil {
t.Fatalf("Failed to stat .gitignore: %v", err)
}
if perm := info.Mode().Perm(); perm != 0600 {
t.Errorf("expected permissions 0600 after idempotent fix, got %o", perm)
}
}
}
func TestFixGitignore_PartialPatterns(t *testing.T) {
tests := []struct {
name string
@ -2911,3 +3021,51 @@ func TestCheckNoVestigialSyncWorktrees_VestigialDetected(t *testing.T) {
t.Errorf("Message = %q, want it to contain 'Vestigial'", check.Message)
}
}
func TestCheckGitignore_WarnsOnLoosePermsWhenPatternComplete(t *testing.T) {
// Skip on Windows as it doesn't support Unix-style file permissions
if runtime.GOOS == "windows" {
t.Skip("Skipping file permissions test on Windows")
}
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.Mkdir(beadsDir, 0750); err != nil {
t.Fatal(err)
}
gitignorePath := filepath.Join(beadsDir, ".gitignore")
if err := os.WriteFile(gitignorePath, []byte(GitignoreTemplate), 0644); err != nil { // #nosec G306 -- loose perms are the scenario under test
t.Fatal(err)
}
// WriteFile's mode is filtered by umask; force the loose mode explicitly
// so the scenario holds under restrictive umasks (e.g. 077).
if err := os.Chmod(gitignorePath, 0644); err != nil {
t.Fatal(err)
}
check := CheckGitignore(tmpDir)
if check.Status != "warning" {
t.Fatalf("Status = %q, want %q (pattern-complete file at 0644 must warn so doctor --fix schedules FixGitignore)", check.Status, "warning")
}
// Pin the warning to the permission branch. CheckGitignore also warns for a
// missing file and for missing patterns, so asserting only that *a* warning
// fired would keep this test green for the wrong reason if GitignoreTemplate
// ever drifted out of requiredPatterns and the pattern branch returned first.
if check.Message != "Unexpected permissions on .beads/.gitignore" {
t.Errorf("Message = %q, want the permission-branch warning", check.Message)
}
if !strings.Contains(check.Detail, "0644") {
t.Errorf("Detail = %q, want the observed mode 0644", check.Detail)
}
if check.Fix == "" {
t.Error("expected a Fix suggestion for loose permissions")
}
// After the fix runs, the check must go green.
if err := FixGitignore(tmpDir); err != nil {
t.Fatalf("FixGitignore: %v", err)
}
if check := CheckGitignore(tmpDir); check.Status != "ok" {
t.Fatalf("post-fix Status = %q, want ok", check.Status)
}
}