* feat(http): serve list/show counts/dep tree/ping, close+reopen under a session, one-lookup not-found (S6b/S6c/S6d) S6c. The external-dependency decorator rebuilt its role views from the legacy DoltStorage seam (storereader over itself, IsBlocked, GetDependencyTree, ClaimReadyIssue), which a remote store only partly serves: `bd list`/`bd children` refused on the SearchIssuesWithCounts stub, `bd show --json` printed zero counts, the default `bd dep tree` refused, `bd ready --claim` and `bd close` of an externally blocked issue reached unsupported paths. For a storage.RemoteBackendStore each view now passes the inner role through and lays the policy over it in role terms (externaldeps/remote_roles.go): ready reads and the ready claim exclude the workspace-wide blocked set over a widened window; per-issue checks (claim, close, batch close, list annotations, tree leaves) read only the named issues' edges through EdgeReader instead of every edge in the workspace. A server advertising policy.external_dependencies (MC's does) gets a plain passthrough. `bd ping` uses a new storage.Pinger, which the http store answers with its authenticated context read. S6d. A store reporting storage.CallerAttributionLimitedStore (http) cannot carry a Provenance label or a patch's closed_by_session. The library still refuses both; the CLI omits them where nothing is lost: `bd reopen`'s fixed "bd: reopen <id>" label (the server labels the same entry), and the closed_by_session of `bd update -s closed` (attribution only, usually the ambient CLAUDE_SESSION_ID; an explicit --session prints a notice; `bd close` still records it). See cmd/bd/remote_backend.go. S6b. utils.ExactIDLookupStore: the resolver stops at exact lookups for a store with no substring search, so a missing prefixed id is a not-found (beadserrors.ErrNotFound, "no issue found matching") after one getIssue. The general resolver no longer repeats an identical normalized probe. The http SearchIssueIDs answers D11's partial-id refusal, which now unwraps to ErrNotFound. Contributor auto-routing for a remote workspace reads local config only, so the not-found fallback pays no settings round trip. `bd update <absent> --claim` (gc's hook claim) answers a gc-classifiable not-found in at most two requests. Served e2e (backend/http/e2e_remote_roles_test.go): every gc list shape and `bd children` against embedded, `show --json` count parity, default dep tree parity, external blocking still enforced, close/reopen under CLAUDE_SESSION_ID, missing-id request counts, absent-id claim against the current server and the MC handshake mask, policy passthrough under the MC mask, ping. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(externaldeps): role-level remote reader and claimer cases bd ready and bd update --claim reach the policy through the legacy seam and the lifecycle guard, so the remote Reader.Ready exclusion and the remote Claimer guard (what bd serve and library callers reach) are pinned at the role level with a fake remote store. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(http): bd serve advertises policy.external_dependencies; clients pass through bd serve composes every ready, claim, claim-next, close, blocking and tree role through the external-dependency policy, but never said so. Every client therefore ran the policy a second time, with the CLIENT machine's external-project config, and claim-next became a non-atomic read-then-claim loop on the client. The server now advertises the token exactly when the roles it serves were composed through the policy: httpapi.Config.ExternalDependencyPolicy, which bd serve derives from its actual chain (externaldeps.Applied for the store arm, externaldeps.AppliedToProvider for the provider arm). A server handed raw roles still withholds it, so the token stays truthful. Against a server that advertises it, every remote role view hands the request to the server's own role untouched: no client validation, no edge reads, claim-next is the server's one atomic call, and the ready count is the server's countReadyWork (new remoteReadyCounter). The client-side policy remains only for servers that do not advertise the token. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(create): default created_by to the request's actor in the create role created_by was stamped in two front doors and never in the library: the CLI (creationActorStamp, with a remote-workspace special case) and the three httpapi create handlers. A library caller of Lifecycle.Create or BatchCreator with an empty CreatedBy stored "" locally and the actor over http. PreparePublicCreateRequest, which every create shape prepares through (Lifecycle.Create, BatchCreator items, batch-apply create items), now defaults an empty CreatedBy to request.Actor; an explicit value is kept. The handlers no longer stamp, `bd create` and the state event create pass only the actor, and creationActorStamp/isRemoteBackendWorkspace are gone. The CLI sites that still create through the raw CreateIssue seam (swarm, todo, gate, the create form) keep stamping currentActor(): that seam is shared with import, where defaulting would re-attribute imported rows, and the http store refuses it anyway, so the remote special case was never reachable there. Conformance: the lifecycle-create, batch-creator and batch-apply contracts now pin created_by == actor for an item that names none, on every leg. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(httpclient): GetIssue answers a miss with storage.ErrNotFound, like the local stores The http store's raw GetIssue answered a missing id with (nil, nil), where DoltStore and the embedded store return a wrapped storage.ErrNotFound. A caller written against the backend contract read the http miss as a hit: `bd create --graph` refused every explicit-id plan over http (patched in cmd/bd on feat/http-mc-corpus; that workaround is reverted there). GetIssue now returns the miss (and the empty id) as storage.ErrNotFound, spelled as issueops.GetIssueInTx spells it. GetLabels, which reads through GetIssue, keeps the local read's "no labels" answer for a missing id; the `bd list --parent` walk reads the typed miss as "parent issue not found". The served bridge test now holds the local reference store and the http store to the same miss: ErrNotFound with the same text. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(createbatchequiv): re-record the apply golden for the created_by default c2866ea7fe made the create role default an empty CreatedBy to the request's actor, so every create item of the apply scenario's batch (actor "apply-writer") now stores created_by "apply-writer" instead of "". TestCreateBatchFastPathsMatchPerRow_*/apply compared the stored rows to a digest recorded before that change and failed on exactly the three tables the column reaches: issues and wisps (the row) and events (the update event's old-value snapshot). Fast and per-row bodies still agree; the batch-apply conformance contract pins the same value. Bisected with bazel: passes at be92efe40f's integ twin 696f7acc8e, fails from the created_by commit on. Only apply.json's three digests move. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: gofmt ledger.go and the externaldeps remote-roles test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cmd/bd): bd create reads routing settings local-only on a remote backend too determineAutoRoutedRepoPath skipped a remote backend's settings document (routing targets are local paths that one shared document cannot name for every client), but getRoutingConfigValue, which `bd create` and migrate-personal read routing.* and contributor.* through, still asked it. The same workspace could route a create one way and a lookup another, and every create paid a settings round trip per key. Both now go through routingSettingsStore: nil for a remote backend, so routing comes from config.yaml / the environment only there, and a local store is still consulted. A unit test holds both reads to the rule with a store that counts settings reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cmd/bd): say so when update -s closed drops an ambient CLAUDE_SESSION_ID Over http `bd update -s closed` cannot carry closed_by_session, so the CLI drops it rather than refusing the close. An explicit --session printed a notice; the ambient CLAUDE_SESSION_ID every agent under Claude Code exports was dropped without a word, a silent data difference from a local backend (the served corpus's mc-update-meta-status-closed). The drop is now named on stderr in both cases, once per command, pointing at `bd close`, whose wire operation records the session. The served e2e asserts the notice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(backend/http): hold bd list --limit 2 to each side's own unlimited order TestE2E_ListWithGCFiltersMatchesEmbedded compared the --limit 2 rows of the served and embedded workspaces as sets. The seed has four P2 rows, so the limit cuts a priority tie whose created_at order differs between two workspaces seeded seconds apart: a test-only flake, the order itself being total. Each side's two rows must now be, in order, the first two of that same side's --limit 0 listing; the unlimited listings are still compared across sides by the shape loop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: unit-tier pins for the created_by default, the policy token and the GetIssue miss Three review mutations were caught only by a heavier tier (the uow conformance legs, the served httpclient tier) or by one package's test alone. Each now has a unit test where its rule lives: - issueops: PreparePublicCreateRequest defaults an empty CreatedBy to the actor and keeps an explicit one, without mutating the caller's request. - externaldeps: the policy layer AppliedToProvider finds becomes the handshake's policy.external_dependencies through httpapi.Listen, the composition bd serve performs, and a raw provider's handshake lacks it. - httpclient (no embedded engine): GetIssue over the real wire client against a stub server answers a 404 not_found, and the empty id without dialing, as storage.ErrNotFound spelled like the local stores. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(changelog): S6b/c/d entries match the code The S6 entry still said `bd create` suppresses created_by on a remote workspace and that the external-dependency policy runs client-side. Since S6b/c/d, created_by defaults to the actor in the library on every backend, and every bd serve composed through the policy advertises policy.external_dependencies, so clients pass those operations through; the client-side policy (now in role terms) runs only against a server that does not advertise it. New entries: the advertised policy token, bd ping over http, the created_by library default, closed_by_session dropped by an http `bd update -s closed` (with a notice, typed or ambient), reopen without a Provenance label over http, local-only routing.* / contributor.* on a remote backend, GetIssue's miss as storage.ErrNotFound, and list/children/show counts/dep tree over http. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(externaldeps): keep S6's list --ready, --claim-next refusal and lost-race error on the S6c composition The re-adopted S6 head (#7288) carries the review fixup's remote role composition; S6c replaces it with its own (rolesAreRemote, the widened ready window, the policy passthrough). Two behaviours S6 shipped and its reviews pinned would otherwise go: - bd close --claim-next against a server that does not apply the policy is refused whole, before anything is read or closed, with "the served batch close cannot carry a next claim, so nothing was closed; close without --claim-next, then run `bd ready --claim`". S6c passed the batch to the http closer, whose W-CloseBatchRequest.ClaimNext refusal drops the remedy, so TestE2E_BDOverHTTP's two refuseClaimNext steps went red. A request invalid on every backend is still ErrValidation first, and a server that applies the policy still gets the request untouched. - remoteReadyClaimer.ClaimNext reports a page on which every candidate was lost to another actor as "claim ready: lost N races ...", not as the empty answer that means there is no work. - `bd list --ready` (List with ReadyFlag) is answered by the policy store's own reader over the served ready reads, as S6 does. S6c passed it to the served listing, which cannot carry ReadyFlag (httpclient ledger row E-ListRequest.ReadyFlag), so it exited 1 over http with or without external refs; TestE2E_BDOverHTTP and TestServedRolesKeepTheExternalDependencyPolicy were red on it. TestRemoteReaderAnswersAReadyListingWithoutTheWireFlag pins it, with the fake's served List refusing ReadyFlag as the wire does. S6's composition tests now run against S6c as remote_roles_composition_test.go. Their fake serves Ready the way a server does (the S6 composition read ready work through the legacy policy reader instead), and two call logs gain that Ready. TestRemoteBatchCloserRefusesANextClaim, TestRemoteBatchCloserValidatesANextClaimFirst and TestRemoteReadyClaimerReportsLostRaces were red on S6c before this change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(externaldeps): unassigned claim-next and fail-closed close reads Review fixes for the S6c composition against a server that does not advertise policy.external_dependencies: the two majors of review attempt 1, plus the minors on the same code. - ReadyClaimer: the composed claim-next reads only open, unassigned ready rows (Unassigned=true, Assignee cleared), the candidates the local ClaimReadyIssueInTx selects. A row another actor holds, or one already assigned to the caller, is no longer taken or counted as a lost race. Each pass reads 25 candidates past the blocked rows, as httpclient's composed claim does, and a full window lost end to end is read once more: claimed rows leave the unassigned set. Only a claim that tried candidates and won none is an error. - BatchCloser: an externally blocked item travels to the server only when its status read finds it closed or not found (liveRefusal). Any other read error is that item's outcome, so a transient or auth failure no longer forwards a refused close to a server that will not refuse it. - TreeWalker: a failed capability probe renders the external leaves over the walked tree instead of failing a walk the server already answered. appendTreeExternalReferences skips an id the tree holds, so an enforcing server's own leaves are not doubled. - remoteEdges names each anchor once and skips an empty one, which the http EdgeReader refuses with ErrValidation. The composition fakes now honor Unassigned/Assignee as workapi.BuildReadyFilter does, model a rival claim landing first and a failing GetIssue, and refuse an empty edge anchor as httpclient does. New: TestRemoteReadyClaimerTakesOnlyUnassignedWork, TestRemoteReadyClaimerWalksAContendedFront, TestRemoteBatchCloserAnswersAFailedReadWithIt, TestRemoteEdgesNamesEachAnchorOnce, and the probe-failure cases of TestRemoteTreeWalkerAddsExternalLeaves. Each is red with its fix reverted. From review attempt 2, three nearby cleanups: - TestServedRolesKeepTheExternalDependencyPolicy seeds open rows held by another actor and by the claimant ahead of the free work, then claims with and without an assignee filter. The unassigned-only claim is now pinned over a real served server, not only through the fakes: red with the pre-fixup remote_roles.go, with filter.Unassigned dropped, and (the filtered claim) with an explicit assignee honored. - The capabilities description in openapi.v0.yaml (and the regenerated types.gen.go comment) no longer calls the whole list build-level: policy.external_dependencies depends on how the server composed its roles, as the paragraph above it says. - createbatchequiv's golden note names issueops.PreparePublicCreateRequest instead of a commit id that is not on this branch. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(backend/http): count a not_found read as reaching the remote in #7469's credential doors main's #7469 added TestExplicitCredentialIgnoresTheEnvPlaintextGrant. Its OpenWith and Open doors read bd-1 from plaintextRemote, which answers every issue read not_found, and the granted leg needs that read to return a nil error. That held while the http client answered a miss with (nil, nil). This branch's "fix(httpclient): GetIssue answers a miss with storage.ErrNotFound, like the local stores" makes the same read return storage.ErrNotFound. So on main plus this branch both doors fail at per_open_credential_test.go:392 ("with Target.AllowInsecureCredential: not found: issue bd-1") under plain go test. The merge is textually clean, so only a build of the merge shows it. The two store doors now count storage.ErrNotFound as success, since that answer came off the wire. The assertions are unchanged. The refused leg still needs the "refusing to send a credential" error and no request on the transport. The granted leg still needs exactly one request carrying "Bearer explicit-token": a granted read that never reaches the wire still fails at :408. 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>
2197 lines
92 KiB
Go
2197 lines
92 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"encoding/json"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"regexp"
|
|
"slices"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
|
"github.com/steveyegge/beads/internal/httpapi/spec"
|
|
"github.com/steveyegge/beads/internal/workapi"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
// These tests are the spec drift gates. They are pure — no database, no
|
|
// server, no build tag — because they must run in the PR workflow's
|
|
// unconditional Go test job, not in a shard that only some pushes reach. With
|
|
// the wire structs pinned to canonical Go types via x-go-type, the compiler
|
|
// cannot see the spec at all, so if these move to a conditional CI tier the
|
|
// contract stops being checked.
|
|
|
|
var httpVerbs = map[string]bool{
|
|
"get": true, "put": true, "post": true, "delete": true, "patch": true,
|
|
"head": true, "options": true, "trace": true,
|
|
}
|
|
|
|
// streamingOps are the operations whose success body is a stream rather than a
|
|
// document, and therefore the only ones exempt from the application/json rule.
|
|
//
|
|
// It is a literal here and a `streaming` column in the route table, which is
|
|
// the drift this pairing catches: TestStreamingRowsAreTheDocumentsStreamingOps
|
|
// requires the two to name the same operations, so a row that starts streaming
|
|
// without saying so in the document — or a document that promises a stream no
|
|
// row holds open — fails.
|
|
var streamingOps = map[string]bool{
|
|
OpWatchEvents: true,
|
|
}
|
|
|
|
type specOp struct {
|
|
path string
|
|
method string
|
|
op map[string]any
|
|
}
|
|
|
|
func loadSpec(t *testing.T) map[string]any {
|
|
t.Helper()
|
|
var doc map[string]any
|
|
if err := yaml.Unmarshal(spec.OpenAPIV0(), &doc); err != nil {
|
|
t.Fatalf("parse embedded openapi document: %v", err)
|
|
}
|
|
return doc
|
|
}
|
|
|
|
func mapAt(t *testing.T, parent map[string]any, key string) map[string]any {
|
|
t.Helper()
|
|
v, ok := parent[key]
|
|
if !ok {
|
|
t.Fatalf("missing key %q", key)
|
|
}
|
|
m, ok := v.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("key %q is %T, want a mapping", key, v)
|
|
}
|
|
return m
|
|
}
|
|
|
|
// resolveRef follows a local $ref one level, which is all this document uses.
|
|
func resolveRef(t *testing.T, doc map[string]any, node map[string]any) map[string]any {
|
|
t.Helper()
|
|
ref, ok := node["$ref"].(string)
|
|
if !ok {
|
|
return node
|
|
}
|
|
rest, ok := strings.CutPrefix(ref, "#/")
|
|
if !ok {
|
|
t.Fatalf("only local $refs are supported, got %q", ref)
|
|
}
|
|
cur := doc
|
|
parts := strings.Split(rest, "/")
|
|
for i, part := range parts {
|
|
next, ok := cur[part]
|
|
if !ok {
|
|
t.Fatalf("$ref %q: no such node %q", ref, strings.Join(parts[:i+1], "/"))
|
|
}
|
|
m, ok := next.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("$ref %q: node %q is %T, want a mapping", ref, part, next)
|
|
}
|
|
cur = m
|
|
}
|
|
return cur
|
|
}
|
|
|
|
func specOps(t *testing.T, doc map[string]any) map[string]specOp {
|
|
t.Helper()
|
|
out := map[string]specOp{}
|
|
for path, item := range mapAt(t, doc, "paths") {
|
|
methods, ok := item.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("path %q is %T, want a mapping", path, item)
|
|
}
|
|
for method, raw := range methods {
|
|
if !httpVerbs[strings.ToLower(method)] {
|
|
continue
|
|
}
|
|
op, ok := raw.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("%s %s is %T, want a mapping", method, path, raw)
|
|
}
|
|
id, _ := op["operationId"].(string)
|
|
if id == "" {
|
|
t.Fatalf("%s %s has no operationId", strings.ToUpper(method), path)
|
|
}
|
|
if prev, dup := out[id]; dup {
|
|
t.Fatalf("operationId %q used twice: %s %s and %s %s",
|
|
id, prev.method, prev.path, strings.ToUpper(method), path)
|
|
}
|
|
out[id] = specOp{path: path, method: strings.ToUpper(method), op: op}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func sortedCodes(codes []Code) []string {
|
|
out := make([]string, 0, len(codes))
|
|
for _, c := range codes {
|
|
out = append(out, string(c))
|
|
}
|
|
sort.Strings(out)
|
|
return out
|
|
}
|
|
|
|
// TestSpecGovernance pins the document-level invariants that make the rest of
|
|
// the contract legible: one OpenAPI version, one error shape everywhere, a
|
|
// machine-readable code list on every documented failure, and no vendor
|
|
// vocabulary.
|
|
func TestSpecGovernance(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
|
|
if got, _ := doc["openapi"].(string); got != "3.0.3" {
|
|
t.Errorf("openapi = %q, want 3.0.3", got)
|
|
}
|
|
if got, _ := doc["x-bd-source"].(string); got != "spec-first" {
|
|
t.Errorf("x-bd-source = %q, want spec-first (the document is hand-written and generates the Go types)", got)
|
|
}
|
|
if got, _ := mapAt(t, doc, "info")["version"].(string); got == "" {
|
|
t.Error("info.version is empty")
|
|
}
|
|
|
|
// The OSS surface stays vendor-neutral: no product names, no hosted-only
|
|
// extensions.
|
|
if raw := string(spec.OpenAPIV0()); strings.Contains(raw, "x-gc-") {
|
|
t.Error("document carries x-gc-* extensions; the OSS spec must stay vendor-neutral")
|
|
}
|
|
|
|
for id, so := range specOps(t, doc) {
|
|
if _, ok := so.op["summary"].(string); !ok {
|
|
t.Errorf("%s: no summary", id)
|
|
}
|
|
if _, ok := so.op["description"].(string); !ok {
|
|
t.Errorf("%s: no description", id)
|
|
}
|
|
for status, raw := range mapAt(t, so.op, "responses") {
|
|
node, ok := raw.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("%s %s response is %T, want a mapping", id, status, raw)
|
|
}
|
|
resp := resolveRef(t, doc, node)
|
|
content := mapAt(t, resp, "content")
|
|
if len(content) != 1 {
|
|
t.Errorf("%s %s: %d media types, want exactly 1", id, status, len(content))
|
|
}
|
|
if strings.HasPrefix(status, "2") {
|
|
if streamingOps[id] {
|
|
// The one carve-out, and it is an allowlist rather than a
|
|
// relaxed rule: a response held open for the life of a
|
|
// connection cannot be a JSON document, but every OTHER
|
|
// operation must still fail here if it grows a second media
|
|
// type or drifts off application/json. A new streaming
|
|
// operation costs a line in this map and a paragraph in the
|
|
// document's Media types section, which is the point.
|
|
if _, ok := content["text/event-stream"]; !ok {
|
|
t.Errorf("%s %s: a streaming operation's success body is text/event-stream", id, status)
|
|
}
|
|
continue
|
|
}
|
|
if _, ok := content["application/json"]; !ok {
|
|
t.Errorf("%s %s: success bodies are application/json", id, status)
|
|
}
|
|
continue
|
|
}
|
|
body, ok := content["application/problem+json"]
|
|
if !ok {
|
|
t.Errorf("%s %s: every non-2xx body is application/problem+json", id, status)
|
|
continue
|
|
}
|
|
bodyMap, ok := body.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("%s %s: content is %T, want a mapping", id, status, body)
|
|
}
|
|
schema := mapAt(t, bodyMap, "schema")
|
|
if got, _ := schema["$ref"].(string); got != "#/components/schemas/Problem" {
|
|
t.Errorf("%s %s: schema %q, want the one Problem envelope", id, status, got)
|
|
}
|
|
if _, ok := resp["x-bd-codes"]; !ok {
|
|
t.Errorf("%s %s: no x-bd-codes; every documented failure names its machine codes", id, status)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestSpecRouteParity is the gate that the document and the server describe the
|
|
// same surface. Exact set equality, both directions: a documented operation
|
|
// with no route is a promise nothing keeps, and a route with no documentation
|
|
// is undisclosed surface. It also checks the operationId on each pair, so two
|
|
// operations cannot quietly swap paths while the set still matches.
|
|
//
|
|
// The route table IS the router — internal/httpapi/server.go builds the mux
|
|
// from it and from nothing else — so this compares what the server actually
|
|
// serves. The last step builds a real ServeMux from the table for the same
|
|
// reason: a pattern ServeMux refuses (a conflict, a malformed wildcard) is a
|
|
// panic on the first request, and it should be a test failure instead.
|
|
func TestSpecRouteParity(t *testing.T) {
|
|
type methodPath struct{ method, path string }
|
|
|
|
doc := loadSpec(t)
|
|
specSet := map[methodPath]string{}
|
|
for id, so := range specOps(t, doc) {
|
|
specSet[methodPath{so.method, so.path}] = id
|
|
}
|
|
|
|
routeSet := map[methodPath]string{}
|
|
for _, rt := range routeTable {
|
|
key := methodPath{rt.method, rt.specPathOf()}
|
|
if prev, dup := routeSet[key]; dup {
|
|
t.Fatalf("%s %s is routed twice: %q and %q", key.method, key.path, prev, rt.op)
|
|
}
|
|
routeSet[key] = rt.op
|
|
}
|
|
|
|
for key, id := range specSet {
|
|
op, ok := routeSet[key]
|
|
if !ok {
|
|
t.Errorf("spec documents %s %s (%s) with no route", key.method, key.path, id)
|
|
continue
|
|
}
|
|
if op != id {
|
|
t.Errorf("%s %s: route serves operation %q, the spec calls it %q", key.method, key.path, op, id)
|
|
}
|
|
}
|
|
for key, op := range routeSet {
|
|
if _, ok := specSet[key]; !ok {
|
|
t.Errorf("route %s %s (%s) is not in the spec; undocumented surface", key.method, key.path, op)
|
|
}
|
|
}
|
|
|
|
// A row that DECLARES a specPath is compared against the document by a
|
|
// string the router never sees, so for those rows the check above proves
|
|
// nothing about what the server serves: the pattern could grow a wrong
|
|
// prefix or a wrong segment and this test would stay green while the
|
|
// documented path 404s. Bound the exception instead of trusting it — the
|
|
// pattern must be the documented path with its final segment replaced by
|
|
// one wildcard, which is the only thing ServeMux cannot spell — and refuse
|
|
// a declaration that is not needed at all.
|
|
//
|
|
// TestClaimPathReachesItsHandler (server_test.go) is the behavioral half.
|
|
for _, rt := range routeTable {
|
|
if rt.specPath == "" {
|
|
continue
|
|
}
|
|
specDir, specLast := splitLastSegment(rt.specPath)
|
|
patDir, patLast := splitLastSegment(rt.pattern)
|
|
if specDir != patDir {
|
|
t.Errorf("%s: pattern %q and declared spec path %q do not share a prefix; the documented path is not the one routed",
|
|
rt.op, rt.pattern, rt.specPath)
|
|
}
|
|
if !isWildcardSegment(patLast) {
|
|
t.Errorf("%s: pattern %q declares a different spec path, so its final segment must be a single-segment wildcard (got %q)",
|
|
rt.op, rt.pattern, patLast)
|
|
}
|
|
if isWildcardSegment(specLast) {
|
|
t.Errorf("%s: spec path %q is expressible as a ServeMux pattern; delete the specPath declaration rather than detaching the row from the router",
|
|
rt.op, rt.specPath)
|
|
}
|
|
}
|
|
|
|
// Build the server's real handler: ServeMux panics on a conflicting or
|
|
// malformed pattern, and that belongs here rather than on the first
|
|
// request after a deploy.
|
|
if h := (&Server{}).handler(); h == nil {
|
|
t.Fatal("handler() returned nil")
|
|
}
|
|
}
|
|
|
|
// TestStreamingRowsAreTheDocumentsStreamingOps ties the route table's
|
|
// `streaming` column to the media-type carve-out above.
|
|
//
|
|
// The two describe one property of an operation from opposite ends: the column
|
|
// decides that the request gets no deadline and takes its database slot per
|
|
// read, and the document decides that clients are told to expect a stream. An
|
|
// operation that gained one without the other is either a JSON handler running
|
|
// without the backstop that bounds every other request, or a documented stream
|
|
// that the router will cut off at sixty seconds — and neither has any other
|
|
// test that can see it.
|
|
func TestStreamingRowsAreTheDocumentsStreamingOps(t *testing.T) {
|
|
routed := map[string]bool{}
|
|
for _, rt := range routeTable {
|
|
if rt.streaming {
|
|
routed[rt.op] = true
|
|
}
|
|
// A streaming row that still queued for the request-wide slot would hold
|
|
// one of sixteen for the life of a connection. The pairing is stated on
|
|
// the field and enforced here.
|
|
if rt.streaming && !rt.bypassSemaphore {
|
|
t.Errorf("%s streams but holds the request-wide database slot; a stream must take its slot per read", rt.op)
|
|
}
|
|
}
|
|
|
|
if missing := diff(routed, streamingOps); len(missing) > 0 {
|
|
t.Errorf("route table streams %v, the document does not describe them as streaming operations", missing)
|
|
}
|
|
if extra := diff(streamingOps, routed); len(extra) > 0 {
|
|
t.Errorf("the document treats %v as streaming, but no route row is marked streaming", extra)
|
|
}
|
|
}
|
|
|
|
func splitLastSegment(path string) (dir, last string) {
|
|
i := strings.LastIndex(path, "/")
|
|
return path[:i+1], path[i+1:]
|
|
}
|
|
|
|
// isWildcardSegment reports whether seg is a ServeMux single-segment wildcard.
|
|
// The multi-segment form ({x...}) is not one: it swallows the rest of the path,
|
|
// which is wider surface than any documented operation.
|
|
func isWildcardSegment(seg string) bool {
|
|
return strings.HasPrefix(seg, "{") && strings.HasSuffix(seg, "}") && !strings.Contains(seg, "...")
|
|
}
|
|
|
|
// TestSpecDefaultsMatchSharedConstants keeps the document honest about the two
|
|
// limit defaults and about limit=0. The whole point of sharing constants
|
|
// between the CLI flag and the HTTP parameter is that the two surfaces cannot
|
|
// diverge; a spec that states a different number would reintroduce the
|
|
// divergence in the one place clients actually read.
|
|
func TestSpecDefaultsMatchSharedConstants(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
ops := specOps(t, doc)
|
|
|
|
for _, tc := range []struct {
|
|
opID string
|
|
want int
|
|
}{
|
|
{OpListIssues, workapi.DefaultListLimit},
|
|
{OpListReadyWork, workapi.DefaultReadyLimit},
|
|
} {
|
|
so, ok := ops[tc.opID]
|
|
if !ok {
|
|
t.Fatalf("operation %q missing from the spec", tc.opID)
|
|
}
|
|
limit := specParam(t, so, "limit")
|
|
schema := mapAt(t, limit, "schema")
|
|
|
|
got, ok := schema["default"].(int)
|
|
if !ok {
|
|
t.Fatalf("%s: limit has no integer default (%T)", tc.opID, schema["default"])
|
|
}
|
|
if got != tc.want {
|
|
t.Errorf("%s: spec documents limit default %d, shared constant is %d", tc.opID, got, tc.want)
|
|
}
|
|
if lo, ok := schema["minimum"].(int); !ok || lo != 0 {
|
|
t.Errorf("%s: limit minimum = %v, want 0 (limit=0 is a legal, meaningful value)", tc.opID, schema["minimum"])
|
|
}
|
|
|
|
// limit=0 means unlimited on both surfaces. If this phrasing ever
|
|
// changes, change it deliberately — clients depend on the behavior
|
|
// and this is the only place the wire documents it.
|
|
desc, _ := limit["description"].(string)
|
|
if !strings.Contains(desc, "`0` means unlimited") {
|
|
t.Errorf("%s: limit description does not document that `0` means unlimited", tc.opID)
|
|
}
|
|
if !strings.Contains(desc, "--allow-non-loopback") {
|
|
t.Errorf("%s: limit description does not document the non-loopback refusal of limit=0", tc.opID)
|
|
}
|
|
}
|
|
|
|
// The anchor bound on ALL THREE dependency-collection reads. Each bounds
|
|
// the same thing — how many issues one call may ask about — from the same
|
|
// maxDependencyAnchors, and each says so in prose. Nothing kept the
|
|
// document's number and the constant together until this: the bound is
|
|
// enforced in the handler, so a spec that drifted to a different maxItems
|
|
// would be refused by the server it documents, at a number no reader could
|
|
// have predicted.
|
|
//
|
|
// THE THIRD ROW IS THE POINT. listBlockingAnnotations enforces the same
|
|
// constant (blocking.go) and declares the same maxItems, and it predates
|
|
// this gate — so a two-operation loop would have pinned the copies that
|
|
// happened to be in the slice that wrote it and left the oldest one free
|
|
// to drift. Every operation reading maxDependencyAnchors belongs here, and
|
|
// the next one to do so must be added.
|
|
for _, opID := range []string{OpListDependencies, OpCountDependencyEdges, OpListBlockingAnnotations} {
|
|
so, ok := ops[opID]
|
|
if !ok {
|
|
t.Fatalf("operation %q missing from the spec", opID)
|
|
}
|
|
schema := mapAt(t, specParam(t, so, "issue_id"), "schema")
|
|
if got, ok := schema["maxItems"].(int); !ok || got != maxDependencyAnchors {
|
|
t.Errorf("%s: issue_id maxItems = %v, want the shared bound %d", opID, schema["maxItems"], maxDependencyAnchors)
|
|
}
|
|
// At least one is required on both, and the schema is where a
|
|
// generated client learns it.
|
|
if got, ok := schema["minItems"].(int); !ok || got != 1 {
|
|
t.Errorf("%s: issue_id minItems = %v, want 1", opID, schema["minItems"])
|
|
}
|
|
}
|
|
|
|
// The id bound on the three request bodies that carry an `ids` list, for
|
|
// the anchor bound's reason: each is enforced in code — maxDeleteIDs in the
|
|
// delete handler, issueops.MaxGetManyIDs in the role behind batchGet and
|
|
// issueops.MaxReclaimIDs in the role behind reclaim — and restated as the
|
|
// member's maxItems, which is where a generated client learns it. Each body is reached through its operation's own $ref, so a
|
|
// row cannot go on checking a schema its operation stopped using.
|
|
for _, tc := range []struct {
|
|
opID string
|
|
want int
|
|
}{
|
|
{OpBatchGetIssues, issueops.MaxGetManyIDs},
|
|
{OpDeleteIssues, maxDeleteIDs},
|
|
{OpReclaimIssues, issueops.MaxReclaimIDs},
|
|
} {
|
|
so, ok := ops[tc.opID]
|
|
if !ok {
|
|
t.Fatalf("operation %q missing from the spec", tc.opID)
|
|
}
|
|
media := mapAt(t, mapAt(t, mapAt(t, so.op, "requestBody"), "content"), "application/json")
|
|
body := resolveRef(t, doc, mapAt(t, media, "schema"))
|
|
ids := resolveRef(t, doc, mapAt(t, mapAt(t, body, "properties"), "ids"))
|
|
if got, ok := ids["maxItems"].(int); !ok || got != tc.want {
|
|
t.Errorf("%s: ids maxItems = %v, want the enforced bound %d", tc.opID, ids["maxItems"], tc.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// capabilityToken matches one backticked capability token in the
|
|
// `capabilities` description. The shape is a lowercase resource, a dot, a
|
|
// lowerCamel verb, and OPTIONALLY a second dot and a third lowerCamel segment
|
|
// (`issues.list.sort`, matching the bd-enterprise client's
|
|
// httpstore/wire/handshake.go:121 and DESIGN.txt §4e) — narrow enough that no
|
|
// other backticked word in that paragraph can be mistaken for one, but wide
|
|
// enough for a sub-capability one level below an operation's own token.
|
|
var capabilityToken = regexp.MustCompile("`([a-z]+\\.[a-zA-Z]+(?:\\.[a-zA-Z]+)?)`")
|
|
|
|
// TestSpecCapabilityVocabularyMatchesTheRouteTable is the gate for the ONE
|
|
// piece of per-operation plumbing that had no gate.
|
|
//
|
|
// The `capabilities` description enumerates every token explicitly, in prose,
|
|
// and prose is not generated from anything: an operation could land with its
|
|
// route row, its handler, its problem codes and its spec path all correct and
|
|
// still never appear in the list a client is told to check. Nothing would fail.
|
|
// The document would simply be wrong about the one member it tells clients to
|
|
// dispatch on, and the drift would be discovered by a client, not by CI.
|
|
//
|
|
// Set equality both ways: a token in the prose with no implemented route is a
|
|
// capability advertised to readers and not to clients, and a route whose token
|
|
// the prose omits is an operation the document forgets it has.
|
|
//
|
|
// ORDER IS NOT CHECKED. The prose groups tokens by resource for a reader;
|
|
// Capabilities() sorts them for a client. Both are deliberate, and pinning one
|
|
// to the other would be a rule about paragraph layout.
|
|
func TestSpecCapabilityVocabularyMatchesTheRouteTable(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "ContextResponse")
|
|
caps := mapAt(t, mapAt(t, schema, "properties"), "capabilities")
|
|
desc, _ := caps["description"].(string)
|
|
if desc == "" {
|
|
t.Fatal("the capabilities property has no description; it is where the token vocabulary is published")
|
|
}
|
|
|
|
documented := map[string]bool{}
|
|
for _, m := range capabilityToken.FindAllStringSubmatch(desc, -1) {
|
|
documented[m[1]] = true
|
|
}
|
|
served := map[string]bool{}
|
|
for _, token := range Capabilities() {
|
|
served[token] = true
|
|
}
|
|
// The conditional tokens are documented in the same paragraph. Their
|
|
// snake_case segment is outside capabilityToken's shape, so each is looked
|
|
// for verbatim.
|
|
for _, token := range conditionalCapabilities {
|
|
served[token] = true
|
|
if strings.Contains(desc, "`"+token+"`") {
|
|
documented[token] = true
|
|
}
|
|
}
|
|
|
|
if missing := diff(served, documented); len(missing) > 0 {
|
|
t.Errorf("this build serves capabilities the document does not enumerate: %v\n"+
|
|
"add them to the `capabilities` description in internal/httpapi/spec/openapi.v0.yaml — "+
|
|
"that paragraph is the vocabulary a client is told to check", missing)
|
|
}
|
|
if extra := diff(documented, served); len(extra) > 0 {
|
|
t.Errorf("the document enumerates capabilities no implemented route contributes: %v", extra)
|
|
}
|
|
}
|
|
|
|
// hasValidCapabilityToken reports whether desc carries at least one
|
|
// backticked token that is BOTH shaped like a capability (capabilityToken)
|
|
// AND a member of validTokens. A backticked string that merely looks like a
|
|
// token — `metadata.json`, say — proves nothing: anyone can put backticks
|
|
// around two words. Checking membership against the real advertised set is
|
|
// what makes the token verifiable rather than decorative (review HIGH,
|
|
// "a token must be one advertised by Capabilities(), not any backticked a.b
|
|
// text").
|
|
func hasValidCapabilityToken(desc string, validTokens map[string]bool) bool {
|
|
for _, m := range capabilityToken.FindAllStringSubmatch(desc, -1) {
|
|
if validTokens[m[1]] {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// untokenedParameters reports "operationId.paramName" (query/path/header
|
|
// parameters) and "operationId body.memberName" (request body members, one
|
|
// level deep) for every undocumented dispatch surface in ops: one whose own
|
|
// description carries no token that is a member of validTokens, and whose
|
|
// (operationId, name) pair is not in baseline.
|
|
//
|
|
// Two further gates narrow this to a true ratchet rather than a sweep that
|
|
// would also fire on surface this rule did not exist to judge:
|
|
//
|
|
// - existingOps restricts the rule to operations that existed when the rule
|
|
// was frozen (testdata/pretoken_operations.json). A parameter or body
|
|
// member on a BRAND-NEW operation is never "missing" a token under this
|
|
// rule — a new operation's own review is where its capability story gets
|
|
// decided, not a baseline file written before it existed.
|
|
// - validTokens restricts what counts as a token at all: shape is not
|
|
// enough (hasValidCapabilityToken).
|
|
//
|
|
// doc resolves the $refs a parameter or request body may point at. baseline
|
|
// is keyed by operationId to the list of its parameter names exempt from the
|
|
// rule; bodyBaseline is the same shape for "body.member" names.
|
|
//
|
|
// Factored out of TestNewParameterOnExistingOperationHasABehaviorToken so
|
|
// TestUntokenedParameterRuleFires can falsify it against a fixture with no
|
|
// dependency on the real document: the rule fires on its own fabricated
|
|
// miss, not just on whatever this spec currently happens to contain.
|
|
func untokenedParameters(
|
|
t *testing.T,
|
|
doc map[string]any,
|
|
ops map[string]specOp,
|
|
baseline map[string][]string,
|
|
bodyBaseline map[string][]string,
|
|
existingOps map[string]bool,
|
|
validTokens map[string]bool,
|
|
) []string {
|
|
t.Helper()
|
|
grandfathered := map[string]bool{}
|
|
for opID, params := range baseline {
|
|
for _, p := range params {
|
|
grandfathered[opID+"\x00"+p] = true
|
|
}
|
|
}
|
|
bodyGrandfathered := map[string]bool{}
|
|
for opID, members := range bodyBaseline {
|
|
for _, m := range members {
|
|
bodyGrandfathered[opID+"\x00"+m] = true
|
|
}
|
|
}
|
|
|
|
var missing []string
|
|
for opID, so := range ops {
|
|
if existingOps != nil && !existingOps[opID] {
|
|
continue // brand-new operation: its own review decides its tokens.
|
|
}
|
|
|
|
if raw, ok := so.op["parameters"].([]any); ok {
|
|
for _, r := range raw {
|
|
pm, ok := r.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("%s: parameter is %T, want a mapping", opID, r)
|
|
}
|
|
pm = resolveRef(t, doc, pm)
|
|
name, _ := pm["name"].(string)
|
|
if name == "" {
|
|
t.Fatalf("%s: parameter with no name", opID)
|
|
}
|
|
if grandfathered[opID+"\x00"+name] {
|
|
continue
|
|
}
|
|
desc, _ := pm["description"].(string)
|
|
if !hasValidCapabilityToken(desc, validTokens) {
|
|
missing = append(missing, opID+"."+name)
|
|
}
|
|
}
|
|
}
|
|
|
|
for member, desc := range requestBodyMemberDescriptions(t, doc, so) {
|
|
if bodyGrandfathered[opID+"\x00"+member] {
|
|
continue
|
|
}
|
|
if !hasValidCapabilityToken(desc, validTokens) {
|
|
missing = append(missing, opID+" body."+member)
|
|
}
|
|
}
|
|
}
|
|
sort.Strings(missing)
|
|
return missing
|
|
}
|
|
|
|
// requestBodyMemberDescriptions returns, for so's request body (if any), each
|
|
// top-level member name mapped to its own description. Every request body in
|
|
// this document is `required: true` with a single application/json media
|
|
// type whose schema is a direct $ref to a named object schema with no allOf —
|
|
// simple enough that one level of property-walking covers all of them; a
|
|
// future body shaped any other way will simply report no members here rather
|
|
// than silently miscounting, which TestRequestBodyMembersCoversEveryBody (if
|
|
// that ever becomes necessary) would be the place to pin.
|
|
func requestBodyMemberDescriptions(t *testing.T, doc map[string]any, so specOp) map[string]string {
|
|
t.Helper()
|
|
rb, ok := so.op["requestBody"].(map[string]any)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
content, ok := rb["content"].(map[string]any)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
media, ok := content["application/json"].(map[string]any)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
schemaRef, ok := media["schema"].(map[string]any)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
schema := resolveRef(t, doc, schemaRef)
|
|
props, ok := schema["properties"].(map[string]any)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
out := map[string]string{}
|
|
for member, raw := range props {
|
|
pm, ok := raw.(map[string]any)
|
|
if !ok {
|
|
continue
|
|
}
|
|
pm = resolveRef(t, doc, pm)
|
|
desc, _ := pm["description"].(string)
|
|
out[member] = desc
|
|
}
|
|
return out
|
|
}
|
|
|
|
func loadPretokenBaseline(t *testing.T) map[string][]string {
|
|
t.Helper()
|
|
return loadJSONStringMap(t, "pretoken_parameters.json")
|
|
}
|
|
|
|
// loadPretokenBodyBaseline is loadPretokenBaseline's sibling for request body
|
|
// members (review MEDIUM, "extend the rule to request-body members on
|
|
// existing operations"): same write-once-grandfather shape, keyed by
|
|
// operationId to the "body.member" names that already existed, untokened,
|
|
// the day body-member coverage was added.
|
|
func loadPretokenBodyBaseline(t *testing.T) map[string][]string {
|
|
t.Helper()
|
|
return loadJSONStringMap(t, "pretoken_request_body_members.json")
|
|
}
|
|
|
|
func loadJSONStringMap(t *testing.T, filename string) map[string][]string {
|
|
t.Helper()
|
|
blob, err := os.ReadFile(filepath.Join("testdata", filename))
|
|
if err != nil {
|
|
t.Fatalf("read %s: %v", filename, err)
|
|
}
|
|
var out map[string][]string
|
|
if err := json.Unmarshal(blob, &out); err != nil {
|
|
t.Fatalf("decode testdata/%s: %v", filename, err)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// loadPretokenOperations is the review's "don't fire on brand-new
|
|
// operations" gate: the set of operationIds that existed the day the
|
|
// untokened-parameter rule (and its body-member extension) was frozen. An
|
|
// operation not in this file is new, and gets no say from either baseline —
|
|
// its own code review decides its capability story.
|
|
func loadPretokenOperations(t *testing.T) map[string]bool {
|
|
t.Helper()
|
|
blob, err := os.ReadFile(filepath.Join("testdata", "pretoken_operations.json"))
|
|
if err != nil {
|
|
t.Fatalf("read pretoken operations: %v", err)
|
|
}
|
|
var list []string
|
|
if err := json.Unmarshal(blob, &list); err != nil {
|
|
t.Fatalf("decode testdata/pretoken_operations.json: %v", err)
|
|
}
|
|
out := make(map[string]bool, len(list))
|
|
for _, id := range list {
|
|
out[id] = true
|
|
}
|
|
return out
|
|
}
|
|
|
|
// servedCapabilities is validTokens for the real document: exactly what
|
|
// Capabilities() advertises right now, which is also what
|
|
// TestSpecCapabilityVocabularyMatchesTheRouteTable pins the spec prose to.
|
|
func servedCapabilities() map[string]bool {
|
|
out := map[string]bool{}
|
|
for _, token := range Capabilities() {
|
|
out[token] = true
|
|
}
|
|
return out
|
|
}
|
|
|
|
// TestNewParameterOnExistingOperationHasABehaviorToken is the lint rule S0
|
|
// item 4 asks for: a parameter on an existing operation with no capability
|
|
// token in its own description is undocumented dispatch surface — a client
|
|
// has no way to learn THIS server accepts it without sending it and risking
|
|
// `unknown_parameter`, which is exactly what happened to `sort` (#5666)
|
|
// before `issues.list.sort` closed the gap.
|
|
//
|
|
// The baseline (testdata/pretoken_parameters.json) is a WRITE-ONCE grandfather
|
|
// list: every parameter this document already had the day the rule was
|
|
// written, captured by walking the spec with this same token regex. A
|
|
// parameter on it is exempt permanently, and nothing here ever regenerates
|
|
// the file. Any parameter not on it — present today or added by any later
|
|
// change — must carry a token, which is what makes this a ratchet rather than
|
|
// a one-time sweep: `issues.list.sort` is already the parity fix the rule's
|
|
// own baseline is built from, not an exemption to it.
|
|
func TestNewParameterOnExistingOperationHasABehaviorToken(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
ops := specOps(t, doc)
|
|
baseline := loadPretokenBaseline(t)
|
|
bodyBaseline := loadPretokenBodyBaseline(t)
|
|
existingOps := loadPretokenOperations(t)
|
|
valid := servedCapabilities()
|
|
|
|
if missing := untokenedParameters(t, doc, ops, baseline, bodyBaseline, existingOps, valid); len(missing) > 0 {
|
|
t.Errorf("parameter(s) or request body member(s) on an existing operation carry no capability token "+
|
|
"that Capabilities() actually serves, and are not on the frozen baseline "+
|
|
"(internal/httpapi/testdata/pretoken_parameters.json / pretoken_request_body_members.json): %v\n"+
|
|
"add a `resource.verb` token to the member's own description, the way `sort` on "+
|
|
"GET /v0/beads/issues advertises `issues.list.sort`", missing)
|
|
}
|
|
}
|
|
|
|
// TestPretokenBaselinesNeverGrow pins the three frozen testdata files at
|
|
// their current size (review MEDIUM, "the baseline must never grow"):
|
|
// nothing here ever regenerates them, so the only way their counts change is
|
|
// someone hand-editing a new exemption in, which is exactly what this guards
|
|
// against. A legitimate new parameter or body member must carry its own
|
|
// token, not an entry on these files; a legitimate new OPERATION is added to
|
|
// pretoken_operations.json never — new operations are simply never members of
|
|
// it, by construction, since nothing regenerates it either.
|
|
func TestPretokenBaselinesNeverGrow(t *testing.T) {
|
|
const (
|
|
wantParamEntries = 137
|
|
wantBodyEntries = 85
|
|
wantOps = 41
|
|
)
|
|
baseline := loadPretokenBaseline(t)
|
|
paramEntries := 0
|
|
for _, params := range baseline {
|
|
paramEntries += len(params)
|
|
}
|
|
if paramEntries != wantParamEntries {
|
|
t.Errorf("testdata/pretoken_parameters.json has %d grandfathered parameters, want exactly %d "+
|
|
"(frozen the day the rule was written); if this moved, something added a new exemption instead "+
|
|
"of a token", paramEntries, wantParamEntries)
|
|
}
|
|
|
|
bodyBaseline := loadPretokenBodyBaseline(t)
|
|
bodyEntries := 0
|
|
for _, members := range bodyBaseline {
|
|
bodyEntries += len(members)
|
|
}
|
|
if bodyEntries != wantBodyEntries {
|
|
t.Errorf("testdata/pretoken_request_body_members.json has %d grandfathered body members, want exactly %d",
|
|
bodyEntries, wantBodyEntries)
|
|
}
|
|
|
|
existingOps := loadPretokenOperations(t)
|
|
if len(existingOps) != wantOps {
|
|
t.Errorf("testdata/pretoken_operations.json has %d operations, want exactly %d "+
|
|
"(frozen the day the new-operation exemption was added)", len(existingOps), wantOps)
|
|
}
|
|
}
|
|
|
|
// TestUntokenedParameterRuleFires is the rule's own falsification, required
|
|
// because TestNewParameterOnExistingOperationHasABehaviorToken is permanently
|
|
// green against a spec written to satisfy it: a synthetic operation proves
|
|
// the CHECK itself still distinguishes the cases it exists to tell apart,
|
|
// independent of anything the real document currently says.
|
|
func TestUntokenedParameterRuleFires(t *testing.T) {
|
|
doc := map[string]any{} // no $refs in the fixtures below; resolveRef never consults it
|
|
newOp := func(desc string) specOp {
|
|
return specOp{
|
|
method: "GET",
|
|
path: "/synthetic",
|
|
op: map[string]any{
|
|
"parameters": []any{
|
|
map[string]any{"name": "widget", "description": desc},
|
|
},
|
|
},
|
|
}
|
|
}
|
|
noBody := map[string][]string{}
|
|
allExisting := map[string]bool{"syntheticOp": true}
|
|
validTokens := map[string]bool{"synthetic.widget": true, "issues.list": true}
|
|
|
|
ops := map[string]specOp{"syntheticOp": newOp("plain prose, no token at all")}
|
|
if got := untokenedParameters(t, doc, ops, noBody, noBody, allExisting, validTokens); !slices.Equal(got, []string{"syntheticOp.widget"}) {
|
|
t.Fatalf("untokened, non-grandfathered parameter: got %v, want [syntheticOp.widget]", got)
|
|
}
|
|
|
|
if got := untokenedParameters(t, doc, ops, map[string][]string{"syntheticOp": {"widget"}}, noBody, allExisting, validTokens); len(got) != 0 {
|
|
t.Fatalf("grandfathered parameter still reported: got %v, want none", got)
|
|
}
|
|
|
|
ops["syntheticOp"] = newOp("carries the `synthetic.widget` token")
|
|
if got := untokenedParameters(t, doc, ops, noBody, noBody, allExisting, validTokens); len(got) != 0 {
|
|
t.Fatalf("tokened parameter still reported: got %v, want none", got)
|
|
}
|
|
|
|
// A backticked string shaped like a token but not one Capabilities()
|
|
// actually serves must still fire: shape alone is not proof (review HIGH).
|
|
ops["syntheticOp"] = newOp("see `metadata.json` for details")
|
|
if got := untokenedParameters(t, doc, ops, noBody, noBody, allExisting, validTokens); !slices.Equal(got, []string{"syntheticOp.widget"}) {
|
|
t.Fatalf("bogus (unserved) token: got %v, want [syntheticOp.widget]", got)
|
|
}
|
|
|
|
// A REAL token, just not one this parameter actually advertises, passes:
|
|
// Capabilities() has no per-parameter binding to check against, so
|
|
// membership in the served set is the full extent of this rule (review
|
|
// HIGH says "a token must be one advertised by Capabilities()", not that
|
|
// it must be the specific token for this parameter).
|
|
ops["syntheticOp"] = newOp("reuses an unrelated real token (`issues.list`)")
|
|
if got := untokenedParameters(t, doc, ops, noBody, noBody, allExisting, validTokens); len(got) != 0 {
|
|
t.Fatalf("real-but-unrelated token: got %v, want none", got)
|
|
}
|
|
|
|
// A brand-new operation (absent from the existingOps baseline) is exempt
|
|
// even with no token at all (review MEDIUM, "don't fire on brand-new
|
|
// operations"). syntheticOp still carries its real-but-unrelated token
|
|
// from the previous case, so it reports nothing either.
|
|
ops["brandNewOp"] = newOp("plain prose, no token at all")
|
|
if got := untokenedParameters(t, doc, ops, noBody, noBody, allExisting, validTokens); len(got) != 0 {
|
|
t.Fatalf("brand-new operation must not be reported: got %v", got)
|
|
}
|
|
// And a nil existingOps (the behavior with no freeze gate at all) does
|
|
// catch it, so the gate is additive, not a silent replacement for the
|
|
// baseline check.
|
|
if got := untokenedParameters(t, doc, ops, noBody, noBody, nil, validTokens); !slices.Equal(got, []string{"brandNewOp.widget"}) {
|
|
t.Fatalf("nil existingOps must not exempt anything: got %v", got)
|
|
}
|
|
}
|
|
|
|
// TestUntokenedRequestBodyMemberRuleFires is TestUntokenedParameterRuleFires'
|
|
// sibling for request body members (review MEDIUM, "extend the rule to
|
|
// request-body members on existing operations").
|
|
func TestUntokenedRequestBodyMemberRuleFires(t *testing.T) {
|
|
doc := map[string]any{
|
|
"components": map[string]any{
|
|
"schemas": map[string]any{
|
|
"SyntheticRequest": map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"widget": map[string]any{"type": "string", "description": "plain prose, no token at all"},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
so := specOp{
|
|
method: "POST",
|
|
path: "/synthetic",
|
|
op: map[string]any{
|
|
"requestBody": map[string]any{
|
|
"content": map[string]any{
|
|
"application/json": map[string]any{
|
|
"schema": map[string]any{"$ref": "#/components/schemas/SyntheticRequest"},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
ops := map[string]specOp{"syntheticOp": so}
|
|
noParams := map[string][]string{}
|
|
allExisting := map[string]bool{"syntheticOp": true}
|
|
validTokens := map[string]bool{"synthetic.widget": true}
|
|
|
|
if got := untokenedParameters(t, doc, ops, noParams, noParams, allExisting, validTokens); !slices.Equal(got, []string{"syntheticOp body.widget"}) {
|
|
t.Fatalf("untokened, non-grandfathered body member: got %v, want [syntheticOp body.widget]", got)
|
|
}
|
|
|
|
if got := untokenedParameters(t, doc, ops, noParams, map[string][]string{"syntheticOp": {"widget"}}, allExisting, validTokens); len(got) != 0 {
|
|
t.Fatalf("grandfathered body member still reported: got %v, want none", got)
|
|
}
|
|
|
|
props := doc["components"].(map[string]any)["schemas"].(map[string]any)["SyntheticRequest"].(map[string]any)["properties"].(map[string]any)
|
|
props["widget"] = map[string]any{"type": "string", "description": "carries the `synthetic.widget` token"}
|
|
if got := untokenedParameters(t, doc, ops, noParams, noParams, allExisting, validTokens); len(got) != 0 {
|
|
t.Fatalf("tokened body member still reported: got %v, want none", got)
|
|
}
|
|
}
|
|
|
|
func specParam(t *testing.T, so specOp, name string) map[string]any {
|
|
t.Helper()
|
|
raw, ok := so.op["parameters"].([]any)
|
|
if !ok {
|
|
t.Fatalf("%s %s has no parameters", so.method, so.path)
|
|
}
|
|
for _, p := range raw {
|
|
param, ok := p.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("%s %s: parameter is %T, want a mapping", so.method, so.path, p)
|
|
}
|
|
if got, _ := param["name"].(string); got == name {
|
|
return param
|
|
}
|
|
}
|
|
t.Fatalf("%s %s: no %q parameter", so.method, so.path, name)
|
|
return nil
|
|
}
|
|
|
|
// TestSpecStatusCodesMatchHandlerTable is the rule that keeps the error
|
|
// vocabulary from growing by accident: every documented status+code pair is
|
|
// permanent wire surface, so the spec may document exactly what the mapping in
|
|
// problem.go can produce, and no more.
|
|
//
|
|
// The Host-header middleware's 400 invalid_argument is reachable on every
|
|
// route and is documented once at the document level rather than per
|
|
// operation, so it is absent from both sides here by construction.
|
|
func TestSpecStatusCodesMatchHandlerTable(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
ops := specOps(t, doc)
|
|
|
|
// There are no 501 stubs left. The check stays because it is the guard
|
|
// against one reappearing silently: 501 is not documented anywhere in this
|
|
// document and `not_implemented` is deliberately absent from the frozen
|
|
// vocabulary in problem.go, so a stub emits a status this test would
|
|
// otherwise forbid. The transitional exemption list that used to sit here
|
|
// was deleted with the last stub, which is what it was written to require.
|
|
for _, rt := range routeTable {
|
|
if !rt.implemented {
|
|
t.Errorf("%s is a 501 stub; v0 has no undocumented statuses left, so a new stub needs an exemption block here that says why", rt.op)
|
|
}
|
|
}
|
|
|
|
if len(ops) != len(operationCodes) {
|
|
t.Errorf("spec documents %d operations, the handler table declares %d", len(ops), len(operationCodes))
|
|
}
|
|
for id := range ops {
|
|
if _, ok := operationCodes[id]; !ok {
|
|
t.Errorf("spec operation %q has no entry in the handler table", id)
|
|
}
|
|
}
|
|
|
|
for id, codes := range operationCodes {
|
|
so, ok := ops[id]
|
|
if !ok {
|
|
t.Errorf("handler table operation %q is not in the spec", id)
|
|
continue
|
|
}
|
|
|
|
wantByStatus := map[int][]Code{}
|
|
for _, c := range codes {
|
|
status := c.Status()
|
|
if status == 0 {
|
|
t.Errorf("%s: code %q has no frozen status", id, c)
|
|
continue
|
|
}
|
|
wantByStatus[status] = append(wantByStatus[status], c)
|
|
}
|
|
|
|
gotStatuses := map[int]bool{}
|
|
for status, raw := range mapAt(t, so.op, "responses") {
|
|
code, err := strconv.Atoi(status)
|
|
if err != nil {
|
|
t.Fatalf("%s: response key %q is not a status code", id, status)
|
|
}
|
|
if code >= 200 && code < 300 {
|
|
continue
|
|
}
|
|
gotStatuses[code] = true
|
|
|
|
node, ok := raw.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("%s %d: response is %T, want a mapping", id, code, raw)
|
|
}
|
|
resp := resolveRef(t, doc, node)
|
|
var documented []string
|
|
for _, c := range toStrings(t, resp["x-bd-codes"]) {
|
|
documented = append(documented, c)
|
|
if Code(c).Status() == 0 {
|
|
t.Errorf("%s %d: code %q is not in the frozen vocabulary", id, code, c)
|
|
continue
|
|
}
|
|
if got := Code(c).Status(); got != code {
|
|
t.Errorf("%s: code %q is documented under %d but is frozen to %d", id, c, code, got)
|
|
}
|
|
}
|
|
sort.Strings(documented)
|
|
if want := sortedCodes(wantByStatus[code]); !equalStrings(documented, want) {
|
|
t.Errorf("%s %d: spec documents codes %v, the handler table can emit %v", id, code, documented, want)
|
|
}
|
|
}
|
|
|
|
for status := range wantByStatus {
|
|
if !gotStatuses[status] {
|
|
t.Errorf("%s: handler table can emit %d, the spec does not document it", id, status)
|
|
}
|
|
}
|
|
for status := range gotStatuses {
|
|
if _, ok := wantByStatus[status]; !ok {
|
|
t.Errorf("%s: spec documents %d, no mapping row can produce it for this operation", id, status)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestDefaultsMatchCLIFlags guards every default this document repeats from a
|
|
// cobra flag registration. A client swapping a `bd` subprocess for an HTTP call
|
|
// gets the same answer only if the two surfaces default the same way, and a
|
|
// default is the one piece of the contract nobody passes explicitly — so a
|
|
// divergence is invisible until the result sets differ.
|
|
//
|
|
// The two limits are now one constant each, in internal/workapi, which both
|
|
// surfaces read: TestSpecDefaultsMatchSharedConstants pins the document to
|
|
// workapi's numbers, and this pins the cobra flag to the same constants BY
|
|
// NAME. Asserting the name rather than the value is the stronger half of the
|
|
// chain — a flag that went back to a literal would still pass a value
|
|
// comparison on the day it was written and drift the day someone edited one
|
|
// side. `sort` has no constant to share at all; the flag string IS the source
|
|
// of truth, so that half is still a value comparison.
|
|
//
|
|
// If a flag registration is reworded this fails loudly — re-point the regex,
|
|
// and check the values still agree while you are there.
|
|
func TestDefaultsMatchCLIFlags(t *testing.T) {
|
|
limitFlag := regexp.MustCompile(`IntP\("limit",\s*"n",\s*([^,]+),`)
|
|
|
|
for _, tc := range []struct {
|
|
file string
|
|
want string
|
|
}{
|
|
{"../../cmd/bd/list.go", "workapi.DefaultListLimit"},
|
|
{"../../cmd/bd/ready.go", "workapi.DefaultReadyLimit"},
|
|
} {
|
|
src, err := os.ReadFile(tc.file)
|
|
if err != nil {
|
|
t.Fatalf("read %s: %v", tc.file, err)
|
|
}
|
|
m := limitFlag.FindSubmatch(src)
|
|
if m == nil {
|
|
t.Fatalf("%s: no --limit flag registration found; re-point this guard at the CLI's default", tc.file)
|
|
}
|
|
if got := strings.TrimSpace(string(m[1])); got != tc.want {
|
|
t.Errorf("%s registers --limit default %s, want the shared constant %s that this document is pinned to", tc.file, got, tc.want)
|
|
}
|
|
}
|
|
|
|
// The ready sort policy. Getting this wrong changes the item SET, not just
|
|
// the order, as soon as the limit truncates: `hybrid` demotes older
|
|
// high-priority work that `priority` surfaces first.
|
|
//
|
|
// Note for anyone tempted to "correct" the spec back to hybrid: the
|
|
// storage layer maps an EMPTY policy to hybrid
|
|
// (internal/storage/sqlbuild/ready.go), but the CLI never sends empty —
|
|
// the flag registers a concrete default — so that fallback is not `bd
|
|
// ready`'s behavior and must not be this parameter's default. A handler
|
|
// that forwards an absent `sort` as "" reintroduces the divergence with
|
|
// the spec still saying the right thing.
|
|
sortFlag := regexp.MustCompile(`StringP\("sort",\s*"s",\s*"([a-z]+)"`)
|
|
src, err := os.ReadFile("../../cmd/bd/ready.go")
|
|
if err != nil {
|
|
t.Fatalf("read cmd/bd/ready.go: %v", err)
|
|
}
|
|
m := sortFlag.FindSubmatch(src)
|
|
if m == nil {
|
|
t.Fatalf("cmd/bd/ready.go: no --sort flag registration found; re-point this guard at the CLI's default")
|
|
}
|
|
cliSort := string(m[1])
|
|
|
|
doc := loadSpec(t)
|
|
so, ok := specOps(t, doc)[OpListReadyWork]
|
|
if !ok {
|
|
t.Fatalf("operation %q missing from the spec", OpListReadyWork)
|
|
}
|
|
schema := mapAt(t, specParam(t, so, "sort"), "schema")
|
|
specSort, _ := schema["default"].(string)
|
|
if specSort != cliSort {
|
|
t.Errorf("spec documents sort default %q, `bd ready --sort` registers %q", specSort, cliSort)
|
|
}
|
|
if !slices.Contains(toStrings(t, schema["enum"]), specSort) {
|
|
t.Errorf("sort default %q is not in the documented enum %v", specSort, schema["enum"])
|
|
}
|
|
// The third link in the chain. The two above tie the document to the CLI
|
|
// flag; without this one the HANDLER is free to send a different policy
|
|
// while both of them still read correctly, which is the only place a
|
|
// wrong default actually changes what a client receives.
|
|
if readySortDefault != cliSort {
|
|
t.Errorf("handleReady defaults `sort` to %q, `bd ready --sort` registers %q", readySortDefault, cliSort)
|
|
}
|
|
}
|
|
|
|
// contextResponseAllowlist is the ENTIRE field set of GET /v0/beads/context,
|
|
// frozen. The handshake is assembled from the server's own configuration, which
|
|
// is exactly the kind of struct that grows a field nobody meant to publish, so
|
|
// this list is the gate: adding a member to the response is an edit here, in
|
|
// the spec, and in review — never a side effect of something upstream growing.
|
|
//
|
|
// Deliberately absent, in this and every future version: the workspace's sync
|
|
// remote (remote URLs routinely embed credentials) and the database bind
|
|
// host/port (advertising it invites clients to bypass this API and dial the
|
|
// database directly). Both are named here rather than only in prose so that
|
|
// re-adding one costs a test edit.
|
|
var contextResponseAllowlist = []string{
|
|
"api_version", "backend", "bd_version", "beads_dir", "capabilities",
|
|
"database", "dolt_mode", "min_client_wire_revision", "project_id",
|
|
"repo_root", "schema_version", "wire_revision",
|
|
}
|
|
|
|
// TestContextResponseAllowlist pins that field set from both sides: the
|
|
// generated Go struct (what the server can marshal) and the document (what
|
|
// clients are promised). ContextResponse is not x-go-type-pinned — it is new
|
|
// wire surface with no canonical struct behind it — so the bijection test does
|
|
// not cover it, and without this the document's own claim that the field set is
|
|
// enforced would be aspirational.
|
|
func TestContextResponseAllowlist(t *testing.T) {
|
|
want := map[string]bool{}
|
|
for _, name := range contextResponseAllowlist {
|
|
want[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, reflect.TypeOf(apigen.ContextResponse{}))
|
|
if extra := diff(goFields, want); len(extra) > 0 {
|
|
t.Errorf("generated ContextResponse carries fields that are not on the allowlist: %v\n"+
|
|
"a member of this response is a permanent, deliberate disclosure — add it here only with the review that implies", extra)
|
|
}
|
|
if missing := diff(want, goFields); len(missing) > 0 {
|
|
t.Errorf("allowlisted fields absent from the generated ContextResponse: %v", missing)
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "ContextResponse")
|
|
specProps := schemaProperties(t, doc, schema)
|
|
if extra := diff(specProps, want); len(extra) > 0 {
|
|
t.Errorf("the ContextResponse schema documents fields that are not on the allowlist: %v", extra)
|
|
}
|
|
if missing := diff(want, specProps); len(missing) > 0 {
|
|
t.Errorf("allowlisted fields absent from the ContextResponse schema: %v", missing)
|
|
}
|
|
}
|
|
|
|
// contextResponseOptional is the set of ContextResponse members a client must
|
|
// be able to read as ABSENT. Everything else on the allowlist is required.
|
|
//
|
|
// Both entries describe the SERVER's filesystem rather than the workspace's
|
|
// logical identity, and a remote client cannot act on an absolute host path —
|
|
// it cannot open it, and `project_id`, `database` and `backend` are what tell
|
|
// two servers apart. The schema's own text calls publishing them a cost the
|
|
// operator accepts; while they were required, accepting it was the only
|
|
// conforming option.
|
|
var contextResponseOptional = []string{"beads_dir", "repo_root"}
|
|
|
|
// TestContextResponseRequiredSet pins the split from both sides: the document's
|
|
// `required` list and the generated struct's pointer-ness, which is what tells
|
|
// a Go client that absence is representable.
|
|
//
|
|
// Without it the relaxation is one edit from being undone, in either direction:
|
|
// re-listing a member under `required` re-imposes the disclosure on every
|
|
// deployment, and dropping one that belongs there turns a guaranteed member
|
|
// into an optional one for every client that had stopped checking.
|
|
func TestContextResponseRequiredSet(t *testing.T) {
|
|
optional := map[string]bool{}
|
|
for _, name := range contextResponseOptional {
|
|
optional[name] = true
|
|
}
|
|
wantRequired := map[string]bool{}
|
|
for _, name := range contextResponseAllowlist {
|
|
if !optional[name] {
|
|
wantRequired[name] = true
|
|
}
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "ContextResponse")
|
|
gotRequired := map[string]bool{}
|
|
for _, name := range toStrings(t, schema["required"]) {
|
|
gotRequired[name] = true
|
|
}
|
|
if extra := diff(gotRequired, wantRequired); len(extra) > 0 {
|
|
t.Errorf("ContextResponse requires members this test expects to be optional: %v\n"+
|
|
"requiring one means no deployment may withhold it", extra)
|
|
}
|
|
if missing := diff(wantRequired, gotRequired); len(missing) > 0 {
|
|
t.Errorf("ContextResponse no longer requires: %v\n"+
|
|
"a client that had stopped checking for these now has to", missing)
|
|
}
|
|
|
|
rt := reflect.TypeOf(apigen.ContextResponse{})
|
|
for i := range rt.NumField() {
|
|
f := rt.Field(i)
|
|
name := strings.Split(f.Tag.Get("json"), ",")[0]
|
|
isPointer := f.Type.Kind() == reflect.Pointer
|
|
if optional[name] && !isPointer {
|
|
t.Errorf("generated ContextResponse.%s is %s; an optional member must be a pointer or the server cannot omit it",
|
|
f.Name, f.Type)
|
|
}
|
|
if !optional[name] && isPointer {
|
|
t.Errorf("generated ContextResponse.%s is %s; a required member must not be nil-able", f.Name, f.Type)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestClaimRequestMembersMatchTheHandler is the same gate for the REQUEST side
|
|
// of the claim, where the same unpinned-surface hazard runs the other way.
|
|
//
|
|
// The handler deliberately does not decode apigen.ClaimRequest: it reads raw
|
|
// members so it can name the offending one in a refusal, which is what makes
|
|
// the schema's additionalProperties: false enforceable by a client that has
|
|
// stopped parsing prose. The price is that its accepted set is a hand-rolled
|
|
// copy of the generated struct with nothing tying the two together — so a spec
|
|
// revision adding an optional member would leave `make api-check` and every
|
|
// other spec test green while the server refused the newly documented member as
|
|
// unknown_parameter. Silent drift with all the gates passing is the one failure
|
|
// this file exists to prevent.
|
|
func TestClaimRequestMembersMatchTheHandler(t *testing.T) {
|
|
accepted := map[string]bool{claimActorMember: true}
|
|
|
|
goFields := jsonTagNames(t, reflect.TypeOf(apigen.ClaimRequest{}))
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated ClaimRequest declares members the claim handler refuses as unknown: %v\n"+
|
|
"teach claimActor to honor them, or the document promises a member the server turns down", extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the claim handler accepts members ClaimRequest does not declare: %v", missing)
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "ClaimRequest")
|
|
specProps := schemaProperties(t, doc, schema)
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the ClaimRequest schema documents members the claim handler refuses: %v", extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the claim handler accepts members the ClaimRequest schema does not document: %v", missing)
|
|
}
|
|
}
|
|
|
|
// TestCloseRequestMembersMatchTheHandler is TestClaimRequestMembersMatchTheHandler
|
|
// for the close body, and it exists for the same reason: the handler decodes
|
|
// raw members so it can name the offending one, which makes the schema's
|
|
// additionalProperties: false enforceable by a client that has stopped parsing
|
|
// prose — at the cost of a hand-rolled copy of the member list with nothing
|
|
// tying it to the document. A spec revision adding an optional member would
|
|
// otherwise leave `make api-check` and every other spec test green while the
|
|
// server refused the newly documented member as unknown_parameter.
|
|
func TestCloseRequestMembersMatchTheHandler(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range closeRequestMembers {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, reflect.TypeOf(apigen.CloseIssueRequest{}))
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated CloseIssueRequest declares members the close handler refuses as unknown: %v\n"+
|
|
"teach closeRequest to honor them, or the document promises a member the server turns down", extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the close handler accepts members CloseIssueRequest does not declare: %v", missing)
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "CloseIssueRequest")
|
|
specProps := schemaProperties(t, doc, schema)
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the CloseIssueRequest schema documents members the close handler refuses: %v", extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the close handler accepts members the CloseIssueRequest schema does not document: %v", missing)
|
|
}
|
|
}
|
|
|
|
// TestBatchCloseRequestMembersMatchTheHandler is the batch create's gate for
|
|
// the batch close body, at BOTH of its levels. Same reason as there: the
|
|
// handler decodes raw members so it can name the offending one by index, which
|
|
// costs a hand-rolled copy of two member lists with nothing tying them to the
|
|
// document.
|
|
func TestBatchCloseRequestMembersMatchTheHandler(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
schemas := mapAt(t, mapAt(t, doc, "components"), "schemas")
|
|
|
|
for _, tc := range []struct {
|
|
schema string
|
|
accepted []string
|
|
goType any
|
|
}{
|
|
{schema: "BatchCloseRequest", accepted: batchCloseRequestMembers, goType: apigen.BatchCloseRequest{}},
|
|
{schema: "BatchCloseItem", accepted: batchCloseItemMembers, goType: apigen.BatchCloseItem{}},
|
|
} {
|
|
t.Run(tc.schema, func(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range tc.accepted {
|
|
accepted[name] = true
|
|
}
|
|
goFields := jsonTagNames(t, reflect.TypeOf(tc.goType))
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated %s declares members the batchClose handler refuses as unknown: %v", tc.schema, extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the batchClose handler accepts members %s does not declare: %v", tc.schema, missing)
|
|
}
|
|
specProps := schemaProperties(t, doc, mapAt(t, schemas, tc.schema))
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the %s schema documents members the batchClose handler refuses: %v", tc.schema, extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the batchClose handler accepts members the %s schema does not document: %v", tc.schema, missing)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestCloseOutcomeCodesAreExactlyWhatTheProjectionEmits holds the per-item
|
|
// vocabulary to the document, which no other gate covers: `code` on an outcome
|
|
// lives inside a 200 BODY, so TestSpecStatusCodesMatchHandlerTable — which
|
|
// compares problem documents — cannot see it at all.
|
|
//
|
|
// An item code the projection emits and the document does not name is
|
|
// undisclosed wire surface on the one operation whose refusals do not travel as
|
|
// problems.
|
|
func TestCloseOutcomeCodesAreExactlyWhatTheProjectionEmits(t *testing.T) {
|
|
// The codes closeOutcome can produce, read off the function's own arms.
|
|
emitted := map[string]bool{
|
|
string(CodeNotFound): true,
|
|
string(CodeNotClosable): true,
|
|
string(CodeInternal): true,
|
|
}
|
|
for code := range emitted {
|
|
if Code(code).Status() == 0 {
|
|
t.Errorf("outcome code %q is not in the frozen vocabulary", code)
|
|
}
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "CloseOutcome")
|
|
described := mapAt(t, mapAt(t, schema, "properties"), "code")["description"]
|
|
prose, _ := described.(string)
|
|
if prose == "" {
|
|
t.Fatal("CloseOutcome.code carries no description; the item vocabulary is documented nowhere else")
|
|
}
|
|
for code := range emitted {
|
|
// `internal` is the fail-closed arm for a refusal no vocabulary here
|
|
// names, and the document does not enumerate it for the same reason no
|
|
// operation enumerates the generic 500: it means the server is broken,
|
|
// not that the client sent something.
|
|
if code == string(CodeInternal) {
|
|
continue
|
|
}
|
|
if !strings.Contains(prose, "`"+code+"`") {
|
|
t.Errorf("closeOutcome emits %q and CloseOutcome.code does not name it", code)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestClaimNextRequestMembersMatchTheHandler is the claim's gate for the
|
|
// claimNext body. The body is one member, and the point of the test is the
|
|
// NEGATIVE half: this operation's filter lives in the query string, so a
|
|
// documented body member the handler refuses — or, worse, a filter member added
|
|
// to the schema that would have to be a second spelling of the ready
|
|
// vocabulary — fails here rather than shipping.
|
|
func TestClaimNextRequestMembersMatchTheHandler(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range claimNextRequestMembers {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, reflect.TypeOf(apigen.ClaimNextRequest{}))
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated ClaimNextRequest declares members the claimNext handler refuses as unknown: %v", extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the claimNext handler accepts members ClaimNextRequest does not declare: %v", missing)
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "ClaimNextRequest")
|
|
specProps := schemaProperties(t, doc, schema)
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the ClaimNextRequest schema documents members the claimNext handler refuses: %v", extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the claimNext handler accepts members the ClaimNextRequest schema does not document: %v", missing)
|
|
}
|
|
}
|
|
|
|
// TestClaimNextAdmitsExactlyTheListingsFilters is the guarantee readyFilters
|
|
// exists for, asserted at the DOCUMENT level rather than trusted to the shared
|
|
// function.
|
|
//
|
|
// The handler cannot drift — it calls readyFilters itself — but the SPEC can,
|
|
// and a document that published a filter the handler never decodes would tell a
|
|
// client its request was narrowed when it was not. The two operations must
|
|
// admit one set: a claim answering a different question than the listing shows
|
|
// would hand an agent work the listing never offered it.
|
|
//
|
|
// The deliberate differences are the listing's own PAGE knobs, which are not
|
|
// filters: they bound or shape what one request returns rather than selecting
|
|
// which rows are eligible, so a claim has no use for them.
|
|
// issueops.ValidateClaimNextRequest refuses each one by VALUE, and because
|
|
// readyFilters does not decode them, the HTTP door refuses them earlier still
|
|
// as an unknown parameter. Each is asserted as an absence from claimNext rather
|
|
// than merely left off the comparison, because a documented parameter that is
|
|
// always a 400 is a trap either way.
|
|
//
|
|
// `sort` is deliberately NOT on that list. It picks WHICH row comes first, so
|
|
// it changes which one a claim takes, and both operations must admit it.
|
|
func TestClaimNextAdmitsExactlyTheListingsFilters(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
names := func(path, method string) map[string]bool {
|
|
op := mapAt(t, mapAt(t, mapAt(t, doc, "paths"), path), method)
|
|
params, _ := op["parameters"].([]any)
|
|
out := map[string]bool{}
|
|
for _, raw := range params {
|
|
p, _ := raw.(map[string]any)
|
|
name, _ := p["name"].(string)
|
|
out[name] = true
|
|
}
|
|
return out
|
|
}
|
|
listing := names("/v0/beads/ready", "get")
|
|
claimNext := names("/v0/beads/issues:claimNext", "post")
|
|
|
|
pageKnobs := map[string]string{
|
|
"limit": "bounds the page; a claim takes one row however large the pool it scanned",
|
|
"brief": "projects the rows a page returns; a claim refetches its winning row whole, so there is nothing to project",
|
|
}
|
|
for name, why := range pageKnobs {
|
|
if !listing[name] {
|
|
t.Fatalf("the listing no longer publishes `%s`; this test's exception for it is stale (%s)", name, why)
|
|
}
|
|
delete(listing, name)
|
|
if claimNext[name] {
|
|
t.Errorf("claimNext publishes `%s`; it refuses one by value (%s), and a documented parameter that is always a 400 is a trap", name, why)
|
|
}
|
|
}
|
|
|
|
if extra := diff(claimNext, listing); len(extra) > 0 {
|
|
t.Errorf("claimNext publishes parameters the ready listing does not: %v\n"+
|
|
"the two must admit one filter vocabulary, or a claim answers a different question than the listing shows", extra)
|
|
}
|
|
if missing := diff(listing, claimNext); len(missing) > 0 {
|
|
t.Errorf("the ready listing publishes parameters claimNext does not: %v\n"+
|
|
"the handler decodes them through readyFilters either way, so the document is understating what it accepts.\n"+
|
|
"If one of these is a page knob rather than a filter, add it to pageKnobs above with its reason", missing)
|
|
}
|
|
}
|
|
|
|
// TestReleaseRequestMembersMatchTheHandler is the close's gate for the release
|
|
// body, and it exists for the same reason. It matters a little more here than
|
|
// there because two of the three members are GUARDS: a documented guard the
|
|
// server refuses as unknown, or an undocumented one it honors, both change who
|
|
// is allowed to release whose claim.
|
|
func TestReleaseRequestMembersMatchTheHandler(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range releaseRequestMembers {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, reflect.TypeOf(apigen.ReleaseIssueRequest{}))
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated ReleaseIssueRequest declares members the release handler refuses as unknown: %v\n"+
|
|
"teach releaseRequest to honor them, or the document promises a member the server turns down", extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the release handler accepts members ReleaseIssueRequest does not declare: %v", missing)
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "ReleaseIssueRequest")
|
|
specProps := schemaProperties(t, doc, schema)
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the ReleaseIssueRequest schema documents members the release handler refuses: %v", extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the release handler accepts members the ReleaseIssueRequest schema does not document: %v", missing)
|
|
}
|
|
}
|
|
|
|
// TestSetSettingRequestMembersMatchTheHandler is the release's gate for the
|
|
// settings write body.
|
|
//
|
|
// The member this is really guarding is the one that is NOT there. The key is
|
|
// the path's, and a `key` member arriving in the body — documented or honored —
|
|
// would give one request two anchors, so both halves of the check matter: the
|
|
// handler refuses it as unknown, and the schema must not promise it.
|
|
func TestSetSettingRequestMembersMatchTheHandler(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range setSettingRequestMembers {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, reflect.TypeOf(apigen.SetSettingRequest{}))
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated SetSettingRequest declares members the settings write refuses as unknown: %v", extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the settings write accepts members SetSettingRequest does not declare: %v", missing)
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "SetSettingRequest")
|
|
specProps := schemaProperties(t, doc, schema)
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the SetSettingRequest schema documents members the settings write refuses: %v", extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the settings write accepts members the SetSettingRequest schema does not document: %v", missing)
|
|
}
|
|
|
|
if accepted["key"] || specProps["key"] {
|
|
t.Error("SetSettingRequest publishes `key`; the anchor is the path parameter and must have one spelling")
|
|
}
|
|
}
|
|
|
|
// TestRemovedSettingPublishesNothingButTheKey pins the removal's response shape
|
|
// against the document from the SERVER's side, which the schema alone cannot do:
|
|
// `RemovedSetting` is unpinned, so nothing else fails when a member is added to
|
|
// the Go type and to the schema together.
|
|
//
|
|
// Both absences are the contract. `removed` cannot be honest — the storage seam
|
|
// discards the affected-row count on every implementation — and `value` would
|
|
// publish, on the one settings operation that withholds nothing, exactly the
|
|
// credential `GET /v0/beads/config/{key}` redacts.
|
|
func TestRemovedSettingPublishesNothingButTheKey(t *testing.T) {
|
|
if got := jsonTagNames(t, reflect.TypeOf(apigen.RemovedSetting{})); len(got) != 1 || !got["key"] {
|
|
t.Errorf("RemovedSetting declares %v, want `key` alone", got)
|
|
}
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "RemovedSetting")
|
|
if got := schemaProperties(t, doc, schema); len(got) != 1 || !got["key"] {
|
|
t.Errorf("the RemovedSetting schema documents %v, want `key` alone", got)
|
|
}
|
|
}
|
|
|
|
// TestAddCommentRequestMembersMatchTheHandler is the release's gate for the
|
|
// comment body.
|
|
//
|
|
// The member it is really guarding is `author`. Every other body on this surface
|
|
// spells its provenance `actor`, so `author` is the one member here a reflex
|
|
// edit would "fix" — and the two are not interchangeable: `actor` attributes a
|
|
// mutation and `author` IS part of the row, echoed back by every read of the
|
|
// thread. Renamed on either side alone, this fails.
|
|
func TestAddCommentRequestMembersMatchTheHandler(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range addCommentRequestMembers {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, reflect.TypeOf(apigen.AddCommentRequest{}))
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated AddCommentRequest declares members the add-comment handler refuses as unknown: %v", extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the add-comment handler accepts members AddCommentRequest does not declare: %v", missing)
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "AddCommentRequest")
|
|
specProps := schemaProperties(t, doc, schema)
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the AddCommentRequest schema documents members the add-comment handler refuses: %v", extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the add-comment handler accepts members the AddCommentRequest schema does not document: %v", missing)
|
|
}
|
|
|
|
// The issue is the PATH's, and the schema must not publish a second spelling
|
|
// of it: a body carrying `issue_id` beside a path `{id}` is one request with
|
|
// two anchors and a question about what to do when they disagree.
|
|
if accepted["issue_id"] || specProps["issue_id"] {
|
|
t.Error("AddCommentRequest publishes `issue_id`; the anchor is the path parameter and must have one spelling")
|
|
}
|
|
}
|
|
|
|
// TestUpdateRequestMembersMatchTheHandler is the claim's and the close's gate
|
|
// for the update body, at BOTH of its levels.
|
|
//
|
|
// It matters more here than anywhere else on the surface: `patch` is the widest
|
|
// member list published, and the handler's accepted set is a hand-rolled copy
|
|
// of it because presence has to be observable. A spec revision adding an
|
|
// optional patch member would otherwise leave `make api-check` and every other
|
|
// spec test green while the server refused the newly documented member as
|
|
// unknown_parameter — and the reverse, a member the handler honors that the
|
|
// document never promised, is undisclosed write surface on a mutation.
|
|
func TestUpdateRequestMembersMatchTheHandler(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
schemas := mapAt(t, mapAt(t, doc, "components"), "schemas")
|
|
|
|
for _, tc := range []struct {
|
|
schema string
|
|
accepted []string
|
|
goType reflect.Type
|
|
}{
|
|
{"UpdateIssueRequest", updateRequestMembers, reflect.TypeOf(apigen.UpdateIssueRequest{})},
|
|
{"IssuePatchBody", issuePatchMembers, reflect.TypeOf(apigen.IssuePatchBody{})},
|
|
} {
|
|
t.Run(tc.schema, func(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range tc.accepted {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, tc.goType)
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated %s declares members the update handler refuses as unknown: %v\n"+
|
|
"teach the handler to honor them, or the document promises a member the server turns down", tc.schema, extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the update handler accepts members %s does not declare: %v", tc.schema, missing)
|
|
}
|
|
|
|
specProps := schemaProperties(t, doc, mapAt(t, schemas, tc.schema))
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the %s schema documents members the update handler refuses: %v", tc.schema, extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the update handler accepts members the %s schema does not document: %v", tc.schema, missing)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestCreateIssueRequestMembersMatchTheHandler is the update's gate for the
|
|
// single create, at ALL THREE of its levels.
|
|
//
|
|
// It carries the weight the batch create's narrow item did not. That operation
|
|
// publishes nine members and its handler's copy of the list is small enough to
|
|
// eyeball; this one publishes the whole create vocabulary, so a spec revision
|
|
// adding an optional member would leave `make api-check` and every other spec
|
|
// test green while the server refused the newly documented member as
|
|
// unknown_parameter — and the reverse, a member the handler honors that the
|
|
// document never promised, is undisclosed write surface on a mutation that can
|
|
// mint a row at an id the caller chose.
|
|
func TestCreateIssueRequestMembersMatchTheHandler(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
schemas := mapAt(t, mapAt(t, doc, "components"), "schemas")
|
|
|
|
for _, tc := range []struct {
|
|
schema string
|
|
accepted []string
|
|
goType reflect.Type
|
|
}{
|
|
{"CreateIssueRequest", createRequestMembers, reflect.TypeOf(apigen.CreateIssueRequest{})},
|
|
{"CreateIssueDependency", createDependencyMembers, reflect.TypeOf(apigen.CreateIssueDependency{})},
|
|
{"CreateIssueWaitsFor", createWaitsForMembers, reflect.TypeOf(apigen.CreateIssueWaitsFor{})},
|
|
} {
|
|
t.Run(tc.schema, func(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range tc.accepted {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, tc.goType)
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated %s declares members the create handler refuses as unknown: %v\n"+
|
|
"teach the handler to honor them, or the document promises a member the server turns down", tc.schema, extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the create handler accepts members %s does not declare: %v", tc.schema, missing)
|
|
}
|
|
|
|
specProps := schemaProperties(t, doc, mapAt(t, schemas, tc.schema))
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the %s schema documents members the create handler refuses: %v", tc.schema, extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the create handler accepts members the %s schema does not document: %v", tc.schema, missing)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestCreateIssueRequestPublishesNoNullableMember pins the create side of the
|
|
// rule TestNullablePatchMembersAreExactlyTheDocumentsNullableOnes pins for the
|
|
// patch: on this body the nullable set is EMPTY, and the handler refuses an
|
|
// explicit null on every member but `metadata`.
|
|
//
|
|
// The two can drift in the direction that matters. A member marked nullable
|
|
// here would promise a clear on a create — a create has nothing to clear, so
|
|
// the promise could only be kept by writing a zero value the caller did not ask
|
|
// for — while the handler would keep answering 400. Asserting the empty set is
|
|
// what makes the four members that ARE nullable on `IssuePatchBody` a statement
|
|
// about patching rather than about the field.
|
|
func TestCreateIssueRequestPublishesNoNullableMember(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
for _, schema := range []string{"CreateIssueRequest", "CreateIssueDependency", "CreateIssueWaitsFor"} {
|
|
node := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), schema)
|
|
for name, raw := range mapAt(t, node, "properties") {
|
|
prop, ok := raw.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("%s property %q is %T, want a mapping", schema, name, raw)
|
|
}
|
|
if nullable, _ := prop["nullable"].(bool); nullable {
|
|
t.Errorf("%s.%s is documented nullable and the create handler refuses a null on it; "+
|
|
"a create has nothing to clear, so a nullable member here promises a write nobody asked for", schema, name)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestReopenRequestMembersMatchTheHandler is the claim's and the close's gate
|
|
// for the reopen body. The reopen decodes raw members for the same reason its
|
|
// mirror does — so a refusal can name the offending one, which is what makes
|
|
// the schema's additionalProperties: false enforceable by a client that has
|
|
// stopped parsing prose — and pays the same price: a hand-rolled copy of the
|
|
// member list with nothing tying it to the document.
|
|
func TestReopenRequestMembersMatchTheHandler(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range reopenRequestMembers {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, reflect.TypeOf(apigen.ReopenIssueRequest{}))
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated ReopenIssueRequest declares members the reopen handler refuses as unknown: %v\n"+
|
|
"teach reopenRequest to honor them, or the document promises a member the server turns down", extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the reopen handler accepts members ReopenIssueRequest does not declare: %v", missing)
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "ReopenIssueRequest")
|
|
specProps := schemaProperties(t, doc, schema)
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the ReopenIssueRequest schema documents members the reopen handler refuses: %v", extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the reopen handler accepts members the ReopenIssueRequest schema does not document: %v", missing)
|
|
}
|
|
}
|
|
|
|
// TestDeleteRequestMembersMatchTheHandler is the reopen's gate for the delete
|
|
// body, and it is new in the slice that gave that body a sixth member.
|
|
//
|
|
// The gap it closes is the same one every gate in this file closes, on the
|
|
// operation where it costs the most. `deleteMembers` is a hand-rolled copy of
|
|
// the schema — the handler reads raw members so a refusal can name the
|
|
// offending one, which on THIS operation is the difference between orphaning a
|
|
// dependent and deleting it — and nothing tied that copy to the document.
|
|
// A member documented and not honored is refused as `unknown_parameter` with
|
|
// every other gate green; a member honored and not documented is undisclosed
|
|
// input on an irreversible write.
|
|
func TestDeleteRequestMembersMatchTheHandler(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range deleteMembers {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, reflect.TypeOf(apigen.DeleteIssuesRequest{}))
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated DeleteIssuesRequest declares members the delete handler refuses as unknown: %v\n"+
|
|
"teach deleteRequest to honor them, or the document promises a member the server turns down", extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the delete handler accepts members DeleteIssuesRequest does not declare: %v", missing)
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "DeleteIssuesRequest")
|
|
specProps := schemaProperties(t, doc, schema)
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the DeleteIssuesRequest schema documents members the delete handler refuses: %v", extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the delete handler accepts members the DeleteIssuesRequest schema does not document: %v", missing)
|
|
}
|
|
}
|
|
|
|
// TestCompareAndSetMetadataRequestMembersMatchTheHandler is the reopen's gate
|
|
// for the compare-and-set body, and it earns its place twice over: this handler
|
|
// reads raw members not only to name an offending one but because the OMISSION
|
|
// of `expected` and `value` is meaningful, so it can never decode into the
|
|
// generated struct and let the compiler hold the two lists together.
|
|
func TestCompareAndSetMetadataRequestMembersMatchTheHandler(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range metadataCASRequestMembers {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, reflect.TypeOf(apigen.CompareAndSetMetadataRequest{}))
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated CompareAndSetMetadataRequest declares members the handler refuses as unknown: %v\n"+
|
|
"teach compareAndSetMetadataRequest to honor them, or the document promises a member the server turns down", extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the compare-and-set handler accepts members CompareAndSetMetadataRequest does not declare: %v", missing)
|
|
}
|
|
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "CompareAndSetMetadataRequest")
|
|
specProps := schemaProperties(t, doc, schema)
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the CompareAndSetMetadataRequest schema documents members the handler refuses: %v", extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the compare-and-set handler accepts members the CompareAndSetMetadataRequest schema does not document: %v", missing)
|
|
}
|
|
}
|
|
|
|
// TestDependencyRequestMembersMatchTheHandlers is the same gate for the two
|
|
// dependency bodies, and for the add's NESTED level — the update's table-driven
|
|
// form because, exactly as there, the body has a level below it.
|
|
//
|
|
// `edges[i]` is where this matters most on the graph side. It is the only
|
|
// member list on the surface checked inside a loop, its refusals are reported
|
|
// as `edges[i].member` rather than by bare name, and a member the document grew
|
|
// there would be refused per edge with an index attached — a failure that reads
|
|
// like a data problem in one row rather than like version skew, which is the
|
|
// slowest possible way to discover a spec revision.
|
|
func TestDependencyRequestMembersMatchTheHandlers(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
schemas := mapAt(t, mapAt(t, doc, "components"), "schemas")
|
|
|
|
for _, tc := range []struct {
|
|
schema string
|
|
accepted []string
|
|
goType reflect.Type
|
|
}{
|
|
{"AddDependenciesRequest", addDependenciesMembers, reflect.TypeOf(apigen.AddDependenciesRequest{})},
|
|
{"DependencyEdge", dependencyEdgeMembers, reflect.TypeOf(apigen.DependencyEdge{})},
|
|
{"RemoveDependencyRequest", removeDependencyMembers, reflect.TypeOf(apigen.RemoveDependencyRequest{})},
|
|
} {
|
|
t.Run(tc.schema, func(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range tc.accepted {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, tc.goType)
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated %s declares members the handler refuses as unknown: %v\n"+
|
|
"teach the handler to honor them, or the document promises a member the server turns down", tc.schema, extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the handler accepts members %s does not declare: %v", tc.schema, missing)
|
|
}
|
|
|
|
specProps := schemaProperties(t, doc, mapAt(t, schemas, tc.schema))
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the %s schema documents members the handler refuses: %v", tc.schema, extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the handler accepts members the %s schema does not document: %v", tc.schema, missing)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchRequestMembersMatchTheHandler is the same gate for the apply
|
|
// body, at ALL TEN of its levels — the dependency add's table-driven form,
|
|
// because this body nests four deep and every level is a hand-rolled member
|
|
// list.
|
|
//
|
|
// It carries the most weight of any row in this file, for a reason specific to
|
|
// this operation. The item is a TAGGED SINGLE-SHAPE OBJECT rather than a schema
|
|
// alternation, so the generated type makes all four payload members
|
|
// constructible at once and the compiler can see nothing about which one
|
|
// belongs with which tag; the handler is the only thing enforcing it, and its
|
|
// accepted set at each level is a copy of the document with nothing tying the
|
|
// two together. A spec revision adding an optional member at any level would
|
|
// otherwise leave `make api-check` and every other spec test green while the
|
|
// server refused the newly documented member as unknown_parameter — and the
|
|
// reverse, a member the handler honors that the document never promised, is
|
|
// undisclosed write surface on the widest mutation this API has.
|
|
func TestApplyBatchRequestMembersMatchTheHandler(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
schemas := mapAt(t, mapAt(t, doc, "components"), "schemas")
|
|
|
|
for _, tc := range []struct {
|
|
schema string
|
|
accepted []string
|
|
goType reflect.Type
|
|
}{
|
|
{"ApplyBatchRequest", applyBatchRequestMembers, reflect.TypeOf(apigen.ApplyBatchRequest{})},
|
|
{"ApplyItem", applyItemMembers, reflect.TypeOf(apigen.ApplyItem{})},
|
|
{"Ref", applyRefMembers, reflect.TypeOf(apigen.Ref{})},
|
|
{"ApplyCreateItem", applyCreateItemMembers, reflect.TypeOf(apigen.ApplyCreateItem{})},
|
|
{"ApplyUpdateItem", applyUpdateItemMembers, reflect.TypeOf(apigen.ApplyUpdateItem{})},
|
|
{"ApplyPatchBody", applyPatchMembers, reflect.TypeOf(apigen.ApplyPatchBody{})},
|
|
{"ApplyLabelPatch", applyLabelPatchMembers, reflect.TypeOf(apigen.ApplyLabelPatch{})},
|
|
{"ApplyMetadataPatch", applyMetadataPatchMembers, reflect.TypeOf(apigen.ApplyMetadataPatch{})},
|
|
{"ApplyCloseItem", applyCloseItemMembers, reflect.TypeOf(apigen.ApplyCloseItem{})},
|
|
{"ApplyDepAddItem", applyDepAddItemMembers, reflect.TypeOf(apigen.ApplyDepAddItem{})},
|
|
} {
|
|
t.Run(tc.schema, func(t *testing.T) {
|
|
accepted := map[string]bool{}
|
|
for _, name := range tc.accepted {
|
|
accepted[name] = true
|
|
}
|
|
|
|
goFields := jsonTagNames(t, tc.goType)
|
|
if extra := diff(goFields, accepted); len(extra) > 0 {
|
|
t.Errorf("generated %s declares members the apply handler refuses as unknown: %v\n"+
|
|
"teach the handler to honor them, or the document promises a member the server turns down", tc.schema, extra)
|
|
}
|
|
if missing := diff(accepted, goFields); len(missing) > 0 {
|
|
t.Errorf("the apply handler accepts members %s does not declare: %v", tc.schema, missing)
|
|
}
|
|
|
|
specProps := schemaProperties(t, doc, mapAt(t, schemas, tc.schema))
|
|
if extra := diff(specProps, accepted); len(extra) > 0 {
|
|
t.Errorf("the %s schema documents members the apply handler refuses: %v", tc.schema, extra)
|
|
}
|
|
if missing := diff(accepted, specProps); len(missing) > 0 {
|
|
t.Errorf("the apply handler accepts members the %s schema does not document: %v", tc.schema, missing)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestApplyItemKindsAreExactlyTheDocumentsEnum pins the TAG itself, which no
|
|
// other gate can see.
|
|
//
|
|
// The item's four payload members are checked above, and its `kind` is checked
|
|
// as a member name — but the VALUES the tag may take are an enum in the document
|
|
// and a map in the handler, and a value in one and not the other is exactly the
|
|
// drift this spelling invites. A kind the document promises and the handler
|
|
// refuses is an operation a client cannot reach; a kind the handler accepts and
|
|
// the document omits is undisclosed surface on the widest mutation here.
|
|
//
|
|
// It also pins that every tag names a payload member the schema declares, which
|
|
// is the whole content of "exactly one must be present and it must be the one
|
|
// `kind` names".
|
|
func TestApplyItemKindsAreExactlyTheDocumentsEnum(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "ApplyItem")
|
|
documented := map[string]bool{}
|
|
for _, value := range toStrings(t, mapAt(t, mapAt(t, schema, "properties"), "kind")["enum"]) {
|
|
documented[value] = true
|
|
}
|
|
|
|
served := map[string]bool{}
|
|
for kind := range applyItemKinds {
|
|
served[string(kind)] = true
|
|
}
|
|
if missing := diff(documented, served); len(missing) > 0 {
|
|
t.Errorf("the document promises item kinds the handler refuses: %v", missing)
|
|
}
|
|
if extra := diff(served, documented); len(extra) > 0 {
|
|
t.Errorf("the handler accepts item kinds the document does not declare: %v", extra)
|
|
}
|
|
|
|
// The refusal that spells the vocabulary has to spell the same one.
|
|
spelled := map[string]bool{}
|
|
for _, name := range applyKindNames() {
|
|
spelled[name] = true
|
|
}
|
|
if missing := diff(served, spelled); len(missing) > 0 {
|
|
t.Errorf("the kind vocabulary the refusal prints omits %v", missing)
|
|
}
|
|
if extra := diff(spelled, served); len(extra) > 0 {
|
|
t.Errorf("the refusal prints kinds nothing accepts: %v", extra)
|
|
}
|
|
|
|
// Every tag must name a payload member the item schema actually declares,
|
|
// or the handler would demand a member a client has no way to send.
|
|
properties := schemaProperties(t, doc, schema)
|
|
for kind, member := range applyItemKinds {
|
|
if !properties[member] {
|
|
t.Errorf("kind %q names payload member %q, which the ApplyItem schema does not document", kind, member)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestApplyPatchNullableMembersAreExactlyTheDocumentsNullableOnes is
|
|
// TestNullablePatchMembersAreExactlyTheDocumentsNullableOnes for the apply
|
|
// operation's own patch, and it exists for the same reason with one addition:
|
|
// this body has TWO patch schemas now, and a member marked nullable in one and
|
|
// not the other would let the same field be clearable through one operation and
|
|
// not the other with nothing saying so.
|
|
func TestApplyPatchNullableMembersAreExactlyTheDocumentsNullableOnes(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "ApplyPatchBody")
|
|
|
|
documented := map[string]bool{}
|
|
for name, raw := range mapAt(t, schema, "properties") {
|
|
prop, ok := raw.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("property %q is %T, want a mapping", name, raw)
|
|
}
|
|
if nullable, _ := prop["nullable"].(bool); nullable {
|
|
documented[name] = true
|
|
}
|
|
}
|
|
|
|
if missing := diff(documented, applyNullablePatchMembers); len(missing) > 0 {
|
|
t.Errorf("the document marks these apply-patch members nullable and the handler refuses a null on them: %v\n"+
|
|
"a clear the contract promises would be answered with a 400", missing)
|
|
}
|
|
if extra := diff(applyNullablePatchMembers, documented); len(extra) > 0 {
|
|
t.Errorf("the handler clears these apply-patch members on an explicit null and the document does not declare them nullable: %v\n"+
|
|
"that is an unannounced clear on a field nobody agreed could be cleared", extra)
|
|
}
|
|
}
|
|
|
|
// TestNullablePatchMembersAreExactlyTheDocumentsNullableOnes pins the closed set
|
|
// on which explicit `null` CLEARS rather than refuses.
|
|
//
|
|
// The two sides can drift silently and in the worst direction: a member the
|
|
// document marks nullable but the handler does not would refuse a clear the
|
|
// contract promises, and a member the handler treats as nullable but the
|
|
// document does not would let a null through as an unannounced clear on a field
|
|
// nobody agreed could be cleared.
|
|
func TestNullablePatchMembersAreExactlyTheDocumentsNullableOnes(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "IssuePatchBody")
|
|
|
|
documented := map[string]bool{}
|
|
for name, raw := range mapAt(t, schema, "properties") {
|
|
prop, ok := raw.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("property %q is %T, want a mapping", name, raw)
|
|
}
|
|
if nullable, _ := prop["nullable"].(bool); nullable {
|
|
documented[name] = true
|
|
}
|
|
}
|
|
|
|
if missing := diff(documented, nullablePatchMembers); len(missing) > 0 {
|
|
t.Errorf("the document marks these patch members nullable and the handler refuses a null on them: %v\n"+
|
|
"a clear the contract promises would be answered with a 400", missing)
|
|
}
|
|
if extra := diff(nullablePatchMembers, documented); len(extra) > 0 {
|
|
t.Errorf("the handler clears these patch members on an explicit null and the document does not declare them nullable: %v\n"+
|
|
"that is an unannounced clear on a field nobody agreed could be cleared", extra)
|
|
}
|
|
}
|
|
|
|
// TestCustomMethodRowsDeclareTheirDocumentedPath bounds the routing exception
|
|
// from the side TestSpecRouteParity cannot see. That test compares DECLARED
|
|
// spec paths, so it stays green whatever the customMethod field says; the
|
|
// dispatcher, meanwhile, chooses a row purely by that field. If the two
|
|
// disagree — a row whose specPath ends in `:close` while its customMethod is
|
|
// `:reopen` — the documented path would reach the wrong operation with every
|
|
// gate passing.
|
|
//
|
|
// It also pins the invariant the dispatcher depends on: no two rows on one
|
|
// pattern may claim the same suffix, and a row that shares a pattern must
|
|
// declare one.
|
|
func TestCustomMethodRowsDeclareTheirDocumentedPath(t *testing.T) {
|
|
claimed := map[string]string{}
|
|
patterns := map[string]int{}
|
|
for _, rt := range routeTable {
|
|
patterns[rt.method+" "+rt.pattern]++
|
|
}
|
|
for _, rt := range routeTable {
|
|
key := rt.method + " " + rt.pattern
|
|
if rt.customMethod == "" {
|
|
if patterns[key] > 1 {
|
|
t.Errorf("%s shares the pattern %q with another row but declares no customMethod; "+
|
|
"the dispatcher has no way to choose between them", rt.op, rt.pattern)
|
|
}
|
|
continue
|
|
}
|
|
if rt.specPath == "" {
|
|
t.Errorf("%s declares customMethod %q but no specPath; the router cannot spell the documented path, "+
|
|
"so it must be declared", rt.op, rt.customMethod)
|
|
continue
|
|
}
|
|
if !strings.HasSuffix(rt.specPath, rt.customMethod) {
|
|
t.Errorf("%s: documented path %q does not end in the customMethod %q the dispatcher matches on; "+
|
|
"the documented path would reach a different operation",
|
|
rt.op, rt.specPath, rt.customMethod)
|
|
}
|
|
if prev, dup := claimed[key+rt.customMethod]; dup {
|
|
t.Errorf("%s and %s both claim the suffix %q on %q; the dispatcher would hand every such request to the first",
|
|
prev, rt.op, rt.customMethod, rt.pattern)
|
|
}
|
|
claimed[key+rt.customMethod] = rt.op
|
|
}
|
|
}
|
|
|
|
func toStrings(t *testing.T, v any) []string {
|
|
t.Helper()
|
|
if v == nil {
|
|
return nil
|
|
}
|
|
raw, ok := v.([]any)
|
|
if !ok {
|
|
t.Fatalf("value is %T, want a sequence", v)
|
|
}
|
|
out := make([]string, 0, len(raw))
|
|
for _, item := range raw {
|
|
s, ok := item.(string)
|
|
if !ok {
|
|
t.Fatalf("sequence item is %T, want a string", item)
|
|
}
|
|
out = append(out, s)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func equalStrings(a, b []string) bool {
|
|
if len(a) != len(b) {
|
|
return false
|
|
}
|
|
for i := range a {
|
|
if a[i] != b[i] {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// TestSpecSecurityMatchesRouteTable is the auth half of route/spec parity: an
|
|
// operation declares the bearer scheme in the document exactly when its route
|
|
// row is not auth-exempt. Without this the exemption column and the document's
|
|
// `security` blocks are two independent statements about the same thing, and
|
|
// the one clients read could quietly become the wrong one.
|
|
//
|
|
// Authentication is a DEPLOYMENT posture — a server started with no token file
|
|
// never emits a 401 — so the spec's job here is to say which operations are
|
|
// guarded when it is enabled, not to claim it always is. The scheme is declared
|
|
// per operation rather than at the document level for the same reason the
|
|
// exemption is a route-table column: healthz is exempt, and a top-level
|
|
// `security` block with a per-operation override would state that twice.
|
|
func TestSpecSecurityMatchesRouteTable(t *testing.T) {
|
|
doc := loadSpec(t)
|
|
ops := specOps(t, doc)
|
|
|
|
schemes := mapAt(t, mapAt(t, doc, "components"), "securitySchemes")
|
|
bearer := mapAt(t, schemes, specBearerScheme)
|
|
if got, _ := bearer["type"].(string); got != "http" {
|
|
t.Errorf("securityScheme %s type = %q, want http", specBearerScheme, got)
|
|
}
|
|
if got, _ := bearer["scheme"].(string); got != "bearer" {
|
|
t.Errorf("securityScheme %s scheme = %q, want bearer", specBearerScheme, got)
|
|
}
|
|
if _, ok := doc["security"]; ok {
|
|
t.Error("the document declares a top-level `security` block; the exemption is per operation, so declaring it globally states the policy twice")
|
|
}
|
|
|
|
for _, rt := range routeTable {
|
|
so, ok := ops[rt.op]
|
|
if !ok {
|
|
t.Errorf("route %q is not in the spec", rt.op)
|
|
continue
|
|
}
|
|
declared := specDeclaresBearer(t, so)
|
|
if rt.authExempt && declared {
|
|
t.Errorf("%s is auth-exempt in the route table but declares %s in the spec", rt.op, specBearerScheme)
|
|
}
|
|
if !rt.authExempt && !declared {
|
|
t.Errorf("%s is guarded by the route table but declares no security in the spec", rt.op)
|
|
}
|
|
|
|
// And the 401 travels with the declaration, so a generated client of a
|
|
// guarded operation always has the status in its response set.
|
|
_, has401 := mapAt(t, so.op, "responses")["401"]
|
|
if declared != has401 {
|
|
t.Errorf("%s declares security = %v but documents a 401 = %v; the two must move together", rt.op, declared, has401)
|
|
}
|
|
}
|
|
}
|
|
|
|
func specDeclaresBearer(t *testing.T, so specOp) bool {
|
|
t.Helper()
|
|
raw, ok := so.op["security"]
|
|
if !ok {
|
|
return false
|
|
}
|
|
list, ok := raw.([]any)
|
|
if !ok {
|
|
t.Fatalf("%s: security is %T, want a sequence", so.path, raw)
|
|
}
|
|
for _, item := range list {
|
|
req, ok := item.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("%s: security item is %T, want a mapping", so.path, item)
|
|
}
|
|
if _, ok := req[specBearerScheme]; ok {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|