fix(note): reject subcommand-style words as the issue id (GH#5370)

Expand validateNoteArgs denylist from {list, add} to
{list, add, show, edit, rm, remove, delete} so common typos cannot
silently fuzzy-match an unrelated bead via ResolvePartialID.

Harden TestCLI_Note{List,Add}MisplacedSyntax to assert bystander notes
are unchanged (before==after) rather than empty, so the regression is
immune to package-level cobra flag leaks from earlier tests.

Fixes #5370
Reported by @athosmartins
This commit is contained in:
Vishnu Jayavel 2026-08-07 12:21:07 -07:00
commit fcfc46a923
3 changed files with 340 additions and 2 deletions

View file

@ -558,6 +558,203 @@ func TestCLI_NoteCommand(t *testing.T) {
}
}
// TestCLI_NoteListMisplacedSyntax is a regression test for "note" silently
// mis-resolving a subcommand-like typo as an issue id (GH#5370). Mirrors
// TestCLI_CommentListMisplacedSyntax (#5369): "bd note list <text>" used to
// parse as id="list", text=[<text>...] with no validation on the id — since
// no issue is literally named "list", ResolvePartialID's substring/prefix
// fallback would silently match it against whatever existing bead or wisp id
// happened to contain "list" and append the note there instead of erroring.
// This asserts both halves of the fix: the command is rejected with a
// helpful hint, AND no note silently landed on an unrelated real issue.
func TestCLI_NoteListMisplacedSyntax(t *testing.T) {
tmpDir := setupCLITestDB(t)
out := runBDInProcess(t, tmpDir, "create", "Bystander issue", "-p", "1", "--json")
jsonStart := strings.Index(out, "{")
if jsonStart < 0 {
t.Fatalf("No JSON found in create output: %s", out)
}
var issue map[string]interface{}
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
}
fullID := issue["id"].(string)
// Snapshot notes BEFORE the rejected command. runBDInProcess reuses the
// package-level rootCmd without resetting cobra flag state, so an earlier
// test's --notes value can leak into this create. Asserting before==after
// is immune to that leak and is a stronger regression check: the rejected
// command wrote nothing (GH#5370 review fix-round).
beforeShow := runBDInProcess(t, tmpDir, "show", fullID, "--json")
var beforeShown []map[string]interface{}
if err := json.Unmarshal([]byte(beforeShow), &beforeShown); err != nil {
t.Fatalf("Failed to parse pre-reject show JSON: %v\nOutput: %s", err, beforeShow)
}
if len(beforeShown) == 0 {
t.Fatalf("expected show to return the bystander issue before reject, got: %s", beforeShow)
}
notesBefore, _ := beforeShown[0]["notes"].(string)
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "note", "list", "accidental stray text")
if err == nil {
t.Fatalf("expected non-zero exit, got stdout=%q stderr=%q", stdout, stderr)
}
combined := stdout + stderr
if !strings.Contains(combined, "bd note") || !strings.Contains(combined, "<issue-id>") {
t.Fatalf("expected hint pointing at bd note <issue-id>, got stdout=%q stderr=%q", stdout, stderr)
}
// The regression check: the bystander issue's notes must be UNCHANGED.
// Pre-fix, this could silently succeed and land a note on whatever
// bead's id happened to contain "list" as a substring.
showOut := runBDInProcess(t, tmpDir, "show", fullID, "--json")
var shown []map[string]interface{}
if err := json.Unmarshal([]byte(showOut), &shown); err != nil {
t.Fatalf("Failed to parse show JSON: %v\nOutput: %s", err, showOut)
}
if len(shown) == 0 {
t.Fatalf("expected show to return the bystander issue, got: %s", showOut)
}
notesAfter, _ := shown[0]["notes"].(string)
if notesAfter != notesBefore {
t.Fatalf("expected bystander issue %s notes unchanged after rejected 'note list' (before=%q after=%q)", fullID, notesBefore, notesAfter)
}
}
// TestCLI_NoteAddMisplacedSyntax mirrors TestCLI_NoteListMisplacedSyntax
// for the symmetric "add" typo — a caller who types "bd note add <id> <text>"
// (confusing note with comments-style "add") would parse as id="add",
// text=[<id>, <text>...].
func TestCLI_NoteAddMisplacedSyntax(t *testing.T) {
tmpDir := setupCLITestDB(t)
out := runBDInProcess(t, tmpDir, "create", "Bystander issue for add-typo", "-p", "1", "--json")
jsonStart := strings.Index(out, "{")
if jsonStart < 0 {
t.Fatalf("No JSON found in create output: %s", out)
}
var issue map[string]interface{}
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
}
fullID := issue["id"].(string)
// Snapshot notes BEFORE the rejected command (same order-independence
// rationale as TestCLI_NoteListMisplacedSyntax).
beforeShow := runBDInProcess(t, tmpDir, "show", fullID, "--json")
var beforeShown []map[string]interface{}
if err := json.Unmarshal([]byte(beforeShow), &beforeShown); err != nil {
t.Fatalf("Failed to parse pre-reject show JSON: %v\nOutput: %s", err, beforeShow)
}
if len(beforeShown) == 0 {
t.Fatalf("expected show to return the bystander issue before reject, got: %s", beforeShow)
}
notesBefore, _ := beforeShown[0]["notes"].(string)
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "note", "add", fullID, "accidental stray text")
if err == nil {
t.Fatalf("expected non-zero exit, got stdout=%q stderr=%q", stdout, stderr)
}
combined := stdout + stderr
if !strings.Contains(combined, "bd note") || !strings.Contains(combined, "<issue-id>") {
t.Fatalf("expected hint pointing at bd note <issue-id>, got stdout=%q stderr=%q", stdout, stderr)
}
showOut := runBDInProcess(t, tmpDir, "show", fullID, "--json")
var shown []map[string]interface{}
if err := json.Unmarshal([]byte(showOut), &shown); err != nil {
t.Fatalf("Failed to parse show JSON: %v\nOutput: %s", err, showOut)
}
if len(shown) == 0 {
t.Fatalf("expected show to return the bystander issue, got: %s", showOut)
}
notesAfter, _ := shown[0]["notes"].(string)
if notesAfter != notesBefore {
t.Fatalf("expected bystander issue %s notes unchanged after rejected 'note add' (before=%q after=%q)", fullID, notesBefore, notesAfter)
}
}
// TestCLI_NoteMisplacedSyntaxRejectedBeforeStoreOpen proves the guard
// fires from noteCmd's Args validator, before PersistentPreRunE ever
// opens a store, mirroring
// TestCLI_CommentMisplacedSyntaxRejectedBeforeStoreOpen for the comment
// sibling. Using a directory with no .beads/ at all proves the store was
// never touched: a RunE-only check would have failed first with "no beads
// database found".
func TestCLI_NoteMisplacedSyntaxRejectedBeforeStoreOpen(t *testing.T) {
noBeadsCwd := t.TempDir()
if _, err := os.Stat(filepath.Join(noBeadsCwd, ".beads")); err == nil {
t.Fatalf("test setup: %s unexpectedly has a .beads dir", noBeadsCwd)
}
stdout, stderr, err := runBDInProcessAllowError(t, noBeadsCwd, "note", "list", "should not be stored")
if err == nil {
t.Fatalf("expected non-zero exit for misplaced 'note list', got success:\nstdout: %s", stdout)
}
combined := stdout + stderr
if strings.Contains(combined, "no beads database found") {
t.Fatalf("Args validation did not run before store open: got the pre-fix error.\nOutput:\n%s", combined)
}
if !strings.Contains(combined, "bd note") {
t.Errorf("expected hint pointing to `bd note`, got:\n%s", combined)
}
}
// TestCLI_NoteMisplacedSyntaxRejectedInProxiedServerMode is the
// proxied-server counterpart, mirroring
// TestCLI_CommentMisplacedSyntaxRejectedInProxiedServerMode: because
// validateNoteArgs runs in Args — before RunE ever branches on
// usesProxiedServer() — the rejection fires identically regardless of
// backend, without needing a real proxied server.
func TestCLI_NoteMisplacedSyntaxRejectedInProxiedServerMode(t *testing.T) {
origProxied := proxiedServerMode
t.Cleanup(func() { proxiedServerMode = origProxied })
proxiedServerMode = true
tmpDir := setupCLITestDB(t)
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "note", "list", "should not be stored")
if err == nil {
t.Fatalf("expected non-zero exit for misplaced 'note list' in proxied-server mode, got success:\nstdout: %s", stdout)
}
combined := stdout + stderr
if !strings.Contains(combined, "bd note") {
t.Errorf("expected hint pointing to `bd note`, got:\n%s", combined)
}
}
// TestCLI_NoteTextStartingWithReservedWordStillWorks confirms the fix is
// scoped to the id positional argument only: a real id followed by note
// TEXT that happens to start with "list" or "add" must still work exactly
// as before, since args[0] (the id slot) is what's checked, never the text.
func TestCLI_NoteTextStartingWithReservedWordStillWorks(t *testing.T) {
tmpDir := setupCLITestDB(t)
out := runBDInProcess(t, tmpDir, "create", "Issue for reserved-word-text test", "-p", "1", "--json")
jsonStart := strings.Index(out, "{")
if jsonStart < 0 {
t.Fatalf("No JSON found in create output: %s", out)
}
var issue map[string]interface{}
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
}
fullID := issue["id"].(string)
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "note", fullID, "list", "of", "things", "to", "do")
if err != nil {
t.Fatalf("note with text starting in 'list' unexpectedly failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
}
if !strings.Contains(stdout, "Note added") {
t.Errorf("Expected 'Note added' in output, got: %s", stdout)
}
showOut := runBDInProcess(t, tmpDir, "show", fullID, "--json")
if !strings.Contains(showOut, "list of things to do") {
t.Fatalf("expected note text to be stored verbatim, got: %s", showOut)
}
}
func TestCLI_Close(t *testing.T) {
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
tmpDir := setupCLITestDB(t)

View file

@ -12,6 +12,93 @@ import (
"github.com/steveyegge/beads/internal/ui"
)
// validateNoteArgs runs as cobra's Args validation for "note", before RunE
// and (on the local/embedded path) before the id ever reaches
// ResolvePartialID's fuzzy/substring matching. Mirror of validateCommentArgs
// (#5369): "note" has no subcommands of its own — its only job is "append a
// note to <id>" — so when the id positional argument is exactly a reserved
// word that is a common subcommand-shaped typo, the near-certain explanation
// is not that a bead is genuinely named that word (real ids always carry a
// prefix+hyphen — see looksLikePrefixedID). Left unguarded, that word
// silently resolves via ResolvePartialID's substring/prefix fallback to
// whatever existing bead or wisp id happens to contain it, and the note
// lands on the WRONG issue with no error. (GH#5370)
//
// Denylist is broader than #5369's {list, add}: "show" is invited by this
// guard's own error text ("bd show <issue-id>"); "update" is invited by the
// guard's own hints referencing "bd update <issue-id>" four times; and
// edit/rm/remove/delete are common subcommand-shaped typos for mutating
// commands. Broader-than-#5369 matches the in-repo direction of PR #5393
// for the comment sibling.
func validateNoteArgs(cmd *cobra.Command, args []string) error {
if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
return err
}
switch args[0] {
case "list":
return HandleErrorRespectJSON(`"bd note list ..." is not valid — "note" takes an issue id first and has no "list" subcommand.
To append a note:
bd note <issue-id> "text"
To read notes on an issue:
bd show <issue-id>
See: bd note --help`)
case "add":
return HandleErrorRespectJSON(`"bd note add ..." is not valid — "note" already means "append a note" and takes an issue id first, not the word "add".
To append a note:
bd note <issue-id> "text"
(Equivalent long form: bd update <issue-id> --append-notes "text".)
See: bd note --help`)
case "show":
return HandleErrorRespectJSON(`"bd note show ..." is not valid — "note" takes an issue id first and has no "show" subcommand.
To read notes on an issue:
bd show <issue-id>
To append a note:
bd note <issue-id> "text"
See: bd note --help`)
case "edit":
return HandleErrorRespectJSON(`"bd note edit ..." is not valid — "note" only appends and has no "edit" subcommand.
To append a note:
bd note <issue-id> "text"
To change an issue field:
bd update <issue-id> --notes "text"
See: bd note --help`)
case "rm", "remove", "delete":
return HandleErrorRespectJSON(`"bd note %s ..." is not valid — "note" only appends and has no "%s" subcommand.
To append a note:
bd note <issue-id> "text"
To change or clear notes:
bd update <issue-id> --notes "text"
See: bd note --help`, args[0], args[0])
case "update":
return HandleErrorRespectJSON(`"bd note update ..." is not valid — "note" takes an issue id first and has no "update" subcommand.
To append a note:
bd note <issue-id> "text"
To set or append notes via the long form:
bd update <issue-id> --notes "text"
bd update <issue-id> --append-notes "text"
See: bd note --help`)
}
return nil
}
var noteCmd = &cobra.Command{
Use: "note <id> [text...]",
GroupID: "issues",
@ -24,8 +111,11 @@ Examples:
bd note gt-abc "Fixed the flaky test"
bd note gt-abc Fixed the flaky test
echo "note from pipe" | bd note gt-abc --stdin
bd note gt-abc --file notes.txt`,
Args: cobra.MinimumNArgs(1),
bd note gt-abc --file notes.txt
Note: "note" has NO subcommands — it only appends.
To read notes on an issue, use: bd show <id>`,
Args: validateNoteArgs,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {

51
cmd/bd/note_test.go Normal file
View file

@ -0,0 +1,51 @@
package main
import "testing"
// TestValidateNoteArgs is a pure unit test for the "note" command's Args
// guard — it calls the validator directly with no store, no Dolt, and no
// cobra dispatch, so it runs regardless of cgo/Docker availability.
// Message-content assertions for the two rejected cases live in the
// CLI-level TestCLI_Note{List,Add}MisplacedSyntax tests; this test only
// pins down which shapes are accepted vs rejected. Mirrors
// TestValidateCommentArgs (#5369) for GH#5370.
func TestValidateNoteArgs(t *testing.T) {
origJSONOutput := jsonOutput
jsonOutput = false
t.Cleanup(func() { jsonOutput = origJSONOutput })
cases := []struct {
name string
args []string
wantErr bool
}{
{name: "bare list is rejected (the reported typo)", args: []string{"list", "some text"}, wantErr: true},
{name: "bare list with no text is still rejected", args: []string{"list"}, wantErr: true},
{name: "bare add is rejected (mirrors comment swapped-add)", args: []string{"add", "some text"}, wantErr: true},
{name: "bare show is rejected (invited by show-hint error text)", args: []string{"show", "some text"}, wantErr: true},
{name: "bare edit is rejected", args: []string{"edit", "some text"}, wantErr: true},
{name: "bare rm is rejected", args: []string{"rm", "some text"}, wantErr: true},
{name: "bare remove is rejected", args: []string{"remove", "some text"}, wantErr: true},
{name: "bare delete is rejected", args: []string{"delete", "some text"}, wantErr: true},
{name: "bare update is rejected (invited by update-hint error text)", args: []string{"update", "some text"}, wantErr: true},
{name: "bare update with no text is still rejected", args: []string{"update"}, wantErr: true},
{name: "real id with text starting with the word list is fine", args: []string{"test-abc123", "list", "of", "things", "to", "do"}, wantErr: false},
{name: "real id with text starting with the word add is fine", args: []string{"test-abc123", "add", "one", "more", "item"}, wantErr: false},
{name: "real id with text starting with the word show is fine", args: []string{"test-abc123", "show", "me", "the", "notes"}, wantErr: false},
{name: "real id with text starting with the word update is fine", args: []string{"test-abc123", "update", "the", "notes", "please"}, wantErr: false},
{name: "real id alone (text comes from --stdin/--file) is fine", args: []string{"test-abc123"}, wantErr: false},
{name: "no args at all is rejected by the base MinimumNArgs check", args: []string{}, wantErr: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := validateNoteArgs(noteCmd, tc.args)
if tc.wantErr && err == nil {
t.Fatalf("validateNoteArgs(%q): expected an error, got nil", tc.args)
}
if !tc.wantErr && err != nil {
t.Fatalf("validateNoteArgs(%q): expected no error, got %v", tc.args, err)
}
})
}
}