fix(worktree): repair permissive .beads/ after worktree create (GH#3593) (#3640)

* fix(worktree): repair permissive .beads/ after worktree create (GH#3593)

Call config.FixBeadsDirPermissions on the new worktree's .beads/ after a
successful git worktree add so tracked directories checked out at umask
defaults match bd's 0700 expectation (same pattern as bd init / GH#3391).

Tests: TestRepairWorktreeBeadsPermissions (!windows).

* fix(worktree): reject unsafe beads permission targets

Validate .beads with Lstat before automatic permission repair so symlinks and non-directories cannot be chmod targets.

Agent-Signature: codex-gpt-5.6-sol-medium on behalf of matt wilkie

* fix(config): make permission repair race-safe

Open .beads without following symlinks, verify descriptor identity, and chmod the opened directory so path swaps cannot redirect permission changes.

Agent-Signature: codex-gpt-5.6-sol-medium on behalf of matt wilkie

* fix(config): preserve secure repair across platforms

Isolate Linux descriptor primitives, keep wasm targets buildable, and repair unreadable directories through an O_PATH handle with fchmodat2.

Agent-Signature: codex-gpt-5.6-sol-medium on behalf of matt wilkie

* test(config): tolerate legacy Linux chmod support

Skip optional unreadable-directory coverage when fchmodat2 is unavailable and verify unsupported descriptor chmod leaves permissions unchanged.

Agent-Signature: codex-gpt-5.6-sol-medium on behalf of matt wilkie

* fix(config): satisfy errcheck on deferred dir.Close

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: matt wilkie <maphew@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Kevin Glynn 2026-07-14 16:14:14 -04:00 • committed by GitHub
commit f4d496fed2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 434 additions and 3 deletions

View file

@ -12,6 +12,7 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/ui"
@ -146,6 +147,19 @@ func init() {
rootCmd.AddCommand(worktreeCmd)
}
// repairWorktreeBeadsPermissions applies FixBeadsDirPermissions to worktreePath/.beads when
// the directory exists. Git worktree checkout can leave tracked .beads/ at permissive modes.
func repairWorktreeBeadsPermissions(worktreePath string) {
beadsDir := filepath.Join(worktreePath, ".beads")
if fixed, err := config.FixBeadsDirPermissions(beadsDir); err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: could not fix worktree .beads permissions: %v\n", err)
}
} else if fixed && !jsonOutput {
fmt.Fprintf(os.Stderr, "Fixed .beads permissions to %04o\n", config.BeadsDirPerm)
}
}
func runWorktreeCreate(cmd *cobra.Command, args []string) error {
CheckReadonly("worktree create")
@ -201,6 +215,10 @@ func runWorktreeCreate(cmd *cobra.Command, args []string) error {
}
}
// Tracked .beads/ checked out by git worktree add can inherit umask defaults (0755).
// Align with bd init / GH#3391 so agent loops do not hit permission warnings (GH#3593).
repairWorktreeBeadsPermissions(worktreePath)
// Add to .gitignore if worktree is inside repo root
if strings.HasPrefix(worktreePath, repoRoot+string(os.PathSeparator)) {
// Use relative path from repo root for gitignore entry

View file

@ -0,0 +1,99 @@
//go:build !windows
package main
import (
"os"
"path/filepath"
"testing"
)
// TestRepairWorktreeBeadsPermissions is the regression for GH#3593: after worktree
// creation, permissive .beads/ (e.g. 0755 from checkout + umask) must be repaired to 0700.
func TestRepairWorktreeBeadsPermissions(t *testing.T) {
tmp := t.TempDir()
worktreePath := filepath.Join(tmp, "demo-wt")
beadsDir := filepath.Join(worktreePath, ".beads")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatalf("mkdir .beads: %v", err)
}
if err := os.Chmod(beadsDir, 0o755); err != nil {
t.Fatalf("chmod .beads: %v", err)
}
saveJSON := jsonOutput
jsonOutput = true // suppress stderr from repair helper
t.Cleanup(func() { jsonOutput = saveJSON })
repairWorktreeBeadsPermissions(worktreePath)
info, err := os.Stat(beadsDir)
if err != nil {
t.Fatalf("stat .beads: %v", err)
}
if got := info.Mode().Perm(); got != 0o700 {
t.Fatalf(".beads permissions = %04o, want 0700", got)
}
}
func TestRepairWorktreeBeadsPermissionsRejectsSymlink(t *testing.T) {
tmp := t.TempDir()
worktreePath := filepath.Join(tmp, "demo-wt")
if err := os.Mkdir(worktreePath, 0o755); err != nil {
t.Fatalf("mkdir worktree: %v", err)
}
target := filepath.Join(tmp, "target")
if err := os.Mkdir(target, 0o755); err != nil {
t.Fatalf("mkdir target: %v", err)
}
if err := os.Chmod(target, 0o755); err != nil {
t.Fatalf("chmod target: %v", err)
}
if err := os.Symlink(target, filepath.Join(worktreePath, ".beads")); err != nil {
t.Fatalf("symlink .beads: %v", err)
}
suppressRepairOutput(t)
repairWorktreeBeadsPermissions(worktreePath)
info, err := os.Stat(target)
if err != nil {
t.Fatalf("stat target: %v", err)
}
if got := info.Mode().Perm(); got != 0o755 {
t.Fatalf("symlink target permissions = %04o, want unchanged 0755", got)
}
}
func TestRepairWorktreeBeadsPermissionsRejectsNonDirectory(t *testing.T) {
tmp := t.TempDir()
worktreePath := filepath.Join(tmp, "demo-wt")
if err := os.Mkdir(worktreePath, 0o755); err != nil {
t.Fatalf("mkdir worktree: %v", err)
}
beadsPath := filepath.Join(worktreePath, ".beads")
if err := os.WriteFile(beadsPath, []byte("not a directory"), 0o755); err != nil {
t.Fatalf("write .beads: %v", err)
}
if err := os.Chmod(beadsPath, 0o755); err != nil {
t.Fatalf("chmod .beads: %v", err)
}
suppressRepairOutput(t)
repairWorktreeBeadsPermissions(worktreePath)
info, err := os.Stat(beadsPath)
if err != nil {
t.Fatalf("stat .beads: %v", err)
}
if got := info.Mode().Perm(); got != 0o755 {
t.Fatalf("non-directory .beads permissions = %04o, want unchanged 0755", got)
}
}
func suppressRepairOutput(t *testing.T) {
t.Helper()
saveJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = saveJSON })
}

View file

@ -36,15 +36,48 @@ func CheckBeadsDirPermissions(path string) {
// FixBeadsDirPermissions sets the .beads directory to BeadsDirPerm when it
// has group or world-accessible bits. Returns true if permissions changed.
func FixBeadsDirPermissions(path string) (bool, error) {
info, err := os.Stat(path)
return fixBeadsDirPermissions(path, openBeadsDirHandle)
}
type beadsDirHandle interface {
Stat() (os.FileInfo, error)
Chmod(os.FileMode) error
Close() error
}
func fixBeadsDirPermissions(path string, openDir func(string) (beadsDirHandle, error)) (bool, error) {
info, err := os.Lstat(path)
if err != nil {
return false, nil // directory doesn't exist yet
if os.IsNotExist(err) {
return false, nil // directory doesn't exist yet
}
return false, fmt.Errorf("failed to inspect %s: %w", path, err)
}
if info.Mode()&os.ModeSymlink != 0 {
return false, fmt.Errorf("refusing to chmod %s: path is a symbolic link", path)
}
if !info.IsDir() {
return false, fmt.Errorf("refusing to chmod %s: path is not a directory", path)
}
perm := info.Mode().Perm()
if perm&0077 == 0 {
return false, nil // no group or world-accessible bits
}
if err := os.Chmod(path, BeadsDirPerm); err != nil {
dir, err := openDir(path)
if err != nil {
return false, fmt.Errorf("failed to open %s securely: %w", path, err)
}
defer func() { _ = dir.Close() }()
openedInfo, err := dir.Stat()
if err != nil {
return false, fmt.Errorf("failed to inspect opened directory %s: %w", path, err)
}
if !openedInfo.IsDir() || !os.SameFile(info, openedInfo) {
return false, fmt.Errorf("refusing to chmod %s: path changed during permission repair", path)
}
if err := dir.Chmod(BeadsDirPerm); err != nil {
return false, fmt.Errorf("failed to chmod %s to %04o: %w", path, BeadsDirPerm, err)
}
return true, nil

View file

@ -0,0 +1,70 @@
//go:build linux
package config
import (
"errors"
"os"
"path/filepath"
"testing"
"golang.org/x/sys/unix"
)
func TestFixBeadsDirPermissions_UnreadableDirectory(t *testing.T) {
path := filepath.Join(t.TempDir(), ".beads")
if err := os.Mkdir(path, 0o111); err != nil {
t.Fatal(err)
}
if err := os.Chmod(path, 0o111); err != nil {
t.Fatal(err)
}
fixed, err := FixBeadsDirPermissions(path)
if errors.Is(err, unix.EOPNOTSUPP) {
t.Skip("kernel does not support fchmodat2 with AT_EMPTY_PATH")
}
if err != nil {
t.Fatalf("FixBeadsDirPermissions() error = %v", err)
}
if !fixed {
t.Fatal("expected unreadable insecure directory to be fixed")
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if got := info.Mode().Perm(); got != BeadsDirPerm {
t.Fatalf("permissions after fix = %04o, want %04o", got, BeadsDirPerm)
}
}
func TestLinuxPathDirHandle_ChmodUnreadableDirectory(t *testing.T) {
path := filepath.Join(t.TempDir(), ".beads")
if err := os.Mkdir(path, 0o111); err != nil {
t.Fatal(err)
}
if err := os.Chmod(path, 0o111); err != nil {
t.Fatal(err)
}
handle, err := openBeadsDirPathHandle(path)
if err != nil {
t.Fatalf("openBeadsDirPathHandle() error = %v", err)
}
defer handle.Close()
if err := handle.Chmod(BeadsDirPerm); err != nil {
if errors.Is(err, unix.EOPNOTSUPP) {
t.Skip("kernel does not support fchmodat2 with AT_EMPTY_PATH")
}
t.Fatalf("descriptor chmod error = %v", err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if got := info.Mode().Perm(); got != BeadsDirPerm {
t.Fatalf("permissions after descriptor chmod = %04o, want %04o", got, BeadsDirPerm)
}
}

View file

@ -0,0 +1,40 @@
//go:build linux
package config
import (
"errors"
"os"
"golang.org/x/sys/unix"
)
func openBeadsDirHandle(path string) (beadsDirHandle, error) {
fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_DIRECTORY, 0)
if err == nil {
return os.NewFile(uintptr(fd), path), nil
}
if !errors.Is(err, unix.EACCES) && !errors.Is(err, unix.EPERM) {
return nil, err
}
// O_PATH needs no read permission. Chmod uses fchmodat2 with AT_EMPTY_PATH,
// so the operation remains anchored to this descriptor rather than the path.
return openBeadsDirPathHandle(path)
}
func openBeadsDirPathHandle(path string) (beadsDirHandle, error) {
fd, err := unix.Open(path, unix.O_PATH|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_DIRECTORY, 0)
if err != nil {
return nil, err
}
return &linuxPathDirHandle{File: os.NewFile(uintptr(fd), path)}, nil
}
type linuxPathDirHandle struct {
*os.File
}
func (h *linuxPathDirHandle) Chmod(mode os.FileMode) error {
return unix.Fchmodat(int(h.Fd()), "", uint32(mode.Perm()), unix.AT_EMPTY_PATH)
}

View file

@ -0,0 +1,12 @@
//go:build !windows && !linux
package config
import "os"
// os.Open may follow a path swapped to a symlink on these platforms. The
// caller's descriptor identity check prevents chmod unless it still refers to
// the directory inspected with Lstat.
func openBeadsDirHandle(path string) (beadsDirHandle, error) {
return os.Open(path)
}

View file

@ -4,6 +4,7 @@ package config
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
@ -167,3 +168,161 @@ func TestFixBeadsDirPermissions_Nonexistent(t *testing.T) {
t.Error("expected fixed=false for nonexistent directory")
}
}
func TestFixBeadsDirPermissions_RejectsSymlink(t *testing.T) {
tmp := t.TempDir()
target := filepath.Join(tmp, "target")
if err := os.Mkdir(target, 0o755); err != nil {
t.Fatal(err)
}
link := filepath.Join(tmp, ".beads")
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
fixed, err := FixBeadsDirPermissions(link)
if err == nil {
t.Fatal("expected error for symbolic link")
}
if fixed {
t.Error("expected fixed=false for symbolic link")
}
}
func TestFixBeadsDirPermissions_RejectsNonDirectory(t *testing.T) {
path := filepath.Join(t.TempDir(), ".beads")
if err := os.WriteFile(path, []byte("not a directory"), 0o755); err != nil {
t.Fatal(err)
}
fixed, err := FixBeadsDirPermissions(path)
if err == nil {
t.Fatal("expected error for non-directory")
}
if fixed {
t.Error("expected fixed=false for non-directory")
}
}
func TestFixBeadsDirPermissions_RejectsSymlinkSwap(t *testing.T) {
tmp := t.TempDir()
path := filepath.Join(tmp, ".beads")
if err := os.Mkdir(path, 0o755); err != nil {
t.Fatal(err)
}
if err := os.Chmod(path, 0o755); err != nil {
t.Fatal(err)
}
target := filepath.Join(tmp, "target")
if err := os.Mkdir(target, 0o755); err != nil {
t.Fatal(err)
}
if err := os.Chmod(target, 0o755); err != nil {
t.Fatal(err)
}
fixed, err := fixBeadsDirPermissions(path, func(path string) (beadsDirHandle, error) {
if err := os.Remove(path); err != nil {
t.Fatalf("remove validated directory: %v", err)
}
if err := os.Symlink(target, path); err != nil {
t.Fatalf("replace directory with symlink: %v", err)
}
return openBeadsDirHandle(path)
})
if err == nil {
t.Fatal("expected error when directory is replaced with a symlink")
}
if fixed {
t.Error("expected fixed=false after symlink swap")
}
info, statErr := os.Stat(target)
if statErr != nil {
t.Fatal(statErr)
}
if got := info.Mode().Perm(); got != 0o755 {
t.Fatalf("symlink target permissions = %04o, want unchanged 0755", got)
}
}
func TestFixBeadsDirPermissions_RejectsDirectorySwap(t *testing.T) {
tmp := t.TempDir()
path := filepath.Join(tmp, ".beads")
if err := os.Mkdir(path, 0o755); err != nil {
t.Fatal(err)
}
if err := os.Chmod(path, 0o755); err != nil {
t.Fatal(err)
}
replacement := filepath.Join(tmp, "replacement")
if err := os.Mkdir(replacement, 0o755); err != nil {
t.Fatal(err)
}
if err := os.Chmod(replacement, 0o755); err != nil {
t.Fatal(err)
}
fixed, err := fixBeadsDirPermissions(path, func(path string) (beadsDirHandle, error) {
if err := os.Remove(path); err != nil {
t.Fatalf("remove validated directory: %v", err)
}
if err := os.Rename(replacement, path); err != nil {
t.Fatalf("replace validated directory: %v", err)
}
return openBeadsDirHandle(path)
})
if err == nil {
t.Fatal("expected error when directory is replaced")
}
if fixed {
t.Error("expected fixed=false after directory swap")
}
info, statErr := os.Stat(path)
if statErr != nil {
t.Fatal(statErr)
}
if got := info.Mode().Perm(); got != 0o755 {
t.Fatalf("replacement directory permissions = %04o, want unchanged 0755", got)
}
}
func TestFixBeadsDirPermissions_ChmodUnsupportedLeavesDirectoryUnchanged(t *testing.T) {
path := filepath.Join(t.TempDir(), ".beads")
if err := os.Mkdir(path, 0o755); err != nil {
t.Fatal(err)
}
if err := os.Chmod(path, 0o755); err != nil {
t.Fatal(err)
}
unsupported := errors.New("descriptor chmod unsupported")
fixed, err := fixBeadsDirPermissions(path, func(path string) (beadsDirHandle, error) {
file, openErr := os.Open(path)
if openErr != nil {
return nil, openErr
}
return &chmodErrorHandle{File: file, err: unsupported}, nil
})
if !errors.Is(err, unsupported) {
t.Fatalf("error = %v, want wrapped unsupported error", err)
}
if fixed {
t.Error("expected fixed=false when descriptor chmod is unsupported")
}
info, statErr := os.Stat(path)
if statErr != nil {
t.Fatal(statErr)
}
if got := info.Mode().Perm(); got != 0o755 {
t.Fatalf("permissions after failed descriptor chmod = %04o, want unchanged 0755", got)
}
}
type chmodErrorHandle struct {
*os.File
err error
}
func (h *chmodErrorHandle) Chmod(os.FileMode) error {
return h.err
}