* fix(hooks): allowlist prime args and exec os.Executable() in runBdPrime
The agent lifecycle hooks re-execute the bd binary to run `bd prime`
without re-entrant store initialization. runBdPrime built that exec from
os.Args[0] plus a variadic argument list, which static analysis flags as
a command taint surface: nothing structurally prevents a future caller
from passing arbitrary strings into the subprocess.
Harden the seam explicitly:
- validatePrimeArgs refuses anything outside the closed set of hook
flags (only --memories-only is ever passed today) before the
subprocess is built, so a caller can never steer the re-exec.
- resolve the executable with os.Executable() instead of os.Args[0],
so the target binary comes from the kernel's view of this process
rather than from argv.
No behavior change for the two real callers (codex-hook, cursor-hook),
which pass only the allowlisted flag or nothing.
Addresses the Snyk Code static-analysis finding on cmd/bd/agent_hook.go
line 26 as hardening.
* test(hooks): stub the re-exec seam and name the rejected argument
Review follow-up to 3435a5755 (round 1, non-blocking). Two test
robustness fixes:
- primeExecutable becomes an injectable seam (var primeExecutable =
os.Executable). The reject test now overrides it and asserts the
resolver never runs for rejected args, so a future reorder that drops
validatePrimeArgs fails the test instead of live-exec'ing the test
binary into a self-exec chain. No test path can reach
exec.CommandContext anymore, and the resolver error path gains
coverage of its own.
- The rejection tests assert the offender ("--config") rather than the
generic substring, so loosening the allowlist for one flag can no
longer mask another.
Also refreshes the PR-facing wording: os.Executable() is a small,
deliberate behavior delta over os.Args[0] (running binary instead of
per-call PATH lookup), noted in the PR description.
* docs(hooks): keep the nosec invariant text true through the seam
Review round 2, nit 5: the #nosec comment still named os.Executable
directly, but the value now arrives one hop indirect through
primeExecutable. Reword the invariant ("exe comes from primeExecutable,
which is os.Executable in production") so the annotation stays accurate.
Comment-only.
* review: pin the prime re-exec target and harden its resolver
Maintainer review fixes for iteration 1 (adopt-pr #6414).
major (Test Evidence Quality): no test reached the exec construction, so
the change's central claim -- that the *resolved* executable is the exec
target -- was unpinned; a mutant that kept the primeExecutable() call and
exec'd os.Args[0] passed all four new tests. Split the construction out of
the I/O as primeCommand(ctx, args...) (*exec.Cmd, error) and assert
cmd.Path and the full cmd.Args against a stubbed resolver. The sentinel
contains a path separator on purpose: exec.Command only skips LookPath for
names that do, so a bare name would leave cmd.Path host-PATH-dependent.
Verified by mutation -- reverting the exec target to os.Args[0] reds only
the new pin and leaves the original four green.
minor (Architectural Consistency): primeExecutable took one of the three
hardening steps doctor/fix's getBdBinary pairs. Give the production
resolver that precedent's shape -- EvalSymlinks (tolerating failure), a
*.test / .test. base-name refusal so an unstubbed test call fails loudly
instead of fork-bombing, and a validated PATH fallback -- and pin the
refusal the way doctor/fix's own suites pin ErrTestBinary. The residual
resolution trade-off, which the PATH fallback does not cover, is now
stated at the declaration instead of left implicit.
nit (Contract & Interface Fidelity): the #nosec named G702, which is not
the subprocess rule. Name G204 and say plainly that .golangci.yml excludes
it repo-wide, so no reader mistakes the annotation for what keeps lint
green.
Iteration 2 -- prose only, no behaviour change:
minor (Debuggability & Operability): the trade-off paragraph added above
documented a mechanism that does not exist. It said os.Executable "pins
/proc/self/exe", so a bd replaced in place by an ordinary
`go install ./cmd/bd` resolves to a "(deleted)" path the PATH fallback
does not cover, and credited inode pinning for PATH-independence. On Linux
os.Executable ends TrimSuffix(path, " (deleted)")
(os/executable_procfs.go), so no "(deleted)" path ever reaches the
resolver. Measured both cases with a live probe against a running binary:
replaced in place, EvalSymlinks SUCCEEDS and the re-exec runs the
replacement, so the documented breakage does not occur; deleted without
being replaced, EvalSymlinks fails, the tolerated-failure branch keeps the
stale path, and the fallback correctly never runs because os.Executable
returned no error. Re-scope the paragraph to that second case, which is
the real residual gap, and credit PATH-independence to the path containing
a separator -- exec.Command calls LookPath only when
filepath.Base(name) == name.
nit (Test Evidence Quality) declined, recorded so it is not re-litigated:
deleting the EvalSymlinks block leaves the prime selector green, so that
arm is unpinned while the other two red exactly one test each. Pinning it
needs a second production seam var for os.Executable -- the resolver reads
the real one, and under `go test` the .test refusal fires before the
EvalSymlinks result is observable -- which is more machinery than a
best-effort step whose failure is tolerated by design warrants. getBdBinary
has the identical gap, so this is an unclosed class rather than a
regression from this change.
* ci(bazel): make the prime re-exec hardening green on the Bazel lane
This PR was opened against a base that had no Bazel lane. The lane landed in
the base advance since (`.github/workflows/bazel.yml`, generated BUILD files,
and #6871's test-binary work), and it reds this PR in two independent ways.
Both are fixed here; neither is reachable from the PR's original base.
1. `cmd/bd/BUILD.bazel` did not exist at the old base, so gazelle never saw
the new `cmd/bd/agent_hook_test.go` and it is absent from `go_test(bd_test)`
srcs. `make bazel-sync` adds exactly the one line committed here, which is
what bazel.yml's "BUILD files in sync" step checks with `git status`. Of the
24 `cmd/bd/*_test.go` files absent from that list, the other 23 are excluded
by a `//go:build` tag; `agent_hook_test.go` is the only untagged one, and a
whole-tree gazelle run produces no other drift.
2. With the test file declared, `TestResolvePrimeExecutableRefusesTestBinary`
then fails under Bazel: rules_go links the binary as `bd_test`, so the
`.test` name checks never fire and `resolvePrimeExecutable` hands back the
test binary instead of refusing it. This is not just a test artifact — it is
the fork-bomb the refusal exists to prevent, live on the new lane.
`getBdBinary` (cmd/bd/doctor/fix/common.go), the precedent this resolver
deliberately restates, hit the same problem and #6871 (`ae1a493e0`) fixed it
by short-circuiting on `testing.Testing()` before the name checks. This
restates that answer, so the resolver stays arm-for-arm faithful to the
precedent it mirrors; the name checks are kept for `go test -c` binaries run
outside the harness, exactly as upstream keeps them.
Verified: `make bazel-sync` clean; `bazel test //cmd/bd:bd_test` (PR selector)
7/7 PASS where it was 1 FAIL before; `go test ./cmd/bd/` selector 17/17 PASS;
gofmt, `go build ./cmd/...`, `go vet ./cmd/bd/`, and a CGO_ENABLED=0
GOOS=windows vet all clean.
---------
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
166 lines
6.8 KiB
Go
166 lines
6.8 KiB
Go
package main
|
|
|
|
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).
|
|
// Each agent keeps its own event names, input/output schemas, and test stubs, but
|
|
// 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 <name>_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) {
|
|
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(cmd.Args[1:], " "), err, strings.TrimSpace(string(out)))
|
|
}
|
|
return string(out), nil
|
|
}
|
|
|
|
// agentHookMarkerBaseDir returns the cache directory for one-shot
|
|
// post-compaction refresh markers for a given agent (subdir e.g. "codex-hooks").
|
|
// override redirects the location for tests.
|
|
func agentHookMarkerBaseDir(subdir, override string) string {
|
|
if override != "" {
|
|
return override
|
|
}
|
|
if dir, err := os.UserCacheDir(); err == nil && dir != "" {
|
|
return filepath.Join(dir, "beads", subdir)
|
|
}
|
|
return filepath.Join(os.TempDir(), "beads-"+subdir)
|
|
}
|
|
|
|
// agentHookMarkerPath derives a per-session, per-workspace marker file under
|
|
// base so concurrent agent sessions don't clobber each other's state. Empty
|
|
// keys fall back to stable placeholders.
|
|
func agentHookMarkerPath(base, sessionKey, workspaceKey string) string {
|
|
if sessionKey == "" {
|
|
sessionKey = "unknown-session"
|
|
}
|
|
if workspaceKey == "" {
|
|
workspaceKey = "unknown-workspace"
|
|
}
|
|
sum := sha256.Sum256([]byte(sessionKey + "\x00" + filepath.Clean(workspaceKey)))
|
|
return filepath.Join(base, hex.EncodeToString(sum[:])+".refresh")
|
|
}
|
|
|
|
// writeAgentHookMarker creates the marker directory and writes the one-shot
|
|
// refresh marker file.
|
|
func writeAgentHookMarker(path string) error {
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(path, []byte("1\n"), 0o600) // #nosec G306 -- user-private cache marker
|
|
}
|