beads/cmd/bd/backup_restore_test.go
Julian Knutsen c67a36e5e7
fix(cli): refuse backup init/sync/remove/restore and import under strict --readonly (#7673)
* fix(cli): refuse backup init/sync/remove and import under --readonly

Strict --readonly is meant to refuse every command that writes, with
"Error: operation '<op>' is not allowed in read-only mode" and exit 1.
bd backup init, backup sync, backup remove and bd import never called
CheckReadonly, so that gate never refused them:

- On a server-mode store they ran to completion under --readonly:
  backup init and backup remove rewrote or emptied the server's
  dolt_backups registry, backup sync wrote the backup destination, and
  import wrote issues.
- On an embedded store they failed only because the store was opened
  read-only, with the storage layer's "store is read-only" text, and
  backup sync took the backup lock first and left .beads/backup.lock
  behind.

The three backup verbs now call CheckReadonly first in their RunE, as
the other write commands do. Its migration-freeze half is redundant for
them: their leaf names are not on the read-only list and they have no
preview flag, so PersistentPreRunE's early freeze gate refuses them
first.

bd import calls it only when --readonly is set. CheckReadonly also
answers a migration freeze, and does so by exiting the process, while
runImport answers a freeze by returning the error so cleanup still
runs; guarding the call leaves that path exactly as it was.

bd import --dry-run is refused too. The preview opens the store
read-only and writes nothing, so this is a policy choice. It matches
create --dry-run (also refused under --readonly) and import's own
freeze posture: a migration freeze already refuses import --dry-run
(TestImportBlockedDuringMigrationFreeze), and CheckReadonly treats the
two gates as one. The cost is small, since the same preview runs
without --readonly. bd backup status and bd backup itself (a command
group that only prints help) stay allowed.

TestBackupAndImportBlockedInReadonlyMode runs each command, plus
import --dry-run, under --readonly and --readonly --sandbox against an
embedded workspace and one on the Dolt test server. Each row expects
exit 1, exactly the standard refusal on stderr, an empty stdout, and
nothing changed: the .beads tree, the backup destination, the issue
count, and, in server mode, the dolt_backups registry.
TestBackupStatusAndListWorkInReadonlyMode is the control showing that
backup status and list still run.

Ported from the versioned-beads fork: b86df6a9eb (test) and
5a067acc56 (fix). The comment on TestImportBlockedDuringMigrationFreeze
is updated, since runImport now calls CheckReadonly under --readonly.

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(backup): refuse --readonly backup restore before the exclusive gate

A restore replaces the store, so strict --readonly must refuse it.
Nothing did:

- In server mode no storage layer stops the connection, so
  `bd --readonly backup restore --force` ran to the end: exit 0,
  "Restore complete", and the store was replaced.
- In embedded mode the command took the EXCLUSIVE workspace gate first,
  leaving the holder sidecars (.beads.gate.lock.info,
  .beads/embeddeddolt.gate.lock.info) behind, and was stopped only
  later by the storage layer's "store is read-only".

acquireCommandWorkspaceGates now calls CheckReadonly("backup restore")
first for the exclusive (restore) case when readonlyMode is set. That
is before any gate file is created or the store is opened, so nothing
is held and the exit skips no release. The guard checks readonlyMode
alone, so a restore without --readonly, including one refused by a
migration freeze, keeps its existing order. The restore RunE also calls
CheckReadonly first, as every write command does.

This does not depend on the strict-readonly SHARED-gate change
(workspacegate.Options.ReadOnly): the refusal comes before any gate is
built.

The one visible change in proxied-server mode, where every --readonly
command is already refused: `bd --readonly backup restore` now gets
this standard refusal (plain text, exit 1). Before, the proxy
capability refusal answered it (exit 1, typed JSON under --json), and
only after the exclusive gate had been taken.

TestEmbeddedBackupRestoreStrictReadonly and
TestBackupRestoreStrictReadonlyServerMode run the built bd as a
subprocess, because CheckReadonly exits. The workspace's live store
holds three issues and its backup holds two. Each test asserts the
standard refusal with exit 1 and an empty stdout, no storage-layer
message, an unchanged project directory and .beads tree, and an
unchanged issue count. Each runs under --readonly and under
--readonly --sandbox. A control restores without --readonly and
expects two issues, so "unchanged" cannot be vacuous.

Ported from the versioned-beads fork: 1cd5f1c202 (test) and
6ac79d6207 (fix). The fork's test used a dirEntryNames helper that
belongs to its separate SHARED-gate change. It is inlined here so this
change compiles and lands on its own in either order. The server test's
comment is corrected too: the fixture's backup and the restore both run
inside the server at the same path, so it passes against a
containerized test server as well as a local one.

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 08:48:37 +00:00

348 lines
12 KiB
Go

//go:build cgo
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/testutil"
"github.com/steveyegge/beads/internal/types"
)
func TestBackupRestoreMissingDir(t *testing.T) {
if testDoltServerPort == 0 {
t.Skip("Dolt test server not available")
}
if testutil.DoltContainerCrashed() {
t.Skipf("Dolt test server crashed: %v", testutil.DoltContainerCrashError())
}
ensureTestMode(t)
dbName := uniqueTestDBName(t)
testDBPath := filepath.Join(t.TempDir(), "dolt")
writeTestMetadata(t, testDBPath, dbName)
s := newTestStoreWithPrefix(t, testDBPath, "dn")
t.Cleanup(func() { _ = s.Close() })
ctx := context.Background()
err := runBackupRestore(ctx, s, "/nonexistent/path", false)
if err == nil {
t.Error("expected error for nonexistent backup dir")
}
}
func TestSyncProjectIDFromDB_NoWorkspaceUsesActiveWorkspaceError(t *testing.T) {
if testDoltServerPort == 0 {
t.Skip("Dolt test server not available")
}
if testutil.DoltContainerCrashed() {
t.Skipf("Dolt test server crashed: %v", testutil.DoltContainerCrashError())
}
ensureTestMode(t)
ctx := context.Background()
repoDir := t.TempDir()
testDBPath := filepath.Join(repoDir, ".beads", "beads.db")
s := newTestStoreWithPrefix(t, testDBPath, "bp")
t.Cleanup(func() { _ = s.Close() })
if err := s.SetMetadata(ctx, "_project_id", "project-123"); err != nil {
t.Fatalf("SetMetadata(_project_id): %v", err)
}
noWorkspaceDir := t.TempDir()
t.Chdir(noWorkspaceDir)
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_DB", "")
beads.ResetCaches()
git.ResetCaches()
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
err := syncProjectIDFromDB(ctx, s)
if err == nil {
t.Fatal("expected syncProjectIDFromDB to fail without an active workspace")
}
if !strings.Contains(err.Error(), activeWorkspaceNotFoundError()) {
t.Fatalf("syncProjectIDFromDB error = %q, want active workspace wording", err)
}
if !strings.Contains(err.Error(), diagHint()) {
t.Fatalf("syncProjectIDFromDB error = %q, want diag hint", err)
}
if _, statErr := os.Stat(filepath.Join(noWorkspaceDir, ".beads")); !os.IsNotExist(statErr) {
t.Fatalf("syncProjectIDFromDB should not create local .beads, stat err = %v", statErr)
}
}
// strictReadonlyRestoreRefusal is the line CheckReadonly prints when a write
// command is run under strict --readonly.
const strictReadonlyRestoreRefusal = "Error: operation 'backup restore' is not allowed in read-only mode\n"
// assertStrictReadonlyRestoreRefused checks one refused `bd --readonly backup
// restore` run: the standard CheckReadonly refusal (text and exit code), nothing
// on stdout, and none of the storage-layer message that embedded mode gives when
// the command gets past CheckReadonly and opens the store.
func assertStrictReadonlyRestoreRefused(t *testing.T, stdout, stderr string, code int) {
t.Helper()
if code != 1 {
t.Errorf("exit code = %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
if !strings.Contains(stderr, strictReadonlyRestoreRefusal) {
t.Errorf("stderr is missing the standard refusal %q:\n%s", strictReadonlyRestoreRefusal, stderr)
}
if strings.Contains(stderr, "embeddeddolt: store is read-only") {
t.Errorf("stderr carries the storage-layer refusal, so the command opened the store before being refused:\n%s", stderr)
}
if strings.TrimSpace(stdout) != "" {
t.Errorf("stdout should be empty when the restore is refused, got:\n%s", stdout)
}
}
// workspaceSnapshot is what a refused command must leave alone: the entries of
// the project directory (the workspace gate file and its holder sidecar sit
// beside .beads, not in it) and everything below .beads, content included.
type workspaceSnapshot struct {
projectEntries []string
beads readonlyTreeSnapshot
}
func snapshotWorkspace(t *testing.T, dir string) workspaceSnapshot {
t.Helper()
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
names := make([]string, 0, len(entries))
for _, e := range entries {
names = append(names, e.Name())
}
return workspaceSnapshot{
projectEntries: names,
beads: snapshotReadonlyTree(t, filepath.Join(dir, ".beads")),
}
}
// assertWorkspaceUnchanged fails, naming each path, when the workspace under dir
// no longer matches a snapshot taken before a refused command.
func assertWorkspaceUnchanged(t *testing.T, dir string, before workspaceSnapshot) {
t.Helper()
after := snapshotWorkspace(t, dir)
var diffs []string
for _, name := range before.projectEntries {
if !slices.Contains(after.projectEntries, name) {
diffs = append(diffs, "removed: "+name)
}
}
for _, name := range after.projectEntries {
if !slices.Contains(before.projectEntries, name) {
diffs = append(diffs, "created: "+name)
}
}
for path, want := range before.beads.Entries {
switch got, ok := after.beads.Entries[path]; {
case !ok:
diffs = append(diffs, "removed: .beads/"+path)
case got != want:
diffs = append(diffs, "changed: .beads/"+path)
}
}
for path := range after.beads.Entries {
if _, ok := before.beads.Entries[path]; !ok {
diffs = append(diffs, "created: .beads/"+path)
}
}
if len(diffs) == 0 {
return
}
sort.Strings(diffs)
const show = 20
if len(diffs) > show {
diffs = append(diffs[:show], fmt.Sprintf("... and %d more", len(diffs)-show))
}
t.Errorf("the refused restore changed the workspace:\n%s", strings.Join(diffs, "\n"))
}
// TestBackupRestoreStrictReadonlyServerMode is the server-mode counterpart of
// TestEmbeddedBackupRestoreStrictReadonly. Server mode is where the missing
// refusal mattered: no storage layer stops a server connection, so a
// `bd --readonly backup restore --force` ran to the end and replaced the store.
// It drives the built bd as a subprocess because CheckReadonly exits the
// process. Both the fixture's backup and the restore run inside the Dolt
// server, against the same path on the server's own filesystem, so a local
// and a containerized test server both serve.
func TestBackupRestoreStrictReadonlyServerMode(t *testing.T) {
if testDoltServerPort == 0 {
t.Skip("Dolt test server not available")
}
if testutil.DoltContainerCrashed() {
t.Skipf("Dolt test server crashed: %v", testutil.DoltContainerCrashError())
}
bd := buildBDForInitTests(t)
// newWorkspace builds a server-mode workspace on the test server whose live
// store holds one issue its backup does not (three against two), so a restore
// that really ran shows up as a changed issue count. Each case gets its own: a
// restore that runs replaces the store and would hide a leak from the next.
newWorkspace := func(t *testing.T) (dir string, env []string, backupDir string) {
t.Helper()
dir = t.TempDir()
beadsDir := filepath.Join(dir, ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatal(err)
}
database := uniqueTestDBName(t)
if err := (&configfile.Config{
Backend: configfile.BackendDolt,
DoltMode: configfile.DoltModeServer,
DoltServerHost: "127.0.0.1",
DoltServerPort: testDoltServerPort,
DoltDatabase: database,
}).Save(beadsDir); err != nil {
t.Fatalf("save workspace metadata: %v", err)
}
ctx := context.Background()
seedStore, err := dolt.New(ctx, &dolt.Config{
Path: filepath.Join(beadsDir, "dolt"),
BeadsDir: beadsDir,
ServerHost: "127.0.0.1",
ServerPort: testDoltServerPort,
Database: database,
CreateIfMissing: true,
})
if err != nil {
t.Fatalf("create the server-mode database: %v", err)
}
t.Cleanup(func() { dropTestDatabase(database, testDoltServerPort) })
defer func() { _ = seedStore.Close() }()
if err := seedStore.SetConfig(ctx, "issue_prefix", "rr"); err != nil {
t.Fatalf("set issue_prefix: %v", err)
}
seed := func(id, title string) {
t.Helper()
now := time.Now()
issue := &types.Issue{
ID: id,
Title: title,
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
CreatedAt: now,
UpdatedAt: now,
}
if err := seedStore.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("create issue %s: %v", id, err)
}
}
commit := func(message string) {
t.Helper()
if err := seedStore.Commit(ctx, message); err != nil && !strings.Contains(err.Error(), "nothing to commit") {
t.Fatalf("commit %q: %v", message, err)
}
}
seed("rr-1", "issue in the backup A")
seed("rr-2", "issue in the backup B")
commit("issues the backup holds")
backupDir = filepath.Join(t.TempDir(), "dolt-backup")
if err := os.MkdirAll(backupDir, 0o750); err != nil {
t.Fatal(err)
}
if err := seedStore.BackupDatabase(ctx, backupDir); err != nil {
t.Fatalf("back up the database (the Dolt server must be able to write %s): %v", backupDir, err)
}
seed("rr-3", "issue created after the backup")
commit("issue the backup lacks")
env = []string{
"BEADS_TEST_MODE=1",
// The subprocess connects to a testdb_* database on the test server;
// this is the opt-in the test-database firewall asks for.
"BEADS_TEST_SERVER=1",
"BEADS_DIR=" + beadsDir,
"XDG_CONFIG_HOME=" + t.TempDir(),
// Keep the subprocess's circuit-breaker state in the suite's own
// directory rather than the host's temp dir.
"BEADS_TEST_CIRCUIT_DIR=" + os.Getenv("BEADS_TEST_CIRCUIT_DIR"),
}
return dir, env, backupDir
}
issueCount := func(t *testing.T, dir string, env []string) int {
t.Helper()
stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, env, "list", "--json")
if code != 0 {
t.Fatalf("bd list --json exited %d\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
start := strings.Index(stdout, "[")
if start < 0 {
t.Fatalf("no JSON array in bd list --json output:\n%s", stdout)
}
var issues []json.RawMessage
if err := json.Unmarshal([]byte(stdout[start:]), &issues); err != nil {
t.Fatalf("parse bd list --json output: %v\n%s", err, stdout)
}
return len(issues)
}
// The control proves the fixture really does restore when --readonly is not
// asked for, so "the store is unchanged" below cannot be vacuous.
t.Run("control_restore_without_readonly", func(t *testing.T) {
dir, env, backupDir := newWorkspace(t)
stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, env, "backup", "restore", "--force", backupDir)
if code != 0 {
t.Fatalf("restore without --readonly exited %d\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
if !strings.Contains(stdout, "Restore complete") {
t.Errorf("stdout is missing %q:\n%s", "Restore complete", stdout)
}
if got := issueCount(t, dir, env); got != 2 {
t.Errorf("issue count after a real restore = %d, want 2: the backup holds two issues and the live store held three", got)
}
})
for _, tc := range []struct {
name string
flags []string
}{
{"readonly", []string{"--readonly"}},
{"readonly_sandbox", []string{"--readonly", "--sandbox"}},
} {
t.Run(tc.name, func(t *testing.T) {
dir, env, backupDir := newWorkspace(t)
before := snapshotWorkspace(t, dir)
args := append(append([]string{}, tc.flags...), "backup", "restore", "--force", backupDir)
stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, env, args...)
assertStrictReadonlyRestoreRefused(t, stdout, stderr, code)
assertWorkspaceUnchanged(t, dir, before)
if got := issueCount(t, dir, env); got != 3 {
t.Errorf("issue count after the refused restore = %d, want 3: the restore replaced the store", got)
}
})
}
}