diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index 779633994..c920700ef 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -488,6 +488,7 @@ go_test( "aaa_stdio_baseline_test.go", "actor_test.go", "ado_test.go", + "agent_hook_test.go", "assign_fence_embedded_test.go", "assign_fence_proxied_test.go", "auto_import_upgrade_test.go", diff --git a/cmd/bd/agent_hook.go b/cmd/bd/agent_hook.go index 9cb3a0cb6..f37684e9c 100644 --- a/cmd/bd/agent_hook.go +++ b/cmd/bd/agent_hook.go @@ -4,11 +4,13 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "fmt" "os" "os/exec" "path/filepath" "strings" + "testing" ) // Shared helpers for the agent lifecycle hook commands (codex-hook, cursor-hook). @@ -16,17 +18,113 @@ import ( // the prime-runner and one-shot refresh-marker mechanics are identical and live // here to avoid divergence. +// allowedPrimeArgs is the closed set of flags the agent hooks may pass to the +// re-executed bd binary. The hooks only ever run the fixed `bd prime` +// invocation (optionally --memories-only); anything else is a programming +// error and is refused before the subprocess is built. +var allowedPrimeArgs = map[string]bool{"--memories-only": true} + +// errPrimeTestBinary is returned by resolvePrimeExecutable when the running +// binary is a test binary. Mirrors doctor/fix's ErrTestBinary: re-execing a +// test binary with `prime` fork-bombs the suite. +var errPrimeTestBinary = errors.New("running as test binary - cannot re-exec bd") + +// primeExecutable resolves the re-exec target for runBdPrime. A var so tests +// can stub resolution and prove no subprocess is ever built from unexpected +// input. +var primeExecutable = resolvePrimeExecutable + +// resolvePrimeExecutable is the production re-exec resolver. It restates +// getBdBinary (cmd/bd/doctor/fix/common.go), the repo's existing answer to "bd +// re-invokes bd": prefer the running binary, resolve symlinks so every re-exec +// site agrees on one path, refuse a test binary so an unstubbed test call +// fails loudly instead of fork-bombing, and fall back to a validated PATH +// lookup when the running binary cannot be resolved. getBdBinary is +// package-private to doctor/fix, so this restates the precedent rather than +// reusing it. +// +// One trade-off is kept deliberately, and it is narrower than it looks. Linux +// reports an unlinked image with a " (deleted)" suffix, but os.Executable +// strips that suffix (os/executable_procfs.go), so no "(deleted)" path ever +// reaches this resolver: a bd replaced in place mid-session (an ordinary +// `go install ./cmd/bd`) still resolves to its own path, EvalSymlinks succeeds +// against the new file, and the re-exec runs the replacement. The residual gap +// is a bd deleted without being replaced: EvalSymlinks fails, that failure is +// tolerated so the stale path is kept, and the PATH fallback is correctly not +// taken because os.Executable itself returned no error. Accepted: the target is +// PATH-independent because it contains a path separator (exec.Command calls +// LookPath only when filepath.Base(name) == name), and both hook handlers treat +// a prime failure as non-fatal, so the effect is a session primed without +// context. +func resolvePrimeExecutable() (string, error) { + exe, err := os.Executable() + if err == nil { + if resolved, linkErr := filepath.EvalSymlinks(exe); linkErr == nil { + exe = resolved + } + // testing.Testing() is the authoritative signal and must come first: + // rules_go links test binaries as _test (cmd/bd's is bd_test), + // which no ".test" name check can see, so under the Bazel lane the + // name checks alone would let an unstubbed call re-exec the test + // binary. The name checks remain for binaries built with `go test -c` + // and run outside the harness. Mirrors doctor/fix's isTestBinary. + base := filepath.Base(exe) + if testing.Testing() || strings.HasSuffix(base, ".test") || strings.Contains(base, ".test.") { + return "", errPrimeTestBinary + } + return exe, nil + } + + bdPath, lookErr := exec.LookPath("bd") + if lookErr != nil { + return "", fmt.Errorf("bd binary not found in PATH: %w", lookErr) + } + return bdPath, nil +} + +// validatePrimeArgs rejects any argument outside allowedPrimeArgs so the +// re-exec below can never be steered by caller-supplied strings. +func validatePrimeArgs(args []string) error { + for _, arg := range args { + if !allowedPrimeArgs[arg] { + return fmt.Errorf("bd prime: unsupported hook argument %q", arg) + } + } + return nil +} + +// primeCommand validates args, resolves the re-exec target, and builds the +// `bd prime [args...]` command without running it. Split out from runBdPrime +// so a test can assert the exec target and argv — the thing this seam exists +// to guarantee — without launching a subprocess. +func primeCommand(ctx context.Context, args ...string) (*exec.Cmd, error) { + if err := validatePrimeArgs(args); err != nil { + return nil, err + } + exe, err := primeExecutable() + if err != nil { + return nil, fmt.Errorf("bd prime: resolve executable: %w", err) + } + cmdArgs := append([]string{"prime"}, args...) + // #nosec G204 - exe comes from primeExecutable (resolvePrimeExecutable in + // production: this bd binary re-invoking itself); cmdArgs is the fixed + // "prime" subcommand plus allowlisted internal flags, never + // attacker-controlled input. Documentation only: .golangci.yml excludes + // G204 repo-wide, so this annotation is not what keeps lint green. + return exec.CommandContext(ctx, exe, cmdArgs...), nil +} + // runBdPrime shells out to `bd prime [args...]` and returns its combined output. // The hooks exec a subprocess (rather than calling prime in process) to avoid // re-entrant store initialization. func runBdPrime(ctx context.Context, args ...string) (string, error) { - cmdArgs := append([]string{"prime"}, args...) - // #nosec G702 - os.Args[0] is this bd binary re-invoking itself; cmdArgs is the - // fixed "prime" subcommand plus internal flags, never attacker-controlled input. - cmd := exec.CommandContext(ctx, os.Args[0], cmdArgs...) + cmd, err := primeCommand(ctx, args...) + if err != nil { + return "", err + } out, err := cmd.CombinedOutput() if err != nil { - return "", fmt.Errorf("bd %s: %w: %s", strings.Join(cmdArgs, " "), err, strings.TrimSpace(string(out))) + return "", fmt.Errorf("bd %s: %w: %s", strings.Join(cmd.Args[1:], " "), err, strings.TrimSpace(string(out))) } return string(out), nil } diff --git a/cmd/bd/agent_hook_test.go b/cmd/bd/agent_hook_test.go new file mode 100644 index 000000000..3c1d361a1 --- /dev/null +++ b/cmd/bd/agent_hook_test.go @@ -0,0 +1,131 @@ +package main + +import ( + "context" + "errors" + "slices" + "strings" + "testing" +) + +func TestValidatePrimeArgsAcceptsHookFlags(t *testing.T) { + if err := validatePrimeArgs(nil); err != nil { + t.Fatalf("no args should be allowed, got %v", err) + } + if err := validatePrimeArgs([]string{"--memories-only"}); err != nil { + t.Fatalf("--memories-only should be allowed, got %v", err) + } +} + +func TestValidatePrimeArgsRejectsUnknownFlag(t *testing.T) { + err := validatePrimeArgs([]string{"--config"}) + if err == nil { + t.Fatal("expected unknown flag to be rejected") + } + if !strings.Contains(err.Error(), `"--config"`) { + t.Fatalf("rejection should name the offending argument, got: %v", err) + } +} + +// runBdPrime must refuse non-allowlisted arguments before it resolves the +// executable or builds a subprocess. The resolver is stubbed so the test also +// proves validation runs first — if a future change drops or reorders the +// validatePrimeArgs call, the resolver (and with it the subprocess) would be +// reached and this test fails instead of live-exec'ing anything. +func TestRunBdPrimeRejectsUnknownArgsBeforeExec(t *testing.T) { + called := false + orig := primeExecutable + primeExecutable = func() (string, error) { + called = true + return "", errors.New("resolver must not run for rejected args") + } + t.Cleanup(func() { primeExecutable = orig }) + + _, err := runBdPrime(context.Background(), "--config") + if err == nil { + t.Fatal("expected runBdPrime to reject unknown args") + } + if !strings.Contains(err.Error(), `"--config"`) { + t.Fatalf("rejection should name the offending argument, got: %v", err) + } + if called { + t.Fatal("executable resolver ran before argument validation") + } +} + +// With allowlisted args, a resolver failure surfaces as the wrapped +// resolve-executable error and no subprocess is built. +func TestRunBdPrimeExecutableResolutionError(t *testing.T) { + orig := primeExecutable + primeExecutable = func() (string, error) { + return "", errors.New("no executable") + } + t.Cleanup(func() { primeExecutable = orig }) + + _, err := runBdPrime(context.Background()) + if err == nil || !strings.Contains(err.Error(), "resolve executable") { + t.Fatalf("want resolve-executable error, got: %v", err) + } +} + +// The point of the seam: the command must be built from the *resolved* +// executable, not from os.Args[0]. primeCommand builds without running, so +// this asserts the exec target and the full argv directly. The sentinel +// deliberately contains a path separator — exec.Command only skips LookPath +// for names that do, so a bare name would leave cmd.Path host-PATH-dependent +// and set cmd.Err, making the assertion vacuous. +func TestPrimeCommandUsesResolvedExecutable(t *testing.T) { + const sentinel = "/tmp/beads-prime-sentinel-bd" + + orig := primeExecutable + primeExecutable = func() (string, error) { return sentinel, nil } + t.Cleanup(func() { primeExecutable = orig }) + + cmd, err := primeCommand(context.Background(), "--memories-only") + if err != nil { + t.Fatalf("primeCommand with allowlisted args: %v", err) + } + if cmd.Err != nil { + t.Fatalf("separator-containing sentinel should build cleanly, got cmd.Err=%v", cmd.Err) + } + if cmd.Path != sentinel { + t.Fatalf("exec target should be the resolved executable %q, got %q", sentinel, cmd.Path) + } + want := []string{sentinel, "prime", "--memories-only"} + if !slices.Equal(cmd.Args, want) { + t.Fatalf("argv should be %q, got %q", want, cmd.Args) + } +} + +// primeCommand refuses non-allowlisted args before resolving, and returns no +// command to run. +func TestPrimeCommandRejectsUnknownArgs(t *testing.T) { + orig := primeExecutable + primeExecutable = func() (string, error) { + return "", errors.New("resolver must not run for rejected args") + } + t.Cleanup(func() { primeExecutable = orig }) + + cmd, err := primeCommand(context.Background(), "--config") + if err == nil { + t.Fatal("expected primeCommand to reject unknown args") + } + if cmd != nil { + t.Fatalf("rejected args must not yield a command, got %v", cmd.Args) + } +} + +// The production resolver refuses a test binary rather than handing back a +// path whose re-exec would fork-bomb the suite — the guard doctor/fix's +// getBdBinary pairs with os.Executable. Under `go test` the running binary is +// the package test binary, so this exercises the refusal directly, the same +// way cmd/bd/doctor/fix's own suites assert ErrTestBinary. +func TestResolvePrimeExecutableRefusesTestBinary(t *testing.T) { + path, err := resolvePrimeExecutable() + if !errors.Is(err, errPrimeTestBinary) { + t.Fatalf("want errPrimeTestBinary under go test, got path=%q err=%v", path, err) + } + if path != "" { + t.Fatalf("refusal must not return a path, got %q", path) + } +}