beads/internal/httpapi/sweep_test.go
Julian Knutsen 2dda7052e0
feat(httpclient): write-role conformance on the http leg — ceiling to zero, sweeper extension (S4) (#7251)
* feat(httpclient): wire the S4 Sweeper extension (wisps-plane, live-dependent protection, limit)

Publish SweepRequest.ProtectLiveDependents and .Limit (plus a
wisps-plane tier and SweepResult.Remaining/.LiveDependent) on the v0
wire behind three new behavior-capability tokens
(issues.sweep.wispsPlane, issues.sweep.liveDependents,
issues.sweep.limit), and wire the client to send them once the
handshake advertises the tokens (refuseUnservedSweep otherwise).
Retire the two W-SweepRequest ledger rows that previously refused
these fields for lack of a wire member.

CurrentWireRevision stays at 2. A new wisps-plane SweepRequest.Tier
value is a request-only enum widening: it cannot cause an older
client to misdecode a response, and it is already gated by its own
capability token, so it is additive rather than a wire break. Teach
wireshape's drift gate that distinction directly: a Digest.Sides side
channel records whether each schema member is request-only,
response-only or both, and widensAdditively now treats a request-only
enum's new value as additive while still treating any response-side
widening as breaking, with tests pinning both directions and a
regenerated golden.json. min_client_wire_revision stays 0.
internal/httpapi/apigen/types.gen.go and openapi.v0.yaml's comments are
regenerated/updated to match (make api-gen).

Six served Sweeper contracts that were parked now run for real against
the in-process HTTP server; TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem
pins the capability-gated encode.

Re-review fix: walk()'s side classification short-circuited on a
name-only visited set, so a node already walked from one side never
had its CHILDREN walked again when a later path promoted the parent
to "both" — children stayed classified under whichever side reached
them first, order-dependent on Go's map iteration. Side recursion is
now guarded per (schema, side) pair (sideWalked, keyed on
name+"\x00"+side) instead of per schema name alone, so a child
reachable from both sides is always walked, and therefore recorded,
from both. Added TestSidePropagatesToNestedChildren (a named grandchild
and an inline nested child both reachable from a request body and,
via a wrapper, a response, assert "both" on every level and that
widening either enum breaks instead of being classed additive),
TestEnumWideningOnSharedNestedChildIsNotAdditive, and
TestComputeFromSideAssignmentIsDeterministic (200 runs, asserts
identical Sides/Entries every time). golden.json is confirmed
unchanged by the fix (regenerated and diffed byte-for-byte). Also
removes a bd-enterprise mention introduced in this slice's own
write_ledger_test.go comment (not a provenance header) in favor of
neutral wording.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(storage): ratchet the http leg's role-contract ceiling to zero

Classify all 42 previously-ceilinged http-leg entrypoints and clear
the ceiling:

- ExpectedRevision + Refusal (10): wire a Phase-0 all-nil fixture,
  matching every other backend's current (unbuilt-CAS-feature) state.
  Said honestly: these ten entrypoints are counted here, the hook is
  unbuilt on every leg (not just this one), and every case runs zero
  assertions until a CompareAndSetVersion wire operation exists for
  this client to bind.
- Lifecycle ExpectedVersion concurrency (4): wire the two races that
  land on Priority/Notes and on Close for real over the served HTTP
  harness (precondition_failed decodes to storage.ErrVersionMismatch
  via errors.Is, same as the local legs). The other two, which race
  IssuePatch.SpecID/.AwaitID/.Owner edits against updateIssue, stay
  waived, but PENDING rather than permanent: IssuePatchBody refuses
  those three fields outright (W-IssuePatch.SpecID/.AwaitID/.Owner,
  D8 refuse-not-drop) rather than ever sending them, so the race never
  reaches the wire today. Closing the gap means publishing those
  fields on the wire, tracked as a follow-up slice, S4b: publish
  owner/spec_id/await_id on the wire.
- DualWrite (6): wired for real instead of waived. Mutate and
  MutateAsNoOp drive the client's Lifecycle role (Create/Update)
  against an in-process served harness with its own reference store,
  so VersionedHistoryConfigurer can be toggled per fixture;
  CurrentRevision, VersionRowCount and LatestVersionAttribution read
  the reference store's raw columns the same way every other served
  fixture's postcondition hooks do. All six FR-1/FR-2/FR-3/FR-5/FR-7
  cases (one version row per accepted mutation, no-op skip, atomic
  attribution, current_revision parity, and flag-off producing no
  rows) now run and pass.
- VersionReconciler + InitVerifier (13), and the raw
  IssueOperationsUpdate seam (3): waived — unservable over a typed
  HTTP role boundary, not a wiring gap.

adoptionCeiling: 42 -> 0 for the http leg; the "adopting" field is
removed (a zero ceiling with a reason is a registry error) since every
remaining gap is now a named waiver, PENDING or permanent as stated
above, instead of a budgeted unnamed one. Also deletes the scratch
zzz_dump_missing_test.go used to enumerate the ceiling during triage.

Re-review fix: the shared conformance attribution case only asserts
change_actor is non-empty (it runs across every leg, each with a
different literal Mutate actor). The http fixture's own Mutate always
sends Actor: "writer", so this leg's AttributionIsRecordedWithTheMutation
subtest now also mutates a second, independent issue and asserts the
recorded actor equals exactly "writer", in addition to the shared
non-empty check.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(types): make ParseRevisionToken the exact inverse of FormatInt

ParseRevisionToken's doc comment already promised it accepts exactly
what RevisionToken emits, but strconv.ParseInt alone is looser than
that: besides a leading "+" that FormatInt never produces, it also
accepts a leading zero on a digit string longer than one character
("007") and the literal "-0" — none of which FormatInt ever emits
(FormatInt(0, 10) is always "0", never "-0", and it never pads a
digit run). A caller is only ever supposed to echo a token a response
carried, so any of these is a client that invented a value rather
than a server this client should follow; reject them explicitly
instead of accepting them silently.

Pins the string<->int64 boundary with
TestParseRevisionTokenRejectsMalformedTokens, covering empty strings,
fractional/exponent spellings, leading "+", surrounding whitespace,
non-decimal bases, one-past-int64-boundary values, non-ASCII digits,
and now "007", "-007" and "-0".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fixup(wireshape): guard widensAdditively against "no enum before"

bee-ghosttrack / CHANGES_REQUESTED on #7251: widensAdditively required
len(new.Enum) > len(old.Enum), which holds vacuously when the old side
has no enum at all (a free `type: string`). That let a request-only
member go from unconstrained to a fixed enum at the same wire_revision
-- the opposite of widening, since the server now 400s a value an old
client could send yesterday.

Add the guard `len(old.Enum) == 0 || len(new.Enum) <= len(old.Enum) ->
false` so the no-enum-before case falls through to the ordinary
non-additive Changed path, same as a strict narrowing. Add a pinning
case to TestEnumWideningAdditivity and extend the doc comment.

Also reword the ExpectedRevision contract file comment from "runs ZERO
assertions" to "SKIPS", per the reviewer's note that the Run* helpers
t.Skip when CompareAndSetVersion is nil -- it's a skip, not an
assertion-free run.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(httpclient): regenerate the divergence ledger after rebasing onto #7247's review fixes

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(httpclient): Sweep Limit now refuses on the missing issues.sweep.limit capability

#7247's review round pinned Sweep{Limit} as an encoder refusal. With S4 the
wire carries limit behind issues.sweep.limit, so against a server without
the token the refusal is a pre-dial capability refusal: still
*storage.ErrUnsupported for this backend, now naming the capability.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(httpapi,httpclient): name the invalid_value refusal; add tests to Bazel

Maintainer fixup for the review of #7251 (iteration 1). There are no blocker or
major findings. This applies the three optional findings that both reviewers
reported.

- Eight comment and description sites added by this PR say that an older
  server refuses an unpublished `tier` (or S4) member with `unknown_value`.
  No such reason exists. The server refuses with ReasonInvalidValue =
  "invalid_value" (internal/httpapi/problem.go), and sweep.go uses it for a
  bad tier. The sites are in openapi.v0.yaml, apigen/types.gen.go (regenerated
  by `make api-gen`), routes.go, sweeper.go and wire/handshake.go. The base has
  none of them, so this only corrects the PR's own text. A client author now
  matches the token the server actually sends.
- wire/handshake.go said the tier member carries no ledger row because it
  "narrows" an existing enum. Adding a value widens the accepted set, so the
  word is now "widens".
- internal/httpclient/BUILD.bazel: add expected_revision_contract_test.go and
  served_dualwrite_history_test.go to the httpclient_test srcs. Both files are
  new in this PR. Without the entries, `go test` runs them but no Bazel lane
  compiles them. The srcs list now matches the package's files, and the
  existing deps already cover their imports.

Provenance: this is the residue of the stranded fixup cad1cf02a2 from the
previous adoption of this PR, replayed onto the current head. Its patch-id
(b62e7d6d5562) is identical to that reviewed residue. That fixup's
widensAdditively guard and SKIP-message nit are not repeated here. The author
already landed both in b3f1516e55 (d41f317e0a after the rebase).

Validation: git diff --check; make api-gen (no-op) and make api-check;
go build, go vet and gofmt on internal/httpapi/... and internal/httpclient/...;
go test for internal/httpclient/wire, internal/httpclient/encode and
test/docsync; the httpclient Sweep* and TestExpectedRevisionContract tests; the
served dual-write tests with BEADS_TEST_EMBEDDED_DOLT=1; and
tools/bazel/go_srcs.py --check.

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

* docs(httpclient): regenerate the divergence ledger on main after #7247 merged

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(httpclient): give encode_test the httpclient tests its pin check reads

Maintainer fixup for the pre-review CI of #7251. Bazel / test and
Bazel / integration (PR run 37781419956) each fail one target,
//internal/httpclient/encode:encode_test, which also fails CI Gate / Required.
TestLedgerRowsAreWellFormed reports that rows W-SweepRequest.ProtectLiveDependents
and W-SweepRequest.Limit are pinned by
TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem, which is "neither a test
in this package nor a TODO(<bead>)".

The pin is right. The test lives in internal/httpclient/bulk_roles_test.go.
testFunctionsInThisPackage collects test names from ".", ".." and
../../../cmd/bd, but the data of encode_test declares only its own sources,
//cmd/bd:go_srcs, the ledger doc and the OpenAPI spec. Under Bazel, ".."
exists in the runfiles but holds no _test.go files, so the walk silently finds
nothing there. go test reads the real directory and passes. This PR changes
neither the walk nor the BUILD file. Every pin on main resolves from this
package or cmd/bd, which is why main is green. These two rows are the only ones
pinned to a test that exists only in internal/httpclient. The red stayed hidden
until now because the PR sat on a stacked base. PR CI, including the Bazel
lanes, runs only for PRs against main, release/** and hotfix/**.

Declare //internal/httpclient:go_srcs as data, so Bazel sees the files that
go test reads. The filegroup already exists with //:__subpackages__ visibility.
The pins stay on the test that actually covers the S4 members.

Validation: bazel test //internal/httpclient/encode:encode_test --config=ci
--nocache_test_results, run two ways. In the local processwrapper sandbox
(--remote_executor= --strategy=TestRunner=processwrapper-sandbox) the same
command fails both rows without this change and passes with it. It also passes
on the remote executor. Plus tools/bazel/go_srcs.py --check, gazelle
-mode=diff on the package (no change), git diff --check, and
go test ./internal/httpclient/encode/.

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

* fix(httpapi): pin the S4 sweep members at the wire edge, gate golden sides

The `sides` map this change adds to golden.json predates schemas main gained
since (#7248's BatchGetIssue*, BatchGetIssuesRequest* and
BatchGetIssuesResult*, plus IssueDetails.gated_by[]), so the rebase left it 9
schemas short of what gendigest writes, and goldenDrift never compared Sides,
so nothing noticed. Regenerated (+9 sides lines, no entry changes), and
goldenDrift now fails with the regenerate instruction when the golden's sides
disagree with a fresh digest; TestGoldenDrift drives that arm three ways.

The SweepSkips description still called the first two buckets protections
and the last four defenses, which filed the new live_dependent protection
under the defenses. It now names pinned, referenced and live_dependent as the
protections (apigen regenerated: the two comment copies only), and
handleSweep's comment counts eight members.

internal/httpapi's sweep pins stopped at the original six members: nothing
there sent protect_live_dependents or limit, refused a mistyped one, or read
live_dependent or remaining back. The forward, refuse and publish tests now
cover all four, and TestSweepResponseCarriesEveryRoleField, named by
sweepResponse's comment but never written, counts both projection levels and
requires every wire field populated from a fully set role result.

The httpclient Sweep defer comment described ProtectLiveDependents/Limit
refusal paths this change replaced with capability gates; it now says why
the pass-through defer stays.

Validation: go test ./internal/httpapi/... ./internal/httpclient/... (CGO,
gms_pure_go), the served sweeper tier with BEADS_TEST_EMBEDDED_DOLT=1 (19/19
pass, none skipped), make api-check, go vet, git diff --check, and bazel test
--config=ci on httpapi_test, wireshape/..., httpclient_test, encode_test and
types_gen_drift_test. Mutants, each restored: disabling the sides arm reds
three TestGoldenDrift arms; the pre-fix golden reds TestWireShapeDigest
naming the 9 schemas; dropping the live_dependent or remaining projection,
the protect_live_dependents decode, or the limit assignment each reds its
new pin.

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 Sonnet 5 <noreply@anthropic.com>
2026-10-08 16:28:56 +00:00

393 lines
15 KiB
Go

package httpapi
import (
"net/http"
"reflect"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/issueops"
)
// The pins for POST /v0/beads/issues:sweep. What is asserted here is the WIRE
// EDGE — that the handler decodes the document's eight members into the role's
// request faithfully, refuses what the document refuses, and does not
// re-implement anything the role owns.
const sweepPath = "/v0/beads/issues:sweep"
func (ts *testServer) sweep(t *testing.T, body string) *http.Response {
t.Helper()
return ts.postBody(t, sweepPath, "application/json", body)
}
// TestSweepPathReachesItsHandler: the sweep path is a LITERAL segment
// registered beside the claim's wildcard `/v0/beads/issues/{idop}`, and ServeMux
// precedence is by specificity rather than by registration order. A 404 or a
// claim-shaped refusal here would mean the sweep is being parsed as a claim of
// an issue named ":sweep".
func TestSweepPathReachesItsHandler(t *testing.T) {
sweeper := &roleSweeper{result: issueops.SweepResult{Swept: 3}}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
resp := ts.sweep(t, `{"tier":"ephemeral"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
if len(sweeper.requests()) != 1 {
t.Fatalf("the sweep role was called %d times, want 1 — the path reached another handler",
len(sweeper.requests()))
}
}
// TestSweepForwardsEveryDocumentedMember is the operation's central pin: each
// of the eight body members reaches the role's request unchanged.
//
// It is asserted on the REQUEST the role received rather than on the response:
// a body carrying the right numbers says nothing about which set was swept, and
// a handler dropping a narrowing member widens what is erased.
func TestSweepForwardsEveryDocumentedMember(t *testing.T) {
sweeper := &roleSweeper{}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
resp := ts.sweep(t, `{
"tier": "durable",
"actor": " alice ",
"closed_before": "2026-03-01T12:00:00Z",
"pattern": "bd-old-*",
"protect_referenced": true,
"dry_run": true,
"protect_live_dependents": true,
"limit": 25
}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
reqs := sweeper.requests()
if len(reqs) != 1 {
t.Fatalf("%d sweeps, want 1", len(reqs))
}
got := reqs[0]
want := issueops.SweepRequest{
Tier: issueops.SweepDurable,
// TRIMMED, by the same rule and the same function the claim's actor
// goes through: it reaches the same commit-message interpolation.
Actor: "alice",
IDPattern: "bd-old-*",
ProtectReferenced: true,
DryRun: true,
ProtectLiveDependents: true,
Limit: 25,
}
cutoff := time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC)
want.ClosedBefore = &cutoff
if got.ClosedBefore == nil || !got.ClosedBefore.Equal(cutoff) {
t.Errorf("ClosedBefore = %v, want %v", got.ClosedBefore, cutoff)
}
got.ClosedBefore, want.ClosedBefore = nil, nil
if !reflect.DeepEqual(got, want) {
t.Errorf("request = %+v, want %+v", got, want)
}
}
// TestSweepDefaultsTheOptionalMembers: a body carrying only `tier` reaches the
// role as an unfiltered request of that tier, and NOT as a dry run.
//
// The dry-run default is the one worth pinning. `dry_run` absent must mean
// false — that is what the document says — and a handler that defaulted it the
// safe-looking way would make the endpoint silently incapable of deleting
// anything.
func TestSweepDefaultsTheOptionalMembers(t *testing.T) {
sweeper := &roleSweeper{}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
if resp := ts.sweep(t, `{"tier":"ephemeral"}`); resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
reqs := sweeper.requests()
if len(reqs) != 1 {
t.Fatalf("%d sweeps, want 1", len(reqs))
}
// protect_referenced ABSENT means TRUE on this surface, which is the one
// default here that deliberately differs from the role's zero value. The
// endpoint is destructive and its optional bearer is shared and
// surface-wide, so an omitted member must not buy weaker protection than
// `bd prune` gives by default.
want := issueops.SweepRequest{Tier: issueops.SweepEphemeral, ProtectReferenced: true}
if reqs[0] != want {
t.Errorf("request = %+v, want %+v", reqs[0], want)
}
}
// TestSweepHonorsAnExplicitProtectReferencedFalse is the other half of the
// default: opting OUT still works. Without this the defaults test alone could be
// satisfied by a handler that hard-coded protection on.
func TestSweepHonorsAnExplicitProtectReferencedFalse(t *testing.T) {
sweeper := &roleSweeper{}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
if resp := ts.sweep(t, `{"tier":"ephemeral","protect_referenced":false}`); resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
reqs := sweeper.requests()
if len(reqs) != 1 {
t.Fatalf("%d sweeps, want 1", len(reqs))
}
if reqs[0].ProtectReferenced {
t.Errorf("explicit protect_referenced:false did not reach the role: %+v", reqs[0])
}
}
// TestSweepPublishesTheWholeResult pins the projection. SweepResult is
// deliberately not x-go-type-pinned, so a field added to the role and forgotten
// here would vanish from the wire in silence.
func TestSweepPublishesTheWholeResult(t *testing.T) {
sweeper := &roleSweeper{result: issueops.SweepResult{
DryRun: true,
Swept: 7,
Dependencies: 3,
Labels: 2,
Events: 11,
Skipped: issueops.SweepSkips{
Pinned: 1, Referenced: 2, NotClosed: 3,
UnknownClosedAt: 4, ClosedAtOrAfterCutoff: 5, Unreadable: 6,
LiveDependent: 8,
},
Remaining: 13,
ReferencedIDs: []string{"bd-1", "bd-2"},
}}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
resp := ts.sweep(t, `{"tier":"durable","pattern":"*","dry_run":true}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
for _, want := range []struct {
key string
val any
}{
{"dry_run", true},
{"swept", float64(7)},
{"dependencies", float64(3)},
{"labels", float64(2)},
{"events", float64(11)},
{"remaining", float64(13)},
} {
if body[want.key] != want.val {
t.Errorf("%s = %v, want %v", want.key, body[want.key], want.val)
}
}
skipped, ok := body["skipped"].(map[string]any)
if !ok {
t.Fatalf("skipped = %v, want an object", body["skipped"])
}
for key, want := range map[string]float64{
"pinned": 1, "referenced": 2, "not_closed": 3,
"unknown_closed_at": 4, "closed_at_or_after_cutoff": 5, "unreadable": 6,
"live_dependent": 8,
} {
if skipped[key] != want {
t.Errorf("skipped.%s = %v, want %v", key, skipped[key], want)
}
}
ids, ok := body["referenced_ids"].([]any)
if !ok || len(ids) != 2 || ids[0] != "bd-1" {
t.Errorf("referenced_ids = %v, want the role's sample", body["referenced_ids"])
}
}
// TestSweepResponseCarriesEveryRoleField is the guard sweepResponse's comment
// names, the sweep twin of TestDeleteResponseCarriesEveryRoleField. It counts
// fields at both levels the projection copies — the result and its skip
// buckets — and then projects a result with every role field set, so a wire
// field the projection leaves zero or nil fails as well as a field added to
// one side and not the other.
func TestSweepResponseCarriesEveryRoleField(t *testing.T) {
full := issueops.SweepResult{
DryRun: true, Swept: 1, Dependencies: 2, Labels: 3, Events: 4,
Skipped: issueops.SweepSkips{
Pinned: 5, Referenced: 6, LiveDependent: 7, NotClosed: 8,
UnknownClosedAt: 9, ClosedAtOrAfterCutoff: 10, Unreadable: 11,
},
Remaining: 12,
ReferencedIDs: []string{"bd-1"},
}
body := sweepResponse(full)
for _, level := range []struct{ role, wire any }{
{full, body},
{full.Skipped, body.Skipped},
} {
role, wire := reflect.TypeOf(level.role), reflect.TypeOf(level.wire)
if role.NumField() != wire.NumField() {
t.Errorf("%v has %d fields and %v has %d: a field was added to one and not projected onto the "+
"other (see sweepResponse)", role, role.NumField(), wire, wire.NumField())
}
}
requireEveryFieldSet(t, reflect.ValueOf(body), "SweepResult")
}
// requireEveryFieldSet fails for each field of the struct v, followed through
// pointers and into nested structs, that still holds its zero value.
func requireEveryFieldSet(t *testing.T, v reflect.Value, path string) {
t.Helper()
for i := range v.NumField() {
field, name := v.Field(i), path+"."+v.Type().Field(i).Name
if field.Kind() == reflect.Pointer && !field.IsNil() {
field = field.Elem()
}
if field.Kind() == reflect.Struct {
requireEveryFieldSet(t, field, name)
continue
}
if field.IsZero() {
t.Errorf("%s is unset although every role field was set: sweepResponse does not project it", name)
}
}
}
// TestSweepOmitsAnEmptyReferencedSample: the member is documented ABSENT when
// nothing was protected, so a client can tell "nothing cited" from "the
// protection was not asked for" without a second field.
func TestSweepOmitsAnEmptyReferencedSample(t *testing.T) {
ts := newTestServer(t, rolesConfig(Config{Sweeper: &roleSweeper{}}))
resp := ts.sweep(t, `{"tier":"ephemeral"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
if _, present := decodeBody(t, resp)["referenced_ids"]; present {
t.Error("referenced_ids is present with nothing protected; the document says absent")
}
}
// TestSweepRefusesTheDocumentedBodies walks the 400 table. Every case names the
// member it is about in `param`, which is why the handler decodes member by
// member instead of unmarshaling the generated struct.
func TestSweepRefusesTheDocumentedBodies(t *testing.T) {
for _, test := range []struct {
name string
body string
param string
}{
{"no tier", `{"pattern":"*"}`, "tier"},
{"tier is not a string", `{"tier":3}`, "tier"},
{"tier is null", `{"tier":null}`, "tier"},
{"tier outside the enum", `{"tier":"wisps"}`, "tier"},
{"unknown member", `{"tier":"durable","scope":"all"}`, "scope"},
{"actor is not a string", `{"tier":"ephemeral","actor":7}`, "actor"},
{"actor is blank", `{"tier":"ephemeral","actor":" "}`, "actor"},
{"closed_before is not a timestamp", `{"tier":"ephemeral","closed_before":"yesterday"}`, "closed_before"},
{"pattern is not a string", `{"tier":"ephemeral","pattern":true}`, "pattern"},
{"dry_run is not a boolean", `{"tier":"ephemeral","dry_run":"yes"}`, "dry_run"},
{"protect_referenced is not a boolean", `{"tier":"ephemeral","protect_referenced":1}`, "protect_referenced"},
{"protect_live_dependents is not a boolean", `{"tier":"ephemeral","protect_live_dependents":"yes"}`, "protect_live_dependents"},
{"limit is not an integer", `{"tier":"ephemeral","limit":2.5}`, "limit"},
{"limit is null", `{"tier":"ephemeral","limit":null}`, "limit"},
} {
t.Run(test.name, func(t *testing.T) {
sweeper := &roleSweeper{}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
resp := ts.sweep(t, test.body)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeInvalidArgument) {
t.Errorf("code = %v, want %s", body["code"], CodeInvalidArgument)
}
if body["param"] != test.param {
t.Errorf("param = %v, want %q", body["param"], test.param)
}
// A refused body must never reach the role: the sweep is
// destructive, and "refused after acting" is the one failure shape
// worth ruling out at every edge.
if got := len(sweeper.requests()); got != 0 {
t.Errorf("the role was called %d times for a refused body, want 0", got)
}
})
}
}
// TestSweepPublishesTheRolesRefusalAsA400 is the reason failSweepErr exists.
// The require-a-filter gate, the tier vocabulary and the glob are all refused
// BELOW the wire, by issueops.Sweeper — that is what makes this endpoint
// incapable of an unguarded mass delete. A role refusal reaching the client as
// a 500 would hide the one sentence that says what to send instead.
func TestSweepPublishesTheRolesRefusalAsA400(t *testing.T) {
// The sentinel has to MATCH, not merely be mentioned in the text.
sweeper := &roleSweeper{err: wrapValidation("a durable sweep requires a closed-before cutoff or an id pattern")}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
// A body the HANDLER accepts and the ROLE refuses: the durable tier with no
// narrowing member is exactly that request, which is the point.
resp := ts.sweep(t, `{"tier":"durable"}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeInvalidArgument) {
t.Errorf("code = %v, want %s", body["code"], CodeInvalidArgument)
}
if detail, _ := body["detail"].(string); !strings.Contains(detail, "closed-before cutoff") {
t.Errorf("detail = %q, want the role's own sentence: it is what says what to send instead", detail)
}
// No `param`: the refusal is about two absent members at once, and the
// document declares `param` absent on exactly that case.
if _, present := body["param"]; present {
t.Errorf("param = %v, want it absent for a whole-request refusal", body["param"])
}
}
// TestSweepRefusesAForeignMediaType: a JSON content type is not CORS-"simple",
// so a cross-origin sweep always triggers a preflight this server never
// approves. Accepting text/plain would let an attacker's page drive a mass
// delete from any browser on the host.
func TestSweepRefusesAForeignMediaType(t *testing.T) {
sweeper := &roleSweeper{}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
resp := ts.postBody(t, sweepPath, "text/plain", `{"tier":"ephemeral"}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
if body := decodeBody(t, resp); body["param"] != "Content-Type" {
t.Errorf("param = %v, want Content-Type", body["param"])
}
if got := len(sweeper.requests()); got != 0 {
t.Errorf("the role was called %d times for a refused media type, want 0", got)
}
}
// TestSweepPublishesNoQueryParameters: this operation's whole vocabulary is its
// body, so a query key is version skew rather than a bad value.
func TestSweepPublishesNoQueryParameters(t *testing.T) {
ts := newTestServer(t, rolesConfig(Config{Sweeper: &roleSweeper{}}))
resp := ts.postBody(t, sweepPath+"?tier=durable", "application/json", `{"tier":"durable","pattern":"*"}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["param"] != "tier" || body["reason"] != string(ReasonUnknownParameter) {
t.Errorf("body = %v, want unknown_parameter on param tier", body)
}
}
// wrapValidation builds an error that MATCHES issueops.ErrValidation while
// reading like the role's own refusal, which is what failSweepErr keys on.
func wrapValidation(detail string) error {
return &validationError{detail: detail}
}
type validationError struct{ detail string }
func (e *validationError) Error() string { return issueops.ErrValidation.Error() + ": " + e.detail }
func (e *validationError) Unwrap() error { return issueops.ErrValidation }