Reject "list"/"add" as the id in the singular "comment" shorthand (#5369)

"bd comment <id> [text...]" had no validation on the id positional
argument. Typing "bd comment list <text>" (confusing the singular
shorthand with the plural "bd comments list" guard) parsed as
id="list", text=[<text>...], and since no issue is literally named
"list", ResolvePartialID's substring/prefix fallback would silently
match "list" against whatever existing bead or wisp id happened to
contain it as a prefix (after wisp- stripping) and post the comment
there instead of erroring — no warning, no error, wrong issue mutated.

- Add validateCommentArgs, wired as commentCmd's Args validator
  (mirrors comments.go's validateCommentsArgs), rejecting "list" and
  "add" as the id with a message pointing at the correct invocation.
  Runs before RunE's usesProxiedServer() dispatch, so both backends
  reject identically.
- Note the restriction in commentCmd's --help text.
- Add TestValidateCommentArgs (pure unit test, no store needed) plus
  CLI-level regression tests mirroring the existing
  TestCLI_CommentsListMisplacedSyntax /
  TestCLI_CommentsSwappedAddRejectedBeforeStoreOpen /
  ...RejectedInProxiedServerMode trio for the plural sibling, plus one
  confirming text that merely starts with "list"/"add" still works
  (only the id slot is checked, never the text).

Manually verified end-to-end against both a pre-fix and post-fix
build: with a bead whose id contains "list" (mirroring a real
production incident), the unpatched binary silently posts the stray
comment there (exit 0); the fixed binary rejects the command (exit 1)
and the bead's comment count stays at zero.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Athos Bernardes 2026-08-07 09:49:46 -03:00 • committed by GitHub
commit 6ec150f8b9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 254 additions and 2 deletions

View file

@ -1402,6 +1402,173 @@ func TestCLI_CommentsAddShortID(t *testing.T) {
})
}
// TestCLI_CommentListMisplacedSyntax is a regression test for the singular
// "comment" shorthand silently mis-resolving a subcommand-like typo as an
// issue id. "bd comment list <text>" (meant as an attempt to list comments,
// using the singular noun by mistake) 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 post the comment there instead of
// erroring. This asserts both halves of the fix: the command is rejected
// with a helpful hint (mirroring TestCLI_CommentsListMisplacedSyntax for
// the plural sibling), AND — the part that actually matters for this
// specific bug — no comment silently landed on an unrelated real issue.
func TestCLI_CommentListMisplacedSyntax(t *testing.T) {
t.Parallel()
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)
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", "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 comments") || !strings.Contains(combined, "<issue-id>") {
t.Fatalf("expected hint pointing at bd comments <issue-id>, got stdout=%q stderr=%q", stdout, stderr)
}
// The regression check: the bystander issue must have received NO
// comment. Pre-fix, this could silently succeed and land a comment on
// whatever bead's id happened to contain "list" as a substring — this
// DB has exactly one issue, so any stray write would show up here.
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
trimmed := strings.TrimSpace(commentsOut)
if trimmed != "[]" && trimmed != "null" {
t.Fatalf("expected no comments on bystander issue %s after rejected 'comment list', got: %s", fullID, commentsOut)
}
}
// TestCLI_CommentAddMisplacedSyntax mirrors TestCLI_CommentListMisplacedSyntax
// for the symmetric "add" typo — a caller who confuses the singular shorthand
// with the plural's "bd comments add <id> <text>" form might type
// "bd comment add <id> <text>", which the same unguarded id-resolution bug
// would parse as id="add", text=[<id>, <text>...].
func TestCLI_CommentAddMisplacedSyntax(t *testing.T) {
t.Parallel()
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)
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", "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 comments add") {
t.Fatalf("expected hint pointing at bd comments add <issue-id>, got stdout=%q stderr=%q", stdout, stderr)
}
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
trimmed := strings.TrimSpace(commentsOut)
if trimmed != "[]" && trimmed != "null" {
t.Fatalf("expected no comments on bystander issue %s after rejected 'comment add', got: %s", fullID, commentsOut)
}
}
// TestCLI_CommentMisplacedSyntaxRejectedBeforeStoreOpen proves the guard
// fires from commentCmd's Args validator, before PersistentPreRunE ever
// opens a store, mirroring
// TestCLI_CommentsSwappedAddRejectedBeforeStoreOpen for the plural 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_CommentMisplacedSyntaxRejectedBeforeStoreOpen(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, "comment", "list", "should not be stored")
if err == nil {
t.Fatalf("expected non-zero exit for misplaced 'comment 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 comments") {
t.Errorf("expected hint pointing to `bd comments`, got:\n%s", combined)
}
}
// TestCLI_CommentMisplacedSyntaxRejectedInProxiedServerMode is the
// proxied-server counterpart, mirroring
// TestCLI_CommentsSwappedAddRejectedInProxiedServerMode: because
// validateCommentArgs runs in Args — before RunE ever branches on
// usesProxiedServer() — the rejection fires identically regardless of
// backend, without needing a real proxied server.
func TestCLI_CommentMisplacedSyntaxRejectedInProxiedServerMode(t *testing.T) {
origProxied := proxiedServerMode
t.Cleanup(func() { proxiedServerMode = origProxied })
proxiedServerMode = true
tmpDir := setupCLITestDB(t)
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", "list", "should not be stored")
if err == nil {
t.Fatalf("expected non-zero exit for misplaced 'comment list' in proxied-server mode, got success:\nstdout: %s", stdout)
}
combined := stdout + stderr
if !strings.Contains(combined, "bd comments") {
t.Errorf("expected hint pointing to `bd comments`, got:\n%s", combined)
}
}
// TestCLI_CommentTextStartingWithReservedWordStillWorks confirms the fix is
// scoped to the id positional argument only: a real id followed by comment
// 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_CommentTextStartingWithReservedWordStillWorks(t *testing.T) {
t.Parallel()
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, "comment", fullID, "list", "of", "things", "to", "do")
if err != nil {
t.Fatalf("comment with text starting in 'list' unexpectedly failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
}
if !strings.Contains(stdout, "Comment added") {
t.Errorf("Expected 'Comment added' in output, got: %s", stdout)
}
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
if !strings.Contains(commentsOut, "list of things to do") {
t.Fatalf("expected comment text to be stored verbatim, got: %s", commentsOut)
}
}
// TestCLI_CreateRejectsFlagLikeTitles verifies that positional arguments starting
// with - or -- are rejected as likely misinterpreted flags (bd-2c0).
func TestCLI_CreateRejectsFlagLikeTitles(t *testing.T) {

View file

@ -11,6 +11,46 @@ import (
"github.com/steveyegge/beads/internal/ui"
)
// validateCommentArgs runs as cobra's Args validation for the singular
// "comment" shorthand, before RunE's usesProxiedServer() dispatch and (on
// the local/embedded path) before the id ever reaches ResolvePartialID's
// fuzzy/substring matching. "comment" has no subcommands of its own — its
// only job is "add a comment to <id>" — so when the id positional argument
// is exactly a word that IS a real subcommand on the plural sibling ("list",
// "add"), the near-certain explanation is that the caller confused the
// singular and plural forms, not that a bead is genuinely named "list" or
// "add" (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 comment lands on the WRONG issue with no error.
func validateCommentArgs(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 comment list ..." is not valid — "comment" (singular) takes an issue id first and has no "list" subcommand.
To list comments on an issue:
bd comments <issue-id>
To add a comment:
bd comment <issue-id> "text"
See: bd comment --help`)
case "add":
return HandleErrorRespectJSON(`"bd comment add ..." is not valid — "comment" (singular) already means "add a comment" and takes an issue id first, not the word "add".
To add a comment:
bd comment <issue-id> "text"
("add" is only a subcommand of the plural form: bd comments add <issue-id> "text".)
See: bd comment --help`)
}
return nil
}
var commentCmd = &cobra.Command{
Use: "comment <id> [text...]",
GroupID: "issues",
@ -23,8 +63,11 @@ Examples:
bd comment bd-123 "Working on this now"
bd comment bd-123 Working on this now
echo "comment from pipe" | bd comment bd-123 --stdin
bd comment bd-123 --file notes.txt`,
Args: cobra.MinimumNArgs(1),
bd comment bd-123 --file notes.txt
Note: "comment" (singular) only adds a comment — it has no "list" subcommand.
To list comments on an issue, use the plural form: bd comments <id>`,
Args: validateCommentArgs,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {

42
cmd/bd/comment_test.go Normal file
View file

@ -0,0 +1,42 @@
package main
import "testing"
// TestValidateCommentArgs is a pure unit test for the singular "comment"
// shorthand'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_Comment{List,Add}MisplacedSyntax tests alongside the
// plural sibling's equivalents; this test only pins down which shapes are
// accepted vs rejected.
func TestValidateCommentArgs(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 comments swapped-add)", args: []string{"add", "some text"}, 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 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 := validateCommentArgs(commentCmd, tc.args)
if tc.wantErr && err == nil {
t.Fatalf("validateCommentArgs(%q): expected an error, got nil", tc.args)
}
if !tc.wantErr && err != nil {
t.Fatalf("validateCommentArgs(%q): expected no error, got %v", tc.args, err)
}
})
}
}