beads/internal/httpapi/update_template_test.go
Julian Knutsen f21e3a80f7
fix(issueops): templates are read-only on every update leg (#7427)
* fix(issueops): enforce the template read-only update guard on every leg

The refusal of an update to a template (validateIssueUpdatable) lived only
in cmd/bd as a pre-read, so PATCH /v0/beads/issues/{id}, batch:apply update
items and library callers of Lifecycle.Update / BatchApplier edited
templates that `bd update` refused.

It is now one role rule, storage issueops.AuthorizeTemplateUpdate, returning
*issueops.TemplateReadOnlyError (matches ErrTemplateReadOnly; the message is
the sentence bd always printed). It runs in the update's own transaction,
after the compare-and-set preconditions (a stale guard still reports the
mismatch), and no force flag waives it:
- ExecuteUpdate (dolt, embedded) and the uow Update and batch update legs;
- the batch apply metadata splice that finishes a create item stays
  unguarded on both bodies (a template the request creates is not modified);
- httpapi maps it to 409 template_read_only on updateIssue and applyBatch
  (spec x-bd-codes and descriptions updated, apigen regenerated) and the
  client rebuilds the typed error.

UpdateRequest.AllowTemplate stands the guard down for one request: the
caller edits a template deliberately. bd label (add, remove, remove-prefix)
and bd set-state set it, so they keep editing templates on every route, as
on origin/main. Over HTTP it is the optional `allow_template` member of the
PATCH body, advertised by the issues.update.allowTemplate behavior token,
which also says the server enforces the guard. httpclient Lifecycle.Update
decides from the cached handshake before the dial: against a server without
the token (no guard, no member) it runs the same rule
(AuthorizeTemplateUpdate) on a pre-read and never sends allow_template, so a
new bd against an older bd serve still refuses template updates.

cmd/bd: bd update, bd assign and the proxied assign/tag drop their pre-read
and print the role's refusal with the same line and exit code.

Conformance: RunLifecycleUpdateRefusesATemplate,
RunLifecycleUpdateAllowTemplateEditsATemplate,
RunBatchApplyUpdateItemsRefuseATemplate and
RunBatchApplySplicesTheMetadataOfATemplateItCreates on dolt, embedded, uow
and http (the http splice case is parked: the v0 create item has no
is_template member), plus handler and CLI rendering tests, and
TestUpdateTemplateGuardAgainstAServerThatPredatesIt (new client, handshake
without the token: refused before the dial, allow_template not sent).

Skew note (CHANGELOG): an older bd label / bd set-state against a new server
cannot send allow_template and now gets 409 template_read_only on a template.
bd comment, note, priority and tag keep their CLI-only pre-read guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(issueops): scope template read-only docs to updates, test label stand-down

Review fixups for PR 7427 (adopt-pr review loop, iteration 1):

- Contract: the role guard covers updates, not every mutation. The
  CHANGELOG headline, ErrTemplateReadOnly and CodeTemplateReadOnly now
  say so, and "Not yet moved" names claim, reopen, :casMetadata and the
  served addComment, which have no template check yet (a PATCH with
  claim: true refuses a template that POST :claim still claims). Close
  is #7425's. Follow-up: bd-jkp9v3.
- Skew: the CapIssuesUpdateAllowTemplate client fallback covers
  updateIssue only. A batch update item gets no client-side check, so
  through an older bd serve it still edits a template; the CHANGELOG
  and both capability docs say so.
- Tests: a template row now goes through the CLI on both tiers
  (TestEmbeddedLabelEditReports, TestProxiedServerLabelC). bd label add,
  bd label remove --prefix and bd set-state edit it (AllowTemplate);
  bd update --title and bd assign exit 1 with the template sentence and
  leave it unchanged. Mutants: dropping AllowTemplate from label.go and
  state.go reds the three edits on both tiers; disabling
  AuthorizeTemplateUpdate reds update and assign on both tiers.
- Stale comments: runTagProxiedServer, applyUpdateProxiedOne,
  proxiedUpdateTarget, UpdateFlags (five booleans, not four) and the
  ItemUpdate notes in applyLabelEdit and bd label propagate's proxied
  route (UpdateItem has no AllowTemplate).

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 16:25:37 +00:00

107 lines
4.3 KiB
Go

package httpapi
import (
"fmt"
"net/http"
"strings"
"testing"
"github.com/steveyegge/beads/issueops"
)
// The template guard is the ROLE's (issueops.Lifecycle.Update, and the batch
// applier's update items, which share its body), so these cases drive a fake
// role that refuses the way the real one does and pin what the wire makes of
// it. The real role behind a real server is the served leg of the conformance
// contracts (internal/httpclient: TestServedLifecycleUpdateRefusesATemplate and
// TestServedBatchApplyUpdateItemsRefuseATemplate), which also proves the client
// rebuilds the typed error.
// templateRefusal is the refusal as a unit-of-work backend returns it: wrapped,
// so the mapping has to find it by type rather than by being handed the value.
func templateRefusal() error {
return fmt.Errorf("update bd-1: %w", &issueops.TemplateReadOnlyError{IssueID: "bd-1"})
}
func assertTemplateDetailIsOurs(t *testing.T, detail any) {
t.Helper()
text, _ := detail.(string)
if text == "" || strings.Contains(text, "cannot modify template") {
t.Errorf("detail = %q, want this server's own sentence rather than the role's", text)
}
}
func TestUpdateOfATemplateIsATypedConflict(t *testing.T) {
lifecycle := &roleLifecycle{updateErr: templateRefusal()}
ts := newUpdateServer(t, lifecycle)
resp := ts.updateIssue(t, updatePath, `{"actor":"alice","patch":{"title":"edited"},"force_close_policy":true}`)
if resp.StatusCode != http.StatusConflict {
t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeTemplateReadOnly) {
t.Errorf("code = %v, want %s", body["code"], CodeTemplateReadOnly)
}
assertTemplateDetailIsOurs(t, body["detail"])
// The handler decides nothing: the request reached the role whole, force
// flag included, and the refusal is the role's.
if got := lifecycle.updateRequests(); len(got) != 1 || !got[0].ForceClosePolicy {
t.Fatalf("the role received %+v, want one request carrying ForceClosePolicy", got)
}
}
func TestApplyBatchUpdateItemOnATemplateIsATypedConflict(t *testing.T) {
applier := &roleBatchApplier{err: itemErr(1, issueops.ItemUpdate, "", "bd-1", templateRefusal())}
ts := newApplyBatchServer(t, applier)
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[{"kind":"create","create":{"title":"one"}}]}`)
if resp.StatusCode != http.StatusConflict {
t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeTemplateReadOnly) {
t.Errorf("code = %v, want %s", body["code"], CodeTemplateReadOnly)
}
if body["item_index"] != float64(1) || body["item_kind"] != "update" || body["item_issue_id"] != "bd-1" {
t.Errorf("item members = %v/%v/%v, want 1/update/bd-1", body["item_index"], body["item_kind"], body["item_issue_id"])
}
assertTemplateDetailIsOurs(t, body["detail"])
}
// TestUpdateCarriesAllowTemplateToTheRole pins that `allow_template` is decoded
// onto the role request and nothing else: the role owns what it waives.
func TestUpdateCarriesAllowTemplateToTheRole(t *testing.T) {
for _, tc := range []struct {
body string
want bool
}{
{`{"actor":"alice","patch":{"title":"edited"},"allow_template":true}`, true},
{`{"actor":"alice","patch":{"title":"edited"},"allow_template":false}`, false},
{`{"actor":"alice","patch":{"title":"edited"}}`, false},
} {
lifecycle := &roleLifecycle{updateResult: issueops.UpdateResult{Issue: updatedIssue("bd-1"), Changed: true}}
ts := newUpdateServer(t, lifecycle)
resp := ts.updateIssue(t, updatePath, tc.body)
if resp.StatusCode != http.StatusOK {
t.Fatalf("%s: status = %d, want 200: %s", tc.body, resp.StatusCode, readAll(t, resp))
}
_ = resp.Body.Close()
got := lifecycle.updateRequests()
if len(got) != 1 || got[0].AllowTemplate != tc.want {
t.Errorf("%s: the role received %+v, want AllowTemplate=%v", tc.body, got, tc.want)
}
}
}
func TestUpdateRefusesANonBooleanAllowTemplate(t *testing.T) {
lifecycle := &roleLifecycle{}
ts := newUpdateServer(t, lifecycle)
resp := ts.updateIssue(t, updatePath, `{"actor":"alice","patch":{"title":"edited"},"allow_template":"yes"}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
if got := lifecycle.updateRequests(); len(got) != 0 {
t.Errorf("the role was reached with %+v", got)
}
}