fix(init): validate a supplied destroy-token even when interactive (#6480) (#6639)

* fix(init): validate a supplied destroy-token even when interactive

CheckRemoteSafety only compared --destroy-token for non-interactive
callers. handleRemoteSafetyDecision only shows the typed-confirmation
prompt when no token was supplied. An interactive
`bd init --discard-remote --destroy-token=WRONG` therefore satisfied
neither guard and discarded remote Dolt history with no confirmation.

Validate any non-empty token regardless of interactivity; an absent
token still defers to the TTY prompt. Adds guard-matrix cases for the
interactive wrong-token, token-without-expected, matching-token and
no-token paths.

Fixes #6480

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* review: distinguish a wrong destroy-token from a missing one

Maintainer fixup for the #6639 review (iteration 1: no blockers, no
majors, scorecard approve). Takes the three non-gating minors and the nit
that live in the file this PR already changes.

1. Debuggability (claude+codex, minor). Making CheckRemoteSafety validate
   a supplied token newly routes interactive callers into
   refusalMessageTokenMissing(), whose text is written for the
   non-interactive path: it says "requires an explicit destroy-token in
   non-interactive mode" and advises "re-run interactively ... and confirm
   at the prompt". That advice cannot work for them -- the prompt at
   init.go:3139 is gated on destroyToken == "" -- so a user who typo'd a
   token re-runs into the identical exit 12 forever.

   A reword could only make the one string vaguer, so token PRESENCE is
   now carried into the decision: refusalMessageTokenMismatch() for a
   supplied-but-wrong token (reachable in both modes; its remedy is to fix
   the token or drop the flag to be prompted), and the existing message,
   byte-for-byte unchanged, for the no-token case. That case is now
   reachable only non-interactively, so its "non-interactive mode" framing
   and its prompt advice are both exactly true again -- and
   docs/recovery/init-safety.md:96, which reproduces that text under
   `init-token-missing`, stays accurate. Reason splits to
   destroy-token-missing / destroy-token-mismatch (grep: no consumer; the
   only Reason any caller reads is "authorized-divergence").

2. Contract fidelity (claude+codex, minor). The three doc comments that
   now state the opposite of the code -- ActionRequireDestroyToken,
   IsInteractive, and ExitDestroyTokenMissing's "all three sources" -- are
   updated to the token-presence rule, matching the correct inline comment
   this PR added at the change site. This file is the ADR-0002 chokepoint,
   so its comments are the contract future flags are read against.

3. Test evidence (codex, minor). handleRemoteSafetyDecision had zero test
   references repo-wide while the bug was the composition of the decision
   with the prompt gate. TestHandleRemoteSafetyDecision_RefusalSeam pins
   the refusal half: a refusal aborts with its exit code, never reaches
   the prompt, and leaves the cross-checkpoint *confirmed latch alone.
   The token-ABSENT prompt arm is deliberately NOT pinned: it is gated on
   term.IsTerminal(os.Stdin), false under `go test`, so asserting "no
   prompt" there would pass no matter what the token gate said. That half
   needs a PTY or a TTY-detection seam; left as follow-up rather than
   landing a vacuous pin for a coverage finding.

4. Nit: the token-without-expected matrix case is annotated defensive /
   unreachable from current callers, so a later reader does not cite it as
   live-path evidence.

Every new pin was proven non-vacuous by mutation, each hitting only its
own arm: forcing the selector back to the conflated message reddens the
three token-supplied cases and leaves no-token green; dropping
ActionRequireDestroyToken from the seam's case label reddens only the
exit-12 subtest; removing "drop --destroy-token" from the new message
reddens the remedy assertion.

Out of scope, deliberately: no change to docs/recovery/init-safety.md
(the string it documents is unchanged and its scenario still accurate; a
wrong-token symptom entry is follow-up), and no attempt at the
pre-existing asymmetry between the remote and local re-init guards.

Validation: go vet ./cmd/bd clean; the full init_safety_test.go suite
green at head (16 pass, 1 pre-existing unconditional skip).

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
This commit is contained in:
Vishnu J 2026-09-26 14:04:45 -07:00 • committed by GitHub
commit 991e5e3aa4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 310 additions and 22 deletions

View file

@ -34,14 +34,17 @@ const (
// local-safety guard with an ordinary error, not this code.
ExitLocalExistsRefused = 11
// ExitDestroyTokenMissing signals a destructive re-init was requested
// in non-interactive mode without a valid `--destroy-token`: either
// `--discard-remote`, or `--reinit-local` over existing local issues.
// The caller must look up the token format via `bd help init-safety`.
// It is also returned when the interactive `--discard-remote` typed-token
// confirmation is declined at the prompt, so a 12 does not on its own
// prove the caller was non-interactive. Supplying the token is the
// correct remedy for all three sources.
// ExitDestroyTokenMissing signals a destructive re-init was refused for
// want of a valid `--destroy-token`. Four sources:
// 1. non-interactive `--discard-remote` with no token;
// 2. non-interactive `--reinit-local` over existing local issues;
// 3. `--discard-remote` with a supplied token that does not match, in
// EITHER mode — a token that WAS supplied is always validated (#6480);
// 4. the interactive `--discard-remote` typed-token confirmation
// declined at the prompt.
// So a 12 does not on its own prove the caller was non-interactive.
// Supplying the matching token is the correct remedy for sources 1-3
// (format via `bd help init-safety`); source 4 was a deliberate decline.
ExitDestroyTokenMissing = 12
)
@ -65,9 +68,11 @@ const (
ActionRefuseDivergence
// ActionRequireDestroyToken — caller passed `--discard-remote` but
// destroy-token validation failed (non-interactive path with no token,
// or wrong token). Refuse with `ExitDestroyTokenMissing`. The
// interactive path should prompt for confirmation instead.
// destroy-token validation failed: either a non-interactive caller
// supplied no token, or a token WAS supplied — in either mode — and did
// not match. Refuse with `ExitDestroyTokenMissing`. An interactive
// caller that supplied NO token does not land here: it gets
// ActionProceedWithDivergence and must prompt for confirmation instead.
ActionRequireDestroyToken
// ActionProceedWithDivergence — caller passed `--discard-remote` and
@ -103,10 +108,12 @@ type RemoteSafetyInput struct {
RemoteHasDoltData bool
// IsInteractive is true when the caller is attached to a TTY.
// Interactive callers can prompt for destroy-token confirmation; the
// decision returned for interactive callers assumes they will prompt
// (so ActionProceedWithDivergence can be returned without a token
// match — the caller must do the prompt itself).
// Interactive callers can prompt for destroy-token confirmation, so the
// decision returned for an interactive caller that supplied NO token
// assumes it will prompt (ActionProceedWithDivergence is returned
// without a token match — the caller must do the prompt itself). A
// token that WAS supplied is always validated regardless of this field:
// the caller's prompt only fires when no token was given (#6480).
IsInteractive bool
}
@ -156,15 +163,29 @@ func CheckRemoteSafety(in RemoteSafetyInput) RemoteSafetyDecision {
}
}
// User authorized. Interactive callers prompt; non-interactive must
// supply a matching destroy-token.
if !in.IsInteractive {
// User authorized. Non-interactive callers must supply a matching
// destroy-token. Interactive callers that supplied no token defer to the
// typed-confirmation prompt, but a token that WAS supplied is always
// validated: the caller's prompt only fires when no token was given, so
// an unvalidated wrong token would skip every confirmation (#6480).
if !in.IsInteractive || in.DestroyToken != "" {
if in.ExpectedToken == "" || in.DestroyToken != in.ExpectedToken {
// Carry token PRESENCE into the refusal. The two cases have
// different remedies and only one of them can be reached
// interactively, so a single conflated message necessarily
// misdirects one of them: telling a user who supplied a wrong
// token to "re-run interactively and confirm at the prompt"
// loops them through the identical refusal forever, because the
// prompt is gated on no token being supplied.
reason, message := "destroy-token-missing", refusalMessageTokenMissing()
if in.DestroyToken != "" {
reason, message = "destroy-token-mismatch", refusalMessageTokenMismatch()
}
return RemoteSafetyDecision{
Action: ActionRequireDestroyToken,
Reason: "destroy-token-missing-or-wrong",
Reason: reason,
ExitCode: ExitDestroyTokenMissing,
UserMessage: refusalMessageTokenMissing(),
UserMessage: message,
}
}
}
@ -196,8 +217,15 @@ func refusalMessageDivergence() string {
}
// refusalMessageTokenMissing returns the What/Why/Next refusal text for
// the `--discard-remote` + missing/wrong destroy-token case. Deliberately
// does not echo the token value.
// `--discard-remote` with NO destroy-token supplied. That combination is
// reachable only from a non-interactive caller — an interactive one with no
// token defers to the typed-confirmation prompt — so both the
// "non-interactive mode" framing and the "re-run interactively" remedy are
// accurate here. A supplied-but-wrong token gets
// refusalMessageTokenMismatch() instead, where that remedy would be a dead
// end. The text is reproduced in docs/recovery/init-safety.md under
// `init-token-missing`; keep them in sync. Deliberately does not echo the
// token value.
func refusalMessageTokenMissing() string {
return `bd init refuses: --discard-remote requires an explicit destroy-token in non-interactive mode.
@ -210,6 +238,30 @@ func refusalMessageTokenMissing() string {
Or re-run interactively (attached to a TTY) and confirm at the prompt.`
}
// refusalMessageTokenMismatch returns the What/Why/Next refusal text for
// `--discard-remote` with a destroy-token that was supplied but does not
// match. Unlike the missing-token case this is reachable in BOTH modes, so
// its Next must hold on a TTY too: re-running interactively with the same
// token repeats this refusal, because the typed-confirmation prompt fires
// only when no token was given. Dropping the flag is the remedy that
// actually reaches the prompt. Deliberately does not echo the token value.
func refusalMessageTokenMismatch() string {
return `bd init refuses: the supplied --destroy-token does not match this project's token.
Why: Destructive cross-boundary operations cannot be authorized
silently, and a token that does not match is not authorization.
The expected token is derived from the issue prefix; this refusal
deliberately does not echo it.
Next:
See 'bd help init-safety' for the destroy-token format, then re-run
with the matching value.
Or drop --destroy-token entirely and re-run interactively (attached
to a TTY): with no token supplied, bd asks for typed confirmation at
the prompt instead.`
}
// FormatDestroyToken returns the destroy-token the caller should supply
// for a given issue prefix. Callers that need to surface this to users
// should do so via `bd help init-safety` or `docs/recovery/init-safety.md` — NOT via

View file

@ -279,6 +279,52 @@ func TestCheckRemoteSafety_GuardMatrix(t *testing.T) {
RemoteSafetyInput{RemoteHasDoltData: true, DiscardRemote: true, IsInteractive: true},
ActionProceedWithDivergence, 0,
},
// INTERACTIVE with a supplied-but-WRONG token (#6480): the token must
// still be validated. The caller's typed-confirmation prompt only
// fires when NO token was supplied, so skipping validation here would
// discard the remote with no confirmation of any kind.
{
"remote/discard-remote/interactive/wrong-token",
RemoteSafetyInput{
RemoteHasDoltData: true, DiscardRemote: true, IsInteractive: true,
DestroyToken: "WRONG", ExpectedToken: "DESTROY-bd",
},
ActionRequireDestroyToken, ExitDestroyTokenMissing,
},
// INTERACTIVE with a token but no expected token to compare against:
// nothing can validate it, so refuse rather than fall to the prompt.
// DEFENSIVE: unreachable from current callers — all three call sites
// pass ExpectedToken: FormatDestroyToken(prefix), which is never
// empty. This pins the fail-closed arm of a pure function; it is not
// evidence about any live path (only wrong-token above is).
{
"remote/discard-remote/interactive/token-without-expected",
RemoteSafetyInput{
RemoteHasDoltData: true, DiscardRemote: true, IsInteractive: true,
DestroyToken: "WRONG",
},
ActionRequireDestroyToken, ExitDestroyTokenMissing,
},
// INTERACTIVE with a MATCHING token: the token is the authorization.
{
"remote/discard-remote/interactive/matching-token",
RemoteSafetyInput{
RemoteHasDoltData: true, DiscardRemote: true, IsInteractive: true,
DestroyToken: "DESTROY-bd", ExpectedToken: "DESTROY-bd",
},
ActionProceedWithDivergence, 0,
},
// INTERACTIVE with NO token supplied (expected token known): unchanged
// — the decision defers to the TTY typed-confirmation prompt.
{
"remote/discard-remote/interactive/no-token-with-expected",
RemoteSafetyInput{
RemoteHasDoltData: true, DiscardRemote: true, IsInteractive: true,
ExpectedToken: "DESTROY-bd",
},
ActionProceedWithDivergence, 0,
},
}
for _, tc := range cases {
@ -298,6 +344,196 @@ func TestCheckRemoteSafety_GuardMatrix(t *testing.T) {
}
}
// TestCheckRemoteSafety_TokenRefusalDistinguishesPresence pins which refusal
// text each exit-12 path gets. The distinction is load-bearing, not cosmetic:
// the missing-token message tells the user to "re-run interactively ... and
// confirm at the prompt", and that remedy only works when NO token was
// supplied, because the caller's typed-confirmation prompt is gated on
// destroyToken == "" (init.go:3139). Handing it to a user who supplied a
// wrong token sends them around the identical refusal forever.
func TestCheckRemoteSafety_TokenRefusalDistinguishesPresence(t *testing.T) {
cases := []struct {
name string
in RemoteSafetyInput
wantReason string
wantSupplied bool
}{
{
"non-interactive/no-token",
RemoteSafetyInput{RemoteHasDoltData: true, DiscardRemote: true, ExpectedToken: "DESTROY-bd"},
"destroy-token-missing", false,
},
{
"non-interactive/wrong-token",
RemoteSafetyInput{
RemoteHasDoltData: true, DiscardRemote: true,
DestroyToken: "WRONG", ExpectedToken: "DESTROY-bd",
},
"destroy-token-mismatch", true,
},
{
"interactive/wrong-token",
RemoteSafetyInput{
RemoteHasDoltData: true, DiscardRemote: true, IsInteractive: true,
DestroyToken: "WRONG", ExpectedToken: "DESTROY-bd",
},
"destroy-token-mismatch", true,
},
{
// Defensive arm (see the guard matrix): a token was still
// supplied, so it gets the mismatch text.
"interactive/token-without-expected",
RemoteSafetyInput{
RemoteHasDoltData: true, DiscardRemote: true, IsInteractive: true,
DestroyToken: "WRONG",
},
"destroy-token-mismatch", true,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := CheckRemoteSafety(tc.in)
if got.Action != ActionRequireDestroyToken {
t.Fatalf("Action = %v, want ActionRequireDestroyToken", got.Action)
}
if got.Reason != tc.wantReason {
t.Errorf("Reason = %q, want %q", got.Reason, tc.wantReason)
}
wantMsg := refusalMessageTokenMissing()
if tc.wantSupplied {
wantMsg = refusalMessageTokenMismatch()
}
if got.UserMessage != wantMsg {
t.Errorf("UserMessage =\n%s\n\nwant\n%s", got.UserMessage, wantMsg)
}
// The defect this pins: the "re-run interactively and confirm
// at the prompt" remedy must never reach a caller who supplied
// a token, since the prompt cannot fire for them.
if tc.wantSupplied && got.UserMessage == refusalMessageTokenMissing() {
t.Errorf("token-supplied refusal got the missing-token text, whose remedy is unreachable here:\n%s", got.UserMessage)
}
})
}
if refusalMessageTokenMissing() == refusalMessageTokenMismatch() {
t.Error("the two token refusals are identical, so token presence is not actually carried")
}
// The mismatch remedy must name the reachable escape: drop the flag to
// be prompted. Without this the message is merely vaguer, not correct.
if !strings.Contains(refusalMessageTokenMismatch(), "drop --destroy-token") {
t.Errorf("mismatch refusal does not offer the reachable remedy (drop the flag, get prompted):\n%s", refusalMessageTokenMismatch())
}
}
// TestCheckRemoteSafety_TokenRefusalTextNoEcho extends the ADR error-message
// contract to both destroy-token refusals. TestCheckRemoteSafety_RefusalTextNoEcho
// below covers only the divergence message, whose assertions (bd bootstrap,
// --from-jsonl) are specific to it.
func TestCheckRemoteSafety_TokenRefusalTextNoEcho(t *testing.T) {
msgs := map[string]string{
"missing": refusalMessageTokenMissing(),
"mismatch": refusalMessageTokenMismatch(),
}
bannedEchoes := []string{
"bd init --force --discard-remote --destroy-token",
"bd init --reinit-local --discard-remote --destroy-token",
"DESTROY-",
}
for name, msg := range msgs {
for _, banned := range bannedEchoes {
if strings.Contains(msg, banned) {
t.Errorf("%s refusal contains destructive echo %q:\n%s", name, banned, msg)
}
}
if !strings.Contains(msg, "bd help init-safety") {
t.Errorf("%s refusal does not point to 'bd help init-safety':\n%s", name, msg)
}
}
}
// TestHandleRemoteSafetyDecision_RefusalSeam pins the caller half of the
// #6480 composition. CheckRemoteSafety's guard matrix proves the decision;
// this proves the decision is honored at the seam — that a refusal aborts
// with its exit code and never reaches the typed-confirmation prompt, and
// that it leaves the cross-checkpoint *confirmed latch alone. Before this,
// handleRemoteSafetyDecision had zero test references repo-wide.
//
// Not covered here: the token-ABSENT prompt arm (init.go:3139). It is gated
// on term.IsTerminal(os.Stdin), which is false under `go test`, so asserting
// "no prompt" for it would pass no matter what the token gate said — a
// vacuous pin. Reaching it needs a PTY or a TTY-detection seam; both exceed
// this change. The arms below discriminate without one.
func TestHandleRemoteSafetyDecision_RefusalSeam(t *testing.T) {
cases := []struct {
name string
decision RemoteSafetyDecision
wantBootstrap bool
wantExit int // 0 = expect nil error
}{
{
"require-destroy-token aborts with 12",
RemoteSafetyDecision{
Action: ActionRequireDestroyToken, Reason: "destroy-token-mismatch",
ExitCode: ExitDestroyTokenMissing, UserMessage: "refusal",
},
false, ExitDestroyTokenMissing,
},
{
"refuse-divergence aborts with 10",
RemoteSafetyDecision{
Action: ActionRefuseDivergence, Reason: "force-without-discard-remote",
ExitCode: ExitRemoteDivergenceRefused, UserMessage: "refusal",
},
false, ExitRemoteDivergenceRefused,
},
{
"bootstrap adopts the remote",
RemoteSafetyDecision{Action: ActionBootstrap, Reason: "bootstrap-from-remote"},
true, 0,
},
{
// A matching token IS the authorization: proceed, no abort.
"authorized divergence proceeds",
RemoteSafetyDecision{Action: ActionProceedWithDivergence, Reason: "authorized-divergence"},
false, 0,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
confirmed := false
// destroyToken non-empty keeps the prompt arm shut on its own
// terms rather than relying on the harness lacking a TTY.
bootstrap, err := handleRemoteSafetyDecision(
tc.decision, "bd", "git+https://example.invalid/repo.git",
"DESTROY-bd", nil, true, &confirmed,
)
if bootstrap != tc.wantBootstrap {
t.Errorf("bootstrap = %v, want %v", bootstrap, tc.wantBootstrap)
}
if tc.wantExit == 0 {
if err != nil {
t.Errorf("err = %v, want nil", err)
}
} else {
code, ok := exitCodeFromError(err)
if !ok {
t.Fatalf("err = %v, want an *exitError with code %d", err, tc.wantExit)
}
if code != tc.wantExit {
t.Errorf("exit code = %d, want %d", code, tc.wantExit)
}
}
// A refusal must not silently satisfy a later checkpoint's
// "already confirmed" short-circuit.
if confirmed {
t.Error("confirmed latch was set without a typed confirmation")
}
})
}
}
// TestCheckRemoteSafety_RefusalTextNoEcho enforces the error-message
// contract: runtime refusal text must not echo a complete destructive
// invocation. A copy-pasteable command in the error is the failure class