beads/cmd/bd/metadata_flag_test.go
Harry Miller ce756a5b86
fix(metadata): require a JSON object for --metadata on create and update (#6035) (#6743)
* fix(metadata): require a JSON object for --metadata on create and update (#6035)

Root cause: the four --metadata entry points (create and update, each in
its direct and proxied-server variant: create.go, create_input.go,
update.go, update_input.go) carried copies of the same check, json.Valid,
which accepts any JSON value. `bd create --metadata '"oops"'` therefore
stored a bare string (or an array, number or null) as the issue's
metadata. `bd update` with the same value was refused only late, by the
storage-layer merge, with an internal unmarshal error.

Fix: one shared readMetadataFlag helper resolves the value (inline or
@file.json) and requires a top-level JSON object, refusing a string,
number, boolean, array or null with "invalid --metadata: must be a JSON
object such as {"key":"value"}, got <kind>". The rule matches what the
storage merge already enforces for update (it unmarshals into a map and
rejects null), so `{}` stays accepted and null is now refused on create
too, where it used to be stored literally. The storage layer is not
changed.

Not changed: an object whose value is a string that looks like JSON
(`{"mykey":"{\"inner\":\"v\"}"}`, the nested case in the report) is
still accepted and stored as written. Metadata values are opaque, and
refusing such strings would be a design change, not a fix.

Agent-Signature: claude-code-opus-5-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(metadata): cover boolean and null in the end-to-end create/update case (#6743 review)

Agent-Signature: claude-code-opus-5-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(metadata): correct the null-behavior claims and the --metadata help text (#6743 review)

Maintainer review fixups for #6743. The review found no blocker and no major,
and the scorecard approved with no required changes; these are its minors and
nits.

- The helper doc comment and the CHANGELOG entry both said the new object rule
  matches what the storage merge already enforced for update. That holds for a
  string, number, boolean or array, and is false for null: json.Unmarshal of
  the literal null into a map zeroes the map and returns no error, so
  MergeMetadataJSON merged nothing and `bd update --metadata null` exited 0.
  Refusing null is a real, if small, behavior change on update, so both
  surfaces now say that instead of claiming a non-change.

- The --metadata help text on create and update advertised "JSON string", the
  one input this change exists to refuse; both now read "JSON object". The
  generated CLI docs are deliberately not regenerated alongside it:
  docs/cli-docs.pin is v1.2.2, so generate-cli-docs.sh builds bd from that tag
  rather than from the checkout, and the committed pages are refreshed at
  release. Verified both ways -- with this edit alone, check-doc-flags.sh
  Check 4 reports "PASS: generated CLI docs are fresh"; hand-editing
  docs/cli-reference/create.md to the new string instead makes it report
  "FAIL: docs/cli-reference is out of sync with live CLI help".

- The `object == nil` arm of the guard is load-bearing and read as redundant to
  both reviewers, so it now says out loud that it is what catches null, and
  names internal/httpapi/batch_apply.go as the source of the idiom. Keeping the
  unmarshal rather than switching the guard to jsonKind preserves symmetry with
  that plane; the synthesis offered either.

- jsonKind's "empty input" arm is unreachable from both callers, which sit
  behind json.Valid. Documented as defensive rather than dropped, because
  dropping it makes the byte index below panic for any future caller that has
  not validated first.

- os.ReadFile's error is wrapped with %w, so callers of this newly shared
  helper can still reach fs.ErrNotExist.

The PR body asserts the same null premise in two places (its `null` table row
and the "keeps update's existing rule" bullet) and overstates HTTP-plane
enforcement; those are corrected at finalize, since review iterations do not
touch GitHub.

No behavior change beyond the help string. `go test ./cmd/bd -run GH6035`
passes; gofmt, go vet, check-doc-flags.sh and check-doc-freshness.sh clean.

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
2026-09-26 03:24:57 -07:00

135 lines
4.2 KiB
Go

package main
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/spf13/cobra"
)
// GH#6035: --metadata only checked json.Valid, so `bd create --metadata
// '"oops"'` stored a bare JSON string as the metadata, while `bd update`
// with the same value failed late in the storage merge. Both commands now
// require a top-level JSON object up front.
const metadataObjectErr = "invalid --metadata: must be a JSON object"
var nonObjectMetadata = []struct {
value string
kind string
}{
{`"oops"`, "a JSON string"},
{`[1,2]`, "a JSON array"},
{`42`, "a JSON number"},
{`true`, "a JSON boolean"},
{`null`, "JSON null"},
}
func TestReadMetadataFlagRequiresObjectGH6035(t *testing.T) {
for _, tt := range nonObjectMetadata {
t.Run(tt.value, func(t *testing.T) {
_, err := readMetadataFlag(tt.value)
if err == nil {
t.Fatalf("readMetadataFlag(%s) accepted a non-object", tt.value)
}
if !strings.Contains(err.Error(), metadataObjectErr) || !strings.Contains(err.Error(), tt.kind) {
t.Fatalf("readMetadataFlag(%s) error = %q, want %q naming %q", tt.value, err, metadataObjectErr, tt.kind)
}
})
}
// Objects pass through verbatim, including a string value that happens
// to look like JSON: values inside the object are opaque.
for _, value := range []string{`{}`, `{"a":1}`, ` {"mykey":"{\"inner\":\"v\"}"} `} {
got, err := readMetadataFlag(value)
if err != nil {
t.Fatalf("readMetadataFlag(%s): %v", value, err)
}
if string(got) != value {
t.Fatalf("readMetadataFlag(%s) = %s, want it unchanged", value, got)
}
}
if _, err := readMetadataFlag(`{"a":`); err == nil || !strings.Contains(err.Error(), "invalid JSON in --metadata") {
t.Fatalf("malformed JSON error = %v, want the invalid-JSON message", err)
}
dir := t.TempDir()
objPath := filepath.Join(dir, "obj.json")
strPath := filepath.Join(dir, "str.json")
if err := os.WriteFile(objPath, []byte(`{"from":"file"}`), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(strPath, []byte(`"oops"`), 0o600); err != nil {
t.Fatal(err)
}
if got, err := readMetadataFlag("@" + objPath); err != nil || string(got) != `{"from":"file"}` {
t.Fatalf("@file object = %s, %v", got, err)
}
if _, err := readMetadataFlag("@" + strPath); err == nil || !strings.Contains(err.Error(), metadataObjectErr) {
t.Fatalf("@file string error = %v, want %q", err, metadataObjectErr)
}
}
func TestGatherCreateInputRejectsNonObjectMetadataGH6035(t *testing.T) {
for _, tt := range nonObjectMetadata {
t.Run(tt.value, func(t *testing.T) {
cmd := newCreateFlagsCommand(t, "--title", "Title", "--metadata", tt.value)
var err error
stderr := captureStderr(t, func() {
_, err = gatherCreateInput(cmd, nil)
})
if err == nil {
t.Fatalf("gatherCreateInput accepted --metadata %s", tt.value)
}
if !strings.Contains(stderr, metadataObjectErr) {
t.Fatalf("stderr = %q, want %q", stderr, metadataObjectErr)
}
})
}
cmd := newCreateFlagsCommand(t, "--title", "Title", "--metadata", `{"a":1}`)
in, err := gatherCreateInput(cmd, nil)
if err != nil {
t.Fatalf("gatherCreateInput with an object: %v", err)
}
if string(in.metadata) != `{"a":1}` || !in.metadataSet {
t.Fatalf("metadata = %q, set = %t", in.metadata, in.metadataSet)
}
}
func TestGatherUpdateInputRejectsNonObjectMetadataGH6035(t *testing.T) {
newCmd := func(value string) *cobra.Command {
cmd := &cobra.Command{Use: "update"}
cmd.Flags().String("metadata", "", "Set custom metadata")
if err := cmd.ParseFlags([]string{"--metadata", value}); err != nil {
t.Fatalf("parse update flags: %v", err)
}
return cmd
}
for _, tt := range nonObjectMetadata {
t.Run(tt.value, func(t *testing.T) {
var err error
stderr := captureStderr(t, func() {
_, err = gatherUpdateInput(context.Background(), newCmd(tt.value))
})
if err == nil {
t.Fatalf("gatherUpdateInput accepted --metadata %s", tt.value)
}
if !strings.Contains(stderr, metadataObjectErr) {
t.Fatalf("stderr = %q, want %q", stderr, metadataObjectErr)
}
})
}
in, err := gatherUpdateInput(context.Background(), newCmd(`{"a":1}`))
if err != nil {
t.Fatalf("gatherUpdateInput with an object: %v", err)
}
if string(in.mergeMetadataIn) != `{"a":1}` {
t.Fatalf("mergeMetadataIn = %q", in.mergeMetadataIn)
}
}