beads/cmd/bd/proxy_capability_test.go
Julian Knutsen a4c47ccfdf
fix(schema,uow): route the proxied data-behind open to the #6575 stop (port of #6695 to main) (#7481)
* fix(schema,uow): route the proxied data-behind open to the #6575 stop with topology-correct guidance (port of #6695)

Port of the release/1.3.x commit bb03a310a9 (PR #6695) to main, where it
never landed: v1.3.1 is cut from a release branch that is not an ancestor
of main.

The proxied / `bd serve` open path never reached the #6575 data-behind
stop. doltSQLProvider.initSchemaAttempt passed a nil adopter to
CheckSharedStoreMigrateGate, so localDataBehind short-circuited and the
router could never emit smartDataBehind. A proxied store that was level
on schema and behind in data reported `shared-store` instead, whose body
is the designated-migrator recipe -- `bd migrate --force` then
`bd dolt push` -- which in that state is exactly the #6368 wedge the
stop exists to prevent. The refusal was always safe (the shared arm
suppresses the auto-migrate either way); the guidance was not.

- uow: wire a dataBehindAdopter with AheadBehind only
  (versioncontrolops.LocalAheadBehind). IsStrictAncestor/WorkingSetClean
  stay nil so the remote-ahead arm keeps its plain adopt directive, and
  FastForward stays nil because it would promote the schema for every
  co-resident client. Read-only proxied opens print the pull-first block
  instead of the shared-consent template.
- uow.WithProxiedServerMode(), set only by openProxiedServerUOWProvider,
  marks the refusal Proxied: the same provider serves `bd serve` on a
  SERVER-mode workspace, where `bd dolt pull` works.
- schema: a Proxied refusal names the server host as where the pull runs
  (`bd dolt pull` is refused at the proxied front door,
  proxy.dolt_pull.unsupported), the option id becomes
  pull-first-on-server-host, and the guidance says the forced
  `bd migrate schema --force` consent step IS runnable from the proxied
  workspace (the capability registry permits `migrate schema`), so it must
  wait for the pull, and that BD_ALLOW_REMOTE_MIGRATE=1 is reachable too.
- cmd/bd: the --json `expected` field carries the same location
  qualifier (dataBehindExpectedField).

Not ported, because main already has it: the release PR's F-B half (the
shared data-behind consent step naming `bd migrate schema --force` and
its --global twin, the printGlobalDatabaseConsentHint retarget, and the
shared_migrate_consent_test.go changes) landed on main as #6692.
Adapted to main: the release line's proxyMaintenanceRefusals table is
main's capability registry, so TestProxyMaintenanceAllowsTheSharedConsentVerb
drives validateProxyRegistryBeforeProvider for every proxied topology and
also pins that `bd dolt pull` and the bare `bd migrate` are refused; the
CHANGELOG paragraph is appended to main's existing #6575 entry.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(upgrading): where the proxied data-behind pull runs; pin its plumbing

Review fixes for the proxied data-behind stop: the one major of review
attempt 1, the cheap minors, and the nit, plus the wording minor of
attempt 2.

- Clone behind the remote, the docs section the gate's payload links
  to, prescribed `bd dolt pull` with no topology qualifier: the remedy a
  proxied-server workspace refuses at its front door. Its intro now says
  so, and a proxied-server step pair puts the pull (and any conflict
  resolution) on the server host, from a workspace with direct database
  access, then `bd migrate schema --force` in the proxied workspace. It
  also warns that nothing there enforces that order: `--force` and
  BD_ALLOW_REMOTE_MIGRATE=1 are honored before the stop is reached, so
  the stop never sees them. The warning ends on the payload's own
  instruction, not to reach for either to get past the stop, rather than
  a negation ("neither is a way past it") that read as the topology
  blocking the wedge. The pending-migration exception above the section,
  the proxied-server list under Shared servers (now three differences)
  and the init-safety ordering rule say the same. The heading, and with
  it the anchor the gate links, is unchanged.
- The option plumbing that carries the fix is pinned link by link.
  TestApplyProviderOptions covers WithProxiedServerMode (it sets that
  field and no open posture). The cmd/bd append moves into
  proxiedProviderOptions, which TestProxiedProviderOptions holds to
  exactly one added option on a fresh slice. And
  TestNewDoltServerUOWProvider_CarriesProxiedServerMode opens two real
  providers on one server, with and without the option, and reads the
  field the gate copies; openAndInitSchema's provider literal and the
  shared test open helpers are left as they were.
- TestProxyMaintenanceAllowsTheSharedConsentVerb also pins `bd dolt
  push` and `bd conflicts resolve` as refused, the rest of the list the
  proxied refusal body recites. `dolt push` is refused as unimplemented,
  the kind of row that flips to allowed once a route lands.
- localDataBehind's doc comment is re-wrapped so the IsStrictAncestor
  sentence no longer breaks across the inserted parenthetical.
- The CHANGELOG entry notes the docs change.

Each new pin is red with its link reverted: the option dropped from the
cmd/bd append, the append made in place, the field copy deleted from
the provider literal, the constructor dropping its options, the option
also setting preview, and the push and conflicts codes changed. Still
unpinned: which option the cmd/bd append adds (options are opaque
outside uow) and that `bd serve`'s server-mode open passes none; both
need a seam in cmd/bd.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-10-11 00:23:25 +00:00

920 lines
35 KiB
Go

package main
import (
"bytes"
"encoding/json"
"errors"
"maps"
"os"
"slices"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/storage/schema"
)
// TestProxyMaintenanceAllowsTheSharedConsentVerb pins the capability facts the
// #6575 proxied data-behind guidance is written against: the consent command
// that guidance prescribes is NOT refused at the proxied front door, while the
// bare `bd migrate` verb, the `bd dolt pull` remedy and the other refusals the
// guidance names (`bd dolt push`, `bd conflicts`) are.
//
// The capability registry keys on the full command path. It refuses the bare
// `migrate` verb and `migrate hooks` / `migrate issues` / `migrate sync`, but
// permits `migrate schema` — so that path passes
// validateProxyRegistryBeforeProvider and reaches `bd migrate schema`'s own
// proxied arm, which reports the migration the provider open already applied
// under this verb's consent.
//
// An earlier revision of that guidance asserted the opposite on three runtime
// surfaces and nothing failed, because no test called the front door with this
// command. The wording is not cosmetic: forceOrEnvConsent honors `--force`
// BEFORE the data-behind stop is routed, so an operator told "it is refused
// here anyway" who types it to confirm takes the exact wedge the stop exists
// to prevent.
//
// The command is resolved from the constant the gate prescribes rather than
// retyped here, so drift on either side has to face this test.
func TestProxyMaintenanceAllowsTheSharedConsentVerb(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
args := strings.Fields(strings.TrimPrefix(schema.SharedConsentCommandForced, "bd "))
target, _, err := rootCmd.Find(args)
if err != nil || target == rootCmd {
t.Fatalf("the gate prescribes %q, which does not resolve to a subcommand: %v",
schema.SharedConsentCommandForced, err)
}
if path := commandRegistryPath(target); path != "migrate schema" {
t.Fatalf("prescribed consent command resolves to path %q, want %q", path, "migrate schema")
}
find := func(t *testing.T, args ...string) *cobra.Command {
t.Helper()
cmd, _, err := rootCmd.Find(args)
if err != nil || cmd == rootCmd {
t.Fatalf("bd %s does not resolve: %v", strings.Join(args, " "), err)
}
return cmd
}
bareMigrate := find(t, "migrate")
doltPull := find(t, "dolt", "pull")
doltPush := find(t, "dolt", "push")
// `conflicts` itself is a parent group that cobra answers with help before
// any gate runs, so the refusal the guidance relies on lives on its leaves;
// resolve is the one a diverged pull's conflicts would need.
conflictsResolve := find(t, "conflicts", "resolve")
for _, topology := range []ProxyTopology{
ProxyTopologyManagedLocal, ProxyTopologyExternalTCP,
ProxyTopologyExternalUnix, ProxyTopologyTeamServer,
} {
t.Run(string(topology), func(t *testing.T) {
var allowErr error
out := captureStdout(t, func() error {
allowErr = validateProxyRegistryBeforeProvider(target, topology)
if allowErr == nil {
allowErr = validateProxyCapabilitiesBeforeProvider(target)
}
return nil
})
if allowErr != nil {
t.Errorf("%q is refused before the provider (%v), but the #6575 proxied data-behind guidance tells the operator it can be run from this workspace",
schema.SharedConsentCommandForced, allowErr)
}
if out != "" {
t.Errorf("a non-refusal still emitted a typed error: %s", out)
}
// The counterfactuals, so "only the bare `bd migrate` verb is
// refused here" and "the pull cannot be run from here" are claims
// and not vacuous ones. The push and conflicts rows hold the rest
// of the refusal list the proxied body recites: `dolt push` is
// refused as unimplemented, the class of row that flips to allowed
// once a route lands (as `dolt commit`'s did), and the body would
// then name a refusal that no longer exists.
for _, tc := range []struct {
cmd *cobra.Command
code string
}{
{bareMigrate, "proxy.migrate.unsupported"},
{doltPull, "proxy.dolt_pull.unsupported"},
{doltPush, "proxy.dolt_push.unsupported"},
{conflictsResolve, "proxy.conflicts.unsupported"},
} {
var refuseErr error
refusal := captureStdout(t, func() error {
refuseErr = validateProxyRegistryBeforeProvider(tc.cmd, topology)
return nil
})
if refuseErr == nil {
t.Errorf("bd %s is no longer refused in proxied-server mode; the data-behind guidance says it is",
commandRegistryPath(tc.cmd))
continue
}
if !strings.Contains(refusal, `"code": "`+tc.code+`"`) {
t.Errorf("bd %s refusal = %q, want %s", commandRegistryPath(tc.cmd), refusal, tc.code)
}
}
})
}
}
func TestProxyCapabilityMatrix(t *testing.T) {
for _, capability := range []ProxyCapability{ProxyCapReadonly, ProxyCapMaxRows} {
err := AssertProxyCapability(ProxyModeProxied, capability)
if err == nil {
t.Errorf("%s unexpectedly honored", capability)
}
var typed *ProxyCapabilityError
if !errors.As(err, &typed) || typed.Code == "" || typed.ExitCode != 1 || typed.Mutates {
t.Errorf("%s error = %#v, want stable non-mutating refusal", capability, err)
}
}
for _, tc := range []struct {
capability ProxyCapability
want string
}{
{ProxyCapWatch, "watch mode not supported in proxied-server mode"},
{ProxyCapRepo, "--repo is not supported with --proxied-server"},
} {
err := AssertProxyCapability(ProxyModeProxied, tc.capability)
if err == nil || err.Error() != tc.want {
t.Errorf("%s error = %v, want %q", tc.capability, err, tc.want)
}
}
}
// realCommandPaths walks the actual bd command tree once and returns every
// command path below the root. Policy tables and front-door branches are only
// as good as their correspondence to this set: a key that matches nothing is
// dead policy, and a branch keyed on something that is not a path applies to
// whichever commands happen to share the string.
func realCommandPaths(t *testing.T) map[string]bool {
t.Helper()
paths := map[string]bool{}
var walk func(*cobra.Command)
walk = func(c *cobra.Command) {
if path := commandRegistryPath(c); path != "" {
paths[path] = true
}
for _, child := range c.Commands() {
walk(child)
}
}
walk(rootCmd)
if len(paths) == 0 {
t.Fatal("walked the real command tree and found no commands")
}
return paths
}
func realCommandAtPath(t *testing.T, path string) *cobra.Command {
t.Helper()
found, _, err := rootCmd.Find(strings.Split(path, " "))
if err != nil {
t.Fatalf("resolve %q in the real command tree: %v", path, err)
}
if got := commandRegistryPath(found); got != path {
t.Fatalf("resolve %q in the real command tree = %q", path, got)
}
return found
}
// TestProxyCapabilityPolicyKeysResolveInRealCommandTree is the drift guard for
// the flag-keyed policy table. Every key must name a command that exists, so a
// renamed or removed command turns into a test failure instead of a rule that
// silently stops applying.
func TestProxyCapabilityPolicyKeysResolveInRealCommandTree(t *testing.T) {
paths := realCommandPaths(t)
for _, table := range []struct {
name string
keys []string
}{
// The path-keyed half (proxyCapabilityRegistry) has its own drift guard
// in TestProxyCapabilityRegistryHasNoStaleRows, so only the flag-keyed
// table is checked here.
{"proxyCommandCapabilities", slices.Sorted(maps.Keys(proxyCommandCapabilities))},
} {
for _, key := range table.keys {
if !paths[key] {
t.Errorf("%s has a row for %q, which is not a real command path", table.name, key)
}
}
}
}
// proxyCapabilityFlagNames records the command-line flag each capability
// governs. They happen to be the same strings as the capability constants, and
// this map exists so that stays a checked fact rather than a coincidence: a
// capability renamed away from its flag would turn the guard below into a
// no-op that still passes.
var proxyCapabilityFlagNames = map[ProxyCapability]string{
ProxyCapReadonly: "readonly",
ProxyCapMaxRows: "max-rows",
ProxyCapWatch: "watch",
ProxyCapRepo: "repo",
}
// commandAcceptsFlag reports whether this command would accept --name on a real
// command line, counting flags inherited from parents (--readonly is a root
// persistent flag) as well as locally registered ones.
func commandAcceptsFlag(cmd *cobra.Command, name string) bool {
if cmd.Flags().Lookup(name) != nil {
return true
}
return cmd.InheritedFlags().Lookup(name) != nil
}
// TestProxyCapabilityRowsNameFlagsTheCommandRegisters is the flag-level half of
// the policy drift guard, and the sibling above is the reason it is needed: that
// one pins PATHS, so a row can name a command that genuinely exists and still
// describe a flag the command has never had. `bd list` carried a
// ProxyCapRepo: repoRefusal row promising a typed refusal for `bd list --repo`,
// which cobra rejects at parse time as an unknown flag — a policy row no command
// line could reach, plus a changelog contract no wrapper could observe. The path
// guard could not see it.
//
// The rule runs in both directions, because each direction is a different lie:
//
// - a refused/honored row says the command handles the flag, so the command
// must register it — otherwise the row is unreachable policy;
// - a notApplicable() row says the command has no such flag, so the command
// must NOT register it — otherwise a live flag is silently unpoliced, and
// the front door's command-keyed assert resolves it to "allowed".
func TestProxyCapabilityRowsNameFlagsTheCommandRegisters(t *testing.T) {
// Vacuity guard: a flag name that no command registers would let every
// "must not register" assertion below pass for the wrong reason.
registrars := map[string]int{}
var walk func(*cobra.Command)
walk = func(c *cobra.Command) {
for _, name := range proxyCapabilityFlagNames {
if c.Flags().Lookup(name) != nil {
registrars[name]++
}
}
for _, child := range c.Commands() {
walk(child)
}
}
walk(rootCmd)
for capability, name := range proxyCapabilityFlagNames {
if capability == ProxyCapReadonly {
continue // root persistent flag; no command registers it locally
}
if registrars[name] == 0 {
t.Errorf("no command in the real tree registers --%s (capability %q); the flag name is stale", name, capability)
}
}
for _, path := range slices.Sorted(maps.Keys(proxyCommandCapabilities)) {
cmd := realCommandAtPath(t, path)
for mode, capabilities := range proxyCommandCapabilities[path] {
for capability, rule := range capabilities {
name, ok := proxyCapabilityFlagNames[capability]
if !ok {
t.Errorf("proxyCommandCapabilities[%q][%s] uses capability %q with no recorded flag name; add one so this guard keeps covering it",
path, mode, capability)
continue
}
registered := commandAcceptsFlag(cmd, name)
if rule.Outcome == ProxyOutcomeNA {
if registered {
t.Errorf("proxyCommandCapabilities[%q][%s][%s] is notApplicable(), but `bd %s` accepts --%s; the row denies a flag the command has",
path, mode, capability, path, name)
}
continue
}
if !registered {
t.Errorf("proxyCommandCapabilities[%q][%s][%s] is %q, but `bd %s` accepts no --%s; no command line can reach this row",
path, mode, capability, rule.Outcome, path, name)
}
}
}
}
}
// TestProxyFrontDoorBranchesUseRealCommandPaths pins the command paths the
// three front-door branches key on by hand: the two validators, plus the
// skipsStoreInit route into validateProxyRegistryBeforeProvider in main.go.
// This is the assertion that would have failed on the leaf-name keying: a
// branch written for `bd ready` must name a path, because "ready" as a leaf
// name is also `bd mol ready --gated`.
func TestProxyFrontDoorBranchesUseRealCommandPaths(t *testing.T) {
paths := realCommandPaths(t)
for _, path := range []string{"create", "show", "ready", "graph", "find-duplicates", "admin compact", "mol ready", "doctor"} {
if !paths[path] {
t.Errorf("front door branches on %q, which is not a real command path", path)
}
}
}
// TestProxyCapabilityFrontDoorAllowsSupportedCommands is the allow-path
// complement of the refusal matrix, and it runs against the real command tree
// rather than a synthetic one. The refusal direction degrades to the older,
// opaque late failure when it misses; a spurious refusal breaks a working
// command outright, so the allow path is the side that needs the guard.
func TestProxyCapabilityFrontDoorAllowsSupportedCommands(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = false
t.Cleanup(func() { jsonOutput = oldJSON })
for _, tc := range []struct {
path string
flags []string
cappedEnv bool
wantRefuse bool
}{
// `bd mol ready --gated` is the regression: proxy-supported, accepts
// no --max-rows, and shares its leaf name with `bd ready`.
{path: "mol ready"},
{path: "mol ready", cappedEnv: true},
{path: "ready"},
{path: "list"},
{path: "list", cappedEnv: true},
{path: "dep tree"},
{path: "dep tree", cappedEnv: true},
{path: "compact"},
{path: "compact", cappedEnv: true},
// `bd ready --gated` is the documented alias for the row above and runs
// the identical gate-resume scan, so a cap that leaves `bd mol ready
// --gated` alone must leave this spelling alone too. Keying the refusal
// on the command rather than the arm split one command line in half.
{path: "ready", flags: []string{"gated"}},
{path: "ready", flags: []string{"gated"}, cappedEnv: true},
// `bd ready` is the command the max-rows refusal was written for, so
// it must still refuse an active cap.
{path: "ready", cappedEnv: true, wantRefuse: true},
// ...on every arm that actually lists ready rows. --claim is not
// exempt, and neither is --gated in combination with it: that pair is a
// usage error rather than a gated run, so the claim arm keeps its
// refusal on every path into it.
{path: "ready", flags: []string{"claim"}, cappedEnv: true, wantRefuse: true},
{path: "ready", flags: []string{"claim", "gated"}, cappedEnv: true, wantRefuse: true},
} {
name := tc.path
for _, flag := range tc.flags {
name += " --" + flag
}
if tc.cappedEnv {
name += " with " + maxRowsEnvVar
}
t.Run(name, func(t *testing.T) {
if tc.cappedEnv {
t.Setenv(maxRowsEnvVar, "5")
} else {
t.Setenv(maxRowsEnvVar, "")
}
cmd := realCommandAtPath(t, tc.path)
// These are the real commands off rootCmd, so a flag set here
// outlives the subtest unless it is put back.
for _, flagName := range tc.flags {
flag := cmd.Flags().Lookup(flagName)
if flag == nil {
t.Fatalf("bd %s has no --%s flag to set", tc.path, flagName)
}
if err := cmd.Flags().Set(flagName, "true"); err != nil {
t.Fatalf("set --%s on bd %s: %v", flagName, tc.path, err)
}
t.Cleanup(func() {
if err := flag.Value.Set(flag.DefValue); err != nil {
t.Errorf("restore --%s on bd %s: %v", flagName, tc.path, err)
}
flag.Changed = false
})
}
var err error
stderr := captureStderr(t, func() {
err = validateProxyCapabilitiesBeforeProvider(cmd)
if err == nil {
// managed-local is the shape that owns its own dolt
// server, so a refusal here is a policy decision about the
// command rather than about the deployment.
err = validateProxyRegistryBeforeProvider(cmd, ProxyTopologyManagedLocal)
}
})
if tc.wantRefuse {
if err == nil {
t.Fatalf("bd %s was allowed; want a refusal", tc.path)
}
return
}
if err != nil {
t.Fatalf("bd %s refused before the provider: %v (stderr=%q)", tc.path, err, stderr)
}
if stderr != "" {
t.Fatalf("bd %s wrote %q to stderr on the allow path", tc.path, stderr)
}
})
}
}
// TestProxyCapabilityRulesAlwaysCarryAMessage covers the whole policy surface
// rather than the rows that exist today: a rule that refuses with no message
// renders as a bare "Error: " with exit 1, and an N/A rule describes a command
// that does not have the flag, which is nothing to refuse.
func TestProxyCapabilityRulesAlwaysCarryAMessage(t *testing.T) {
for _, command := range slices.Sorted(maps.Keys(proxyCommandCapabilities)) {
for mode, capabilities := range proxyCommandCapabilities[command] {
for capability, rule := range capabilities {
err := AssertProxyCommandCapability(command, mode, capability)
if proxyCapabilityAllowed(rule.Outcome) {
if err != nil {
t.Errorf("%s/%s/%s outcome=%s asserted %v, want nil", command, mode, capability, rule.Outcome, err)
}
continue
}
if err == nil {
t.Errorf("%s/%s/%s outcome=%s asserted nil, want a refusal", command, mode, capability, rule.Outcome)
continue
}
if err.Error() == "" {
t.Errorf("%s/%s/%s refused with an empty message", command, mode, capability)
}
}
}
}
// A rule with neither a code nor a message must still say something.
if got := proxyCapabilityRuleError(proxyCapabilityRule{Outcome: ProxyOutcomeRefused}, ProxyCapMaxRows, ProxyModeProxied); got == nil || got.Error() == "" {
t.Errorf("message-less refusal rendered as %v, want a non-empty error", got)
}
// The mirror hole on the same path: the allow branch above returns nil,
// and the front door wraps that return value, so a rule added as a bare
// `return HandleProxyCapabilityError(AssertProxy...(...))` must not turn
// an allowed capability into "Error: <nil>" with exit 1.
if got := HandleProxyCapabilityError(nil); got != nil {
t.Errorf("HandleProxyCapabilityError(nil) = %v, want nil", got)
}
}
// TestRepoRowsMatchShippedBehavior pins the --repo rows against the commands
// they describe, in both directions. The table documents itself as the
// deterministic audit source of truth, so a row that disagrees with the command
// is worse than an absent one — and that cuts the same way whether the
// disagreement over- or under-states the refusal.
func TestRepoRowsMatchShippedBehavior(t *testing.T) {
// `bd create --repo` is the reachable site: create.go registers the flag and
// the pre-provider gate asserts the mode-wide rule for it, so that rule must
// carry the documented message.
err := AssertProxyCapability(ProxyModeProxied, ProxyCapRepo)
if err == nil {
t.Fatal("--repo asserted nil; bd create --repo is refused under --proxied-server")
}
if got, want := err.Error(), "--repo is not supported with --proxied-server"; got != want {
t.Fatalf("--repo refusal = %q, want %q", got, want)
}
// `bd list --repo` is NOT a reachable site: listCmd registers no --repo, so
// the row reads notApplicable() and a command-keyed assert must come back
// allowed. An earlier version of this test asserted the opposite — that the
// list row refuses — which pinned a promise no command line could collect,
// since cobra rejects `bd list --repo` as an unknown flag before any of this
// runs.
if err := AssertProxyCommandCapability("list", ProxyModeProxied, ProxyCapRepo); err != nil {
t.Fatalf("list --repo asserted %v; bd list has no --repo flag, so its row must be notApplicable()", err)
}
}
// TestRepoProxiedRefusalIsStrictJSON pins the --repo refusal's SHAPE, where the
// test above pins only its text: a wrapper parsing --json must get the stable
// code and the mutates flag on stdout, and the error must still carry exit 1.
//
// It drives `bd create --repo` through the REAL command tree, and that is the
// whole point of the test. `bd create` is the only command that registers
// --repo (create.go), so its pre-provider gate is the only site a user can
// actually reach this refusal from. An earlier version of this test called
// runListProxiedServer directly with a hand-built listInput{repoOverrideSet:
// true} — which cannot happen, because listCmd has no --repo flag for cobra to
// mark Changed, and `bd list --repo` dies at parse time as an unknown flag. A
// direct-call assertion looks like coverage while proving nothing about any
// command line.
func TestRepoProxiedRefusalIsStrictJSON(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
cmd := realCommandAtPath(t, "create")
flag := cmd.Flags().Lookup("repo")
if flag == nil {
t.Fatal("bd create no longer registers --repo; the refusal has no reachable site")
}
if err := cmd.Flags().Set("repo", "/somewhere/else"); err != nil {
t.Fatalf("set --repo on bd create: %v", err)
}
t.Cleanup(func() {
if err := flag.Value.Set(flag.DefValue); err != nil {
t.Errorf("restore --repo on bd create: %v", err)
}
flag.Changed = false
})
var gotErr error
out := captureStdout(t, func() error {
gotErr = validateProxyCapabilitiesBeforeProvider(cmd)
return nil
})
if code, ok := exitCodeFromError(gotErr); !ok || code != 1 {
t.Fatalf("create --repo refusal exit = %v (typed=%v), want 1", code, ok)
}
var got map[string]any
if err := json.Unmarshal([]byte(out), &got); err != nil {
t.Fatalf("create --repo refusal is not JSON on stdout: %q (%v)", out, err)
}
if got["code"] != "proxy.repo.unsupported" {
t.Fatalf("create --repo refusal code = %v, want proxy.repo.unsupported (out=%q)", got["code"], out)
}
if got["error"] != "--repo is not supported with --proxied-server" {
t.Fatalf("create --repo refusal error = %v", got["error"])
}
if got["mutates"] != false {
t.Fatalf("create --repo refusal mutates = %v, want false", got["mutates"])
}
}
// TestReadyClaimResolvesRowCapOnceBeforeProvider pins the malformed-value
// advisory to one line. The command body resolves the cap again for itself, so
// a front door that also warned would print one typo twice.
func TestReadyClaimResolvesRowCapOnceBeforeProvider(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = false
t.Cleanup(func() { jsonOutput = oldJSON })
t.Setenv(maxRowsEnvVar, "bogus")
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: "ready"}
cmd.Flags().Bool("claim", false, "")
cmd.Flags().Int("max-rows", 0, "")
root.AddCommand(cmd)
if err := cmd.Flags().Set("claim", "true"); err != nil {
t.Fatal(err)
}
var err error
stderr := captureStderr(t, func() { err = validateProxyCapabilitiesBeforeProvider(cmd) })
if err != nil {
t.Fatalf("malformed %s refused the claim: %v", maxRowsEnvVar, err)
}
if strings.Contains(stderr, "is not a non-negative integer") {
t.Fatalf("front door warned about %s; the command body is the one that warns (stderr=%q)", maxRowsEnvVar, stderr)
}
}
func TestProxyCapabilityRowsCoverTopologies(t *testing.T) {
for _, topology := range []ProxyTopology{ProxyTopologyManagedLocal, ProxyTopologyExternalTCP, ProxyTopologyExternalUnix} {
for _, arg := range []string{"--readonly", "--max-rows", "--watch", "--repo"} {
if _, ok := LookupProxyCapabilityAt("", arg, ProxyModeProxied, topology); !ok {
t.Errorf("missing proxied row topology=%s argument=%s", topology, arg)
}
}
}
}
func TestProxyCapabilityCommandRows(t *testing.T) {
cases := []struct {
command, argument string
outcome ProxyCapabilityOutcome
}{
{"list", "--max-rows", ProxyOutcomeHonored},
{"dep tree", "--max-rows", ProxyOutcomeHonored},
{"ready", "--max-rows", ProxyOutcomeRefused},
{"graph", "--max-rows", ProxyOutcomeRefused},
{"find-duplicates", "--max-rows", ProxyOutcomeRefused},
{"show", "--watch", ProxyOutcomeHonored},
{"list", "--watch", ProxyOutcomeHonored},
}
for _, topology := range []ProxyTopology{ProxyTopologyManagedLocal, ProxyTopologyExternalTCP, ProxyTopologyExternalUnix} {
for _, tc := range cases {
rule, ok := LookupProxyCapabilityAt(tc.command, tc.argument, ProxyModeProxied, topology)
if !ok || rule.Outcome != tc.outcome {
t.Errorf("topology=%s %s %s outcome=%q ok=%v, want %q", topology, tc.command, tc.argument, rule.Outcome, ok, tc.outcome)
}
}
}
}
// TestProxyMaintenanceNestedPathsRefuseBeforeProvider proves the gate resolves
// a PARENT+CHILD path, which is where a nested command used to slip through.
// It runs on external-tcp because that is the topology on which every path
// listed here still refuses: the backup family is honored on managed-local
// since slice S3, and asserting a refusal there would be asserting the bug.
func TestProxyMaintenanceNestedPathsRefuseBeforeProvider(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
for _, path := range []string{"backup init", "backup status", "migrate sync", "gate discover"} {
parts := strings.Split(path, " ")
root := &cobra.Command{Use: "bd"}
parent := &cobra.Command{Use: parts[0]}
child := &cobra.Command{Use: parts[1]}
root.AddCommand(parent)
parent.AddCommand(child)
out := captureStdout(t, func() error {
_ = validateProxyRegistryBeforeProvider(child, ProxyTopologyExternalTCP)
return nil
})
if !strings.Contains(out, `"code":`) {
t.Errorf("%s produced no typed refusal: %s", path, out)
}
}
}
func TestProxyFormulaSwarmMergeSlotRefusals(t *testing.T) {
for _, path := range []string{"cook", "ship", "swarm create", "swarm list", "merge-slot create", "merge-slot check", "merge-slot acquire", "merge-slot release"} {
parts := strings.Split(path, " ")
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: parts[0]}
root.AddCommand(cmd)
for _, childName := range parts[1:] {
child := &cobra.Command{Use: childName}
cmd.AddCommand(child)
cmd = child
}
err := validateProxyRegistryBeforeProvider(cmd, ProxyTopologyManagedLocal)
if err == nil {
t.Fatalf("%s unexpectedly allowed", path)
}
if code, ok := exitCodeFromError(err); !ok || code != 1 {
t.Fatalf("%s exit=%v, want 1", path, err)
}
}
}
func TestProxyWorkflowRefusalContractAndNoMutation(t *testing.T) {
cases := []struct {
path, code, message string
}{
{"cook", "proxy.formula.unsupported", "cook is not supported in proxied-server mode"},
{"ship", "proxy.formula.unsupported", "ship is not supported in proxied-server mode"},
{"swarm create", "proxy.swarm.unsupported", "swarm create is not supported in proxied-server mode"},
{"merge-slot acquire", "proxy.merge_slot.unsupported", "merge-slot acquire is not supported in proxied-server mode"},
}
for _, tc := range cases {
t.Run(tc.path, func(t *testing.T) {
parts := strings.Split(tc.path, " ")
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: parts[0]}
root.AddCommand(cmd)
if tc.path == "cook" {
cmd.Flags().Bool("persist", false, "")
_ = cmd.Flags().Set("persist", "true")
}
for _, name := range parts[1:] {
child := &cobra.Command{Use: name}
cmd.AddCommand(child)
cmd = child
}
row, ok := lookupProxyMaintenanceRuleForTest(tc.path)
if !ok || row.Code != tc.code || row.Message != tc.message || row.ExitCode != 1 || row.Mutates {
t.Fatalf("row = %#v, ok=%v", row, ok)
}
typed := proxyCapabilityErrorFor(row)
if typed.Code != tc.code || typed.Message != tc.message || typed.ExitCode != 1 || typed.Mutates {
t.Fatalf("typed refusal = %#v", typed)
}
dir := t.TempDir()
before := []byte("unchanged\n")
for _, name := range []string{"issues.jsonl", "config.yaml", "events.jsonl"} {
if err := os.WriteFile(dir+"/"+name, before, 0o600); err != nil {
t.Fatal(err)
}
}
oldProvider := uowProvider
uowProvider = nil
t.Cleanup(func() { uowProvider = oldProvider })
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
// commandDidWrite is a process-wide latch that any earlier test in
// this package may already have set, so it has to be baselined
// here or the assertion below reports another test's write.
oldDidWrite := commandDidWrite.Load()
commandDidWrite.Store(false)
t.Cleanup(func() { commandDidWrite.Store(oldDidWrite) })
out := captureStdout(t, func() error { _ = validateProxyRegistryBeforeProvider(cmd, ProxyTopologyManagedLocal); return nil })
var got map[string]any
if err := json.Unmarshal([]byte(out), &got); err != nil || got["code"] != tc.code || got["error"] != tc.message {
t.Fatalf("JSON refusal = %q (%v)", out, err)
}
if uowProvider != nil || commandDidWrite.Load() {
t.Fatal("refusal initialized provider or marked a write")
}
for _, name := range []string{"issues.jsonl", "config.yaml", "events.jsonl"} {
gotBytes, err := os.ReadFile(dir + "/" + name)
if err != nil || !bytes.Equal(gotBytes, before) {
t.Fatalf("%s mutated: %v", name, err)
}
}
})
}
}
func lookupProxyMaintenanceRuleForTest(path string) (proxyCapabilityRule, bool) {
row, ok := LookupCapabilityRow(path, "")
return row.Rule, ok
}
func TestProxyMaintenanceRefusalLeavesFilesUntouched(t *testing.T) {
root := &cobra.Command{Use: "bd"}
migrate := &cobra.Command{Use: "migrate"}
hooks := &cobra.Command{Use: "hooks"}
root.AddCommand(migrate)
migrate.AddCommand(hooks)
before := []byte("hooks-state")
path := t.TempDir() + "/.local_version"
if err := os.WriteFile(path, before, 0600); err != nil {
t.Fatal(err)
}
oldProvider := uowProvider
uowProvider = nil
t.Cleanup(func() { uowProvider = oldProvider })
err := validateProxyRegistryBeforeProvider(hooks, ProxyTopologyManagedLocal)
if err == nil {
t.Fatal("expected typed maintenance refusal")
}
if code, ok := exitCodeFromError(err); !ok || code != 1 {
t.Fatalf("exit = %v, want 1", err)
}
after, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(after, before) {
t.Fatalf("refusal mutated %s", path)
}
}
// newProxyFrontDoorCommand builds `bd <use> --<flag>` under a real root. The
// root matters: the front door keys on a command's path below its root, so a
// parentless command has no path and matches no rule — which is how a test
// tree can report success for a refusal that never fired.
func newProxyFrontDoorCommand(t *testing.T, use, flag string) *cobra.Command {
t.Helper()
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: use}
cmd.Flags().Bool(flag, false, "")
root.AddCommand(cmd)
if err := cmd.Flags().Set(flag, "true"); err != nil {
t.Fatal(err)
}
if got := commandRegistryPath(cmd); got != use {
t.Fatalf("test command path = %q, want %q", got, use)
}
return cmd
}
func TestProxyCapabilityRefusalFrontDoorTextBeforeProvider(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = false
t.Cleanup(func() { jsonOutput = oldJSON })
cmd := newProxyFrontDoorCommand(t, "create", "repo")
got := captureStderr(t, func() { _ = validateProxyCapabilitiesBeforeProvider(cmd) })
if !strings.Contains(got, "--repo is not supported with --proxied-server") {
t.Fatalf("text refusal = %q", got)
}
}
func TestProxyCapabilityRefusalFrontDoorJSONIncludesCode(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
cmd := newProxyFrontDoorCommand(t, "create", "repo")
out := captureStdout(t, func() error {
_ = validateProxyCapabilitiesBeforeProvider(cmd)
return nil
})
if !strings.Contains(out, `"code": "proxy.repo.unsupported"`) {
t.Fatalf("JSON refusal = %q", out)
}
}
// TestProxyFrontDoorAdmitsShowWatch pins that `bd show --watch` reaches the
// proxied provider. It used to be refused here with proxy.watch.unsupported,
// although the provider can answer the poll exactly as `list --watch` does.
func TestProxyFrontDoorAdmitsShowWatch(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
cmd := newProxyFrontDoorCommand(t, "show", "watch")
var err error
out := captureStdout(t, func() error {
err = validateProxyCapabilitiesBeforeProvider(cmd)
return nil
})
if err != nil || strings.Contains(out, "proxy.watch.unsupported") {
t.Fatalf("front door refused show --watch: err=%v out=%q", err, out)
}
if err := AssertProxyCommandCapability("show", ProxyModeProxied, ProxyCapWatch); err != nil {
t.Fatalf("show --watch capability refused: %v", err)
}
}
func TestProxyCapabilityDirectEscapeHatch(t *testing.T) {
for _, cap := range []ProxyCapability{ProxyCapReadonly, ProxyCapMaxRows, ProxyCapWatch, ProxyCapRepo} {
if err := AssertProxyCapability(ProxyModeDirect, cap); err != nil {
t.Errorf("direct %s refused: %v", cap, err)
}
}
}
func TestReadyClaimValidatesMaxRowsBeforeProvider(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: "ready"}
cmd.Flags().Bool("claim", false, "")
cmd.Flags().Int("max-rows", 0, "")
root.AddCommand(cmd)
if err := cmd.Flags().Set("claim", "true"); err != nil {
t.Fatal(err)
}
if err := cmd.Flags().Set("max-rows", "-1"); err != nil {
t.Fatal(err)
}
var gotErr error
out := captureStdout(t, func() error {
gotErr = validateProxyCapabilitiesBeforeProvider(cmd)
return nil
})
if code, ok := exitCodeFromError(gotErr); !ok || code != 1 {
t.Fatalf("ready claim invalid max-rows exit = %v, want 1", code)
}
if !strings.Contains(out, "--max-rows must be non-negative") {
t.Fatalf("ready claim invalid max-rows refusal = %q", out)
}
}
// TestReadyPositiveCapRefusedTypedWithAndWithoutClaim pins one refusal to one
// shape. --claim does not exempt a positive row cap: the proxied ready role
// cannot enforce one on either arm, and ready.go refuses both (see its comment
// above rejectMaxRowsUnderProxiedServer). Exempting the claim at the front door
// would not let it through — it would only downgrade the same refusal to an
// untyped one raised after the provider opened, so `bd ready --max-rows 5` and
// `bd ready --claim --max-rows 5` would answer --json in two different shapes,
// selected by a flag that has nothing to do with the cap.
func TestReadyPositiveCapRefusedTypedWithAndWithoutClaim(t *testing.T) {
const wantCode = "proxy.max_rows.unsupported"
const wantMessage = "--max-rows / BEADS_MAX_ROWS is not supported in proxied-server mode"
assertTypedRefusal := func(t *testing.T, gotErr error, out string) {
t.Helper()
if code, ok := exitCodeFromError(gotErr); !ok || code != 1 {
t.Fatalf("refusal exit = %v (typed=%v), want 1", code, ok)
}
var got map[string]any
if err := json.Unmarshal([]byte(out), &got); err != nil {
t.Fatalf("refusal is not JSON on stdout: %q (%v)", out, err)
}
if got["code"] != wantCode || got["error"] != wantMessage || got["mutates"] != false {
t.Fatalf("refusal = %q, want code=%q error=%q mutates=false", out, wantCode, wantMessage)
}
}
for _, tc := range []struct {
name string
claim bool
}{{name: "bulk"}, {name: "claim", claim: true}} {
t.Run(tc.name, func(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: "ready"}
cmd.Flags().Bool("claim", false, "")
cmd.Flags().Int("max-rows", 0, "")
root.AddCommand(cmd)
if err := cmd.Flags().Set("max-rows", "5"); err != nil {
t.Fatal(err)
}
if tc.claim {
if err := cmd.Flags().Set("claim", "true"); err != nil {
t.Fatal(err)
}
}
var gotErr error
out := captureStdout(t, func() error {
gotErr = validateProxyCapabilitiesBeforeProvider(cmd)
return nil
})
assertTypedRefusal(t, gotErr, out)
})
}
// The command body refuses the same cap behind the front door. It renders
// identically so the contract survives on whichever path reaches it first.
t.Run("backstop", func(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
var gotErr error
out := captureStdout(t, func() error {
gotErr = rejectResolvedMaxRowsUnderProxiedServer(5)
return nil
})
assertTypedRefusal(t, gotErr, out)
})
}