beads/cmd/bd/metadata_flag.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

78 lines
2.9 KiB
Go

package main
import (
"encoding/json"
"fmt"
"os"
"strings"
)
// readMetadataFlag resolves a --metadata flag value (inline JSON, or
// @file.json to read it from a file) and requires it to be a JSON object.
//
// create and update share it so both commands, proxied or not, agree on the
// shape (GH#6035). `{}` is accepted; a bare string, number, boolean, array,
// or null is refused here with a clear message instead of being stored as-is
// (create) or failing late in the merge (update).
//
// That is close to, but not the same as, what the storage merge enforced for
// update. storage.MergeMetadataJSON unmarshals the incoming document into a
// map, which rejects a string, number, boolean or array with an internal
// error -- but JSON null unmarshals into a map with no error at all, so
// `bd update --metadata null` used to exit 0 having merged nothing. Refusing
// null up front is therefore a deliberate (small) behavior change on update,
// not a restatement of the merge's rule.
//
// Values inside the object are opaque, so a string value that happens to look
// like JSON is kept verbatim.
func readMetadataFlag(value string) (json.RawMessage, error) {
metadataJSON := value
if strings.HasPrefix(value, "@") {
filePath := value[1:]
// #nosec G304 -- user explicitly provides file path via @file.json syntax
data, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("failed to read metadata file %s: %w", filePath, err)
}
metadataJSON = string(data)
}
if !json.Valid([]byte(metadataJSON)) {
return nil, fmt.Errorf("invalid JSON in --metadata: must be valid JSON")
}
var object map[string]json.RawMessage
// The nil check is the arm that catches `null`: unmarshalling the JSON
// literal null into a map zeroes the map and reports no error, so testing
// err alone would let null through. Same idiom as the metadata checks in
// internal/httpapi/batch_apply.go.
if err := json.Unmarshal([]byte(metadataJSON), &object); err != nil || object == nil {
return nil, fmt.Errorf(`invalid --metadata: must be a JSON object such as {"key":"value"}, got %s`, jsonKind(metadataJSON))
}
return json.RawMessage(metadataJSON), nil
}
// jsonKind names the top-level kind of a valid JSON document for error text.
//
// The "empty input" arm is defensive, not a reachable case for the caller
// above: json.Valid is false for both "" and whitespace-only input, so a
// document that has already passed it can never trim to empty. It keeps the
// byte index below safe for any future caller that has not validated first.
func jsonKind(doc string) string {
trimmed := strings.TrimSpace(doc)
if trimmed == "" {
return "empty input"
}
switch trimmed[0] {
case '"':
return "a JSON string"
case '[':
return "a JSON array"
case 't', 'f':
return "a JSON boolean"
case 'n':
return "JSON null"
case '{':
return "a JSON object"
default:
return "a JSON number"
}
}