beads/cmd/bd/init_permissions_test.go
Julian Knutsen cdda0dffa5
test(cmd/bd): drop dead unsupported-storage test, CWD-independent bd fallback build, stop BEADS_DIR leaking between in-process runs (#7171)
* test(delete): drop stale TestDeleteIssueUnsupportedStorage

The test asserted that deleteIssue returns "delete operation not supported
by this storage backend" when the global store is nil. That error came
from a type assertion to a deleter interface that a5da57e39 (Phase 7:
remove storage factory/memory backend/provider abstraction) removed:
store is now storage.DoltStorage, whose method set always includes
DeleteIssue, so there is no unsupported backend left to report. With the
assertion gone, the test's nil store is just a nil-interface method call
and panics at deleteIssue, killing the whole cmd/bd test binary.

The nil store is not reachable in production: deleteIssue's only caller
(bd doctor --check=pollution --clean) has already queried the store to
find the issues it deletes. So the test constructs an impossible state
for a removed behavior; delete it rather than reintroduce a dead branch.

No CI lane ran it: it needs the integration tag and a Dolt test server
(testDoltServerPort != 0), and every integration lane that builds
cmd/bd (main.yml integration cmd/bd shards, nightly Full Test Suite,
bazel --config=integration) sets BEADS_TEST_SKIP=dolt, while the
proxied/dolt-server lanes run only their TestProxiedServer*/
TestServerMode* manifests. It only ran in local integration runs with
Docker or a matching dolt.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(cmd/bd): build the fallback bd by package path, independent of CWD

When BEADS_TEST_BD_BINARY is unset, buildEmbeddedBD and its sibling
helpers fall back to `go build -tags gms_pure_go -o X .`, which builds
whatever package is in the process's working directory. That is cmd/bd
only if the first caller of the sync.Once has not chdir'd into a fixture
and the test binary was started in cmd/bd. A precompiled test binary run
from the repo root (the pr-risk pattern) builds the root library package
instead: go writes a non-executable archive to X and the test dies with
"fork/exec .../bd: permission denied" (reproduced with TestEmbeddedCount).

Add goBuildBDCommand: the same non-race -tags gms_pure_go build CI
prebuilds BEADS_TEST_BD_BINARY with, naming
github.com/steveyegge/beads/cmd/bd explicitly and running in cmd/bd's
source directory, resolved at package init (this file's compiled-in path,
else the start-up working directory) before any test can chdir. Use it in
buildEmbeddedBD and the other copies of the pattern (cli_fast,
doctor_repair, explicit_db_nodb, init_permissions, scripttest,
shared_server, buildBDForInitTests); migrationFrontDoorBinary keeps its
untagged cgo build but gets the same package path and directory.
TestGoBuildBDCommandIsCWDIndependent checks it from a chdir'd temp dir
with go list (no link).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(cmd/bd): stop in-process bd from leaking BEADS_DIR into later tests

TestResolvedConfigRepoRoot's two CWD-discovery subtests ("uses local
workspace from subdirectory", "uses worktree fallback when local .beads
is absent") failed in full cmd/bd runs with "no active beads workspace
found" but passed alone. Cause: runBDInProcess / runBDInProcessAllowError
run rootCmd.Execute in the test process, and PersistentPreRun exports the
selected workspace with a raw os.Setenv("BEADS_DIR", ...) that nothing
restores. After any TestCLI_* test, BEADS_DIR still names that test's
since-deleted bd-cli-test-* fixture; FindBeadsDir honors an explicit
BEADS_DIR before walking from CWD, finds nothing there, and reports no
workspace. Minimal repro: -run '^(TestCLI_Ready|TestResolvedConfigRepoRoot)$'.

The leak also broke later TestCLI_* tests themselves: with
-run '^(TestCLI_.*|TestResolvedConfigRepoRoot)$' against a Dolt test
server, failures drop from 47 to 20 with this change and no new ones (the
remaining 20 are leftover cobra flag values between in-process runs, a
separate issue).

- runBDInProcess(AllowError): snapshot os.Environ() around Execute and
  restore exactly the keys it changed (restoreEnvSnapshot).
- TestResolvedConfigRepoRoot: clear BEADS_DIR (t.Setenv) in the two
  subtests that test CWD discovery, so neither a leak nor a developer's
  exported BEADS_DIR decides them.

Not host-specific (HOME, global git config and ceilings play no part),
and CI never saw it: the TestCLI_* leakers need a Dolt test server, and
every CI lane that runs cmd/bd's integration tests sets
BEADS_TEST_SKIP=dolt, so they skip and BEADS_DIR is never set.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(delete): expect storage.ErrNotFound after delete in TestDeleteIssueWrapper

"successful issue deletion" asserted that GetIssue returns (nil, nil)
for a deleted issue; the Dolt store reports a missing issue as
storage.ErrNotFound, so the subtest failed with "GetIssue failed: not
found: issue test-xxx" whenever it ran. Like TestDeleteIssueUnsupportedStorage
it needs the integration tag and a Dolt test server, which no CI lane
provides to cmd/bd (BEADS_TEST_SKIP=dolt), so it rotted unseen.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-03 23:44:37 -07:00

143 lines
4 KiB
Go

//go:build !windows
package main
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
)
var (
initPermissionTestBD string
initPermissionTestBDOnce sync.Once
initPermissionTestBDErr error
)
func buildBDForInitPermissionTests(t *testing.T) string {
t.Helper()
initPermissionTestBDOnce.Do(func() {
prebuilt, err := findPrebuiltBDBinary()
if err != nil {
initPermissionTestBDErr = err
return
}
if prebuilt != "" {
initPermissionTestBD = prebuilt
return
}
tmpDir, err := testTempDir("bd-init-permissions-test-*")
if err != nil {
initPermissionTestBDErr = fmt.Errorf("failed to create temp dir: %w", err)
return
}
initPermissionTestBD = filepath.Join(tmpDir, "bd")
cmd := goBuildBDCommand(initPermissionTestBD)
if out, err := cmd.CombinedOutput(); err != nil {
initPermissionTestBDErr = fmt.Errorf("go build failed: %v\n%s", err, out)
}
})
if initPermissionTestBDErr != nil {
t.Fatalf("failed to build bd binary: %v", initPermissionTestBDErr)
}
return initPermissionTestBD
}
// TestInitRepairsPermissiveBeadsDir is the init-path regression test for
// GH#3391: a pre-existing .beads/ directory with permissive bits
// (e.g. 0755 from a permissive umask) must be repaired to 0700 during
// bd init.
//
// The test creates a real git repo with a pre-existing .beads/ at 0755,
// runs bd init, and asserts that permissions are repaired. The init may
// fail later (e.g. no Dolt server), but the permission fix happens early
// enough that the assertion is valid regardless of exit code.
func TestInitRepairsPermissiveBeadsDir(t *testing.T) {
bdBin := buildBDForInitPermissionTests(t)
repoDir := newGitRepo(t)
beadsDir := filepath.Join(repoDir, ".beads")
if err := os.Mkdir(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads: %v", err)
}
if err := os.Chmod(beadsDir, 0755); err != nil {
t.Fatalf("failed to chmod .beads: %v", err)
}
// Verify starting permissions.
info, err := os.Stat(beadsDir)
if err != nil {
t.Fatal(err)
}
if got := info.Mode().Perm(); got&0007 == 0 {
t.Fatalf("precondition failed: .beads should have world bits, got %04o", got)
}
cmd := exec.Command(bdBin, "init", "--prefix", "bd",
"--non-interactive", "--skip-hooks", "--skip-agents")
cmd.Dir = repoDir
var stderr bytes.Buffer
cmd.Stderr = &stderr
// We don't check the exit code — init may fail later for reasons
// unrelated to permissions (no Dolt, etc.). The permission fix runs
// before database creation.
_ = cmd.Run()
// Assert: permissions must be repaired to the same mode bd uses when
// creating .beads/ itself.
info, err = os.Stat(beadsDir)
if err != nil {
t.Fatalf("Stat(.beads) after init: %v", err)
}
perm := info.Mode().Perm()
if perm != 0700 {
t.Errorf(".beads permissions after init = %04o, want 0700", perm)
}
// Assert: the fix was announced on stderr.
if !strings.Contains(stderr.String(), "Fixed .beads permissions to 0700") {
t.Errorf("expected permission-fix message on stderr, got:\n%s", stderr.String())
}
}
// TestInitPreservesSecureBeadsDir verifies that bd init does NOT touch a
// .beads/ directory that already has secure permissions (0700).
func TestInitPreservesSecureBeadsDir(t *testing.T) {
bdBin := buildBDForInitPermissionTests(t)
repoDir := newGitRepo(t)
beadsDir := filepath.Join(repoDir, ".beads")
if err := os.Mkdir(beadsDir, 0700); err != nil {
t.Fatalf("failed to create .beads: %v", err)
}
cmd := exec.Command(bdBin, "init", "--prefix", "bd",
"--non-interactive", "--skip-hooks", "--skip-agents")
cmd.Dir = repoDir
var stderr bytes.Buffer
cmd.Stderr = &stderr
_ = cmd.Run()
// Permissions should remain 0700.
info, err := os.Stat(beadsDir)
if err != nil {
t.Fatalf("Stat(.beads) after init: %v", err)
}
perm := info.Mode().Perm()
if perm != 0700 {
t.Errorf(".beads permissions after init = %04o, want 0700", perm)
}
// No fix message expected.
if strings.Contains(stderr.String(), "Fixed .beads permissions") {
t.Errorf("unexpected permission-fix message for already-secure .beads/:\n%s", stderr.String())
}
}