diff --git a/.changeset/conformance-unsupported-include-sort-endpoint.md b/.changeset/conformance-unsupported-include-sort-endpoint.md new file mode 100644 index 00000000..3aefb8be --- /dev/null +++ b/.changeset/conformance-unsupported-include-sort-endpoint.md @@ -0,0 +1,5 @@ +--- +"@thomasfosterau/effect-jsonapi": minor +--- + +`Conformance` gains two spec-tier rules that probe `include` and `sort` on an endpoint that does not declare them, so the kit now guards the 400 the middleware answers there. `spec/query/include-unsupported-endpoint` sends `?include=` to a read endpoint whose query does not declare `include` (JSON:API 1.1 §Inclusion of Related Resources: "If an endpoint does not support the `include` parameter, it **MUST** respond with `400 Bad Request` to any requests that include it"). `spec/query/sort-unsupported-endpoint` sends `?sort=` to a list or related endpoint whose query does not declare `sort` and whose response is a resource collection (§Sorting: "If the server does not support sorting as specified in the query parameter `sort`, it **MUST** return `400 Bad Request`", a section that "applies to any endpoint that responds with a resource collection as primary data"). Each fails on any status other than 400, and on a 400 whose `source.parameter` names only other parameters; a 400 with no `source.parameter` passes with a note. Each skips, saying why, when the api has no endpoint of that shape. A server that silently ignored either parameter, and passed every rule before, now fails one. diff --git a/docs/conformance.md b/docs/conformance.md index 7d8e6bc2..c3202f31 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -2,7 +2,7 @@ Design note for `Conformance` — the executable specification a server is driven through to prove it implements JSON:API v1.1, and this package's profile. Tracks [#120](https://github.com/thomasfosterau/effect-jsonapi/issues/120) (epic [#115](https://github.com/thomasfosterau/effect-jsonapi/issues/115)). -**Status:** v1 implemented, plus the write fixture ([#162](https://github.com/thomasfosterau/effect-jsonapi/issues/162)). 39 rules (34 `spec`, 5 `profile`), eight declared coverage gaps; `Conformance.rules` and `Conformance.gaps` are the live lists. +**Status:** v1 implemented, plus the write fixture ([#162](https://github.com/thomasfosterau/effect-jsonapi/issues/162)). 41 rules (36 `spec`, 5 `profile`), eight declared coverage gaps; `Conformance.rules` and `Conformance.gaps` are the live lists. ## 0. Why it exists @@ -118,7 +118,7 @@ Four edges of the contract, stated so nobody relies on the opposite: ## 3. What v1 covers -34 rules. Every one carries a stable id, an RFC 2119 level, a section and a URL. +41 rules. Every one carries a stable id, an RFC 2119 level, a section and a URL. **Content negotiation (§Content Negotiation, §Extensions, §Profiles)** — the response media type and its permitted parameters; 415 on a parameterised request `Content-Type` (probed without `mutating: true`, so it sends the create endpoint — or failing that an update or relationship endpoint — a body `{}` that nothing can apply); 406 when every `Accept` instance is parameterised; an unsupported `ext` URI; an unrecognised `profile` ignored rather than rejected; and the two RFC 9110 §12.4.2 weight rules — a non-zero `q` is not a media type parameter, `q=0` is a refusal. The kit reported the first of those against the shipped middleware before [#101](https://github.com/thomasfosterau/effect-jsonapi/issues/101) was fixed; it now guards the fix against regressing. @@ -128,7 +128,14 @@ The document rules probe **compound** documents, not just bare ones: for each en **Error objects (§Errors, §Error Objects)** — the `{ errors: [...] }` shape; member types; `source` discrimination (`pointer` / `parameter` / `header` only, `pointer` a real JSON Pointer); and `status` agreeing with the response status. -**Query parameters (§Sparse Fieldsets, §Inclusion, §Sorting, §Query Parameters)** — sparse fieldsets applying to primary data _and_ to `included` (two rules, because they fail independently — [#112](https://github.com/thomasfosterau/effect-jsonapi/issues/112)); an unidentifiable `include` path is a 400; an unsupported `sort` field is a 400; and an all-lowercase unrecognised query parameter is a 400. +**Query parameters (§Sparse Fieldsets, §Inclusion, §Sorting, §Query Parameters)** — sparse fieldsets applying to primary data _and_ to `included` (two rules, because they fail independently — [#112](https://github.com/thomasfosterau/effect-jsonapi/issues/112)); an unidentifiable `include` path is a 400; an unsupported `sort` field is a 400; and an all-lowercase unrecognised query parameter is a 400. Those `include` / `sort` rules probe an endpoint that declares the family; two more probe one that does not ([#278](https://github.com/thomasfosterau/effect-jsonapi/issues/278)), guarding the 400 [#261](https://github.com/thomasfosterau/effect-jsonapi/issues/261) added to the middleware: + +| Rule | Probes | Expects | +| --- | --- | --- | +| `spec/query/include-unsupported-endpoint` | the first read endpoint whose query does not declare `include`, with `?include=` naming a relationship its baseline response carries inline linkage for (else a placeholder) | 400 — §Inclusion of Related Resources: "If an endpoint does not support the `include` parameter, it **MUST** respond with `400 Bad Request` to any requests that include it." | +| `spec/query/sort-unsupported-endpoint` | the first list or related endpoint whose query does not declare `sort` and whose baseline response has a resource collection as primary data, with `?sort=` naming an attribute that response carries (else a placeholder) | 400 — §Sorting: "If the server does not support sorting as specified in the query parameter `sort`, it **MUST** return `400 Bad Request`." The section "applies to any endpoint that responds with a resource collection as primary data", so a single-resource endpoint is not probed: there the 400 rests instead on the general rule in §Implementation-Specific Query Parameters, which this rule does not claim to test. | + +Whether an endpoint declares the family is read from discovery (§1: its flat wire query keys), not from a new option. A status other than 400 is a finding. So is a 400 whose error objects carry `source.parameter` naming only other parameters, since that 400 refused something else; a 400 naming no `source.parameter` at all passes with a note saying the status alone decided it, because JSON:API makes `source` optional ("It **SHOULD** include one of the following members or be omitted"). With no endpoint of the right shape the rule skips, saying whether every such endpoint declares the family or none has a resolvable URL. **Status codes** — 404 for an absent resource. With the write fixture (§1.4): a creation without a client-generated id answers 201 with the created resource as primary data (`create-response-document`); the 201 carries `Location` (`create-location`, a SHOULD — the spec's level, corrected from the MUST the never-run v1 rule claimed) and, when the resource also carries `links.self`, the two match (`create-location-matches-self`); an update answers 202, 200 with a document whose primary data — when it has any — is the updated resource (JSON:API 1.1 lets a 200 carry no primary data when the server changed nothing beyond the request; the document must then still be one, so the kit wants a top-level `meta` and no `errors`), or 204 with no response document (`update-response`); and a delete answers 204 empty, 200 with only `meta`, or 202 (`delete-response`). @@ -266,6 +273,8 @@ it("does not flag anything else when one rule is broken", async () => { A kit that fails everything catches every bug and is worthless. The control — the conformant server, against which the kit reports no failures — is the other half of the same argument. +**The two rules for a family an endpoint does not declare get their own api**, because the main fixture declares `include` on every read endpoint: `get` without `include` beside a `list` that declares `include` but not `sort`. Against a canned server that refuses both, each rule passes having probed its endpoint; a server that ignores `include` there fails the include rule alone, one that ignores `sort` fails the sort rule alone (the main fixture's `list` carries a `broken(…)` case for it too), and a 422 fails both. A 400 whose `source.parameter` blames another parameter fails; one with no `source` passes with its note. The skips are pinned — every read endpoint declaring `include`, no endpoint without it resolving, every list declaring `sort` — and so is the scope: a to-one related endpoint answering one resource is never sent `sort`. Two in-process cases hold the real middleware to the same 400s, and the write fixture's server now refuses `include`, which its api declares nowhere. + **The write rules get their own fixture too**: an api with create, update, delete and atomic operations endpoints and a canned server whose writes land in a `MutableHashMap`. Against it every write rule must pass and actually run, and the store must end empty; then each rule is broken in turn (a 200 for a creation, a 201 without the created resource or without `Location`, a `Location` that disagrees with `links.self`, an update answering a different resource, a 200 DELETE carrying `data`, an atomic response without the `ext` parameter), each asserting **exactly** that rule fails. A 200 update with no primary data and a top-level `meta` must pass; one answering `{}`, an `errors` document (with or without `meta`), a `meta` that is not an object, `data: null` or no document at all must fail, each with a finding that says which. Further cases pin that the kit refuses an id it evidently did not create: a create answer naming a resource of another type, naming the `ids` sample, naming an id a read earlier in the run returned (as primary data, only in `included`, or only as to-one or to-many linkage), naming an id the run already holds a live record for, and naming `..`, `.`, `""` or a lone surrogate — in each, no PATCH, no DELETE and no `cleanup` reaches that id (for the unsafe segments, no PATCH or DELETE is sent at all), and the record says what was named. Others show that an id the server reuses after the kit removed its first holder is still accepted, even when a read-back of the first holder showed it (`src/internal/conformance/write.test.ts`); that what an unsuccessful read carries is not counted as shown; and that every rule that creates nothing, the profile tier's included, sends its requests before the first create while the report keeps the suite's order. The parameterised-`Content-Type` rule is run against a server that ignores the media type and applies whatever it can, and must fail it while having sent nothing it could apply; two more apis pin where it sends that probe — to the create endpoint even when an update and a relationship write are discovered first, and, with no create endpoint, to the update before the relationship write. The contract itself is pinned too: nothing is written without `mutating: true`; a missing fixture or sub-key skips naming the key; a rejected payload skips rather than passes; cleanup runs after a rule that fails and after one that dies; a failing cleanup is recorded without aborting the run; and with no `cleanup` the report lists what it left. **The filter-grammar rules get their own fixture**, because nothing else would run them: no api in this repo declares `filter: true`, so against every example they legitimately report `Skipped`. A rule that skips everywhere would ship never having executed, which is indistinguishable from a rule that does not work. So `Conformance.test.ts` carries a grammar-enabled api and a canned server implementing §2/§4/§5/§7 correctly, asserts the three rules **pass and actually ran** (not skipped), and then breaks each in turn: the profile parameter dropped from the media type, an operator outside the closed core accepted, a rejection that omits `source.parameter`, and the group form answering a different document from the shorthand it desugars from. diff --git a/src/Conformance.test.ts b/src/Conformance.test.ts index 5c7ea6b4..df6ca1ab 100644 --- a/src/Conformance.test.ts +++ b/src/Conformance.test.ts @@ -160,6 +160,24 @@ const outcomeFor = (report: Conformance.Report, id: string): Conformance.Outcome return found; }; +/** A 400 error document whose one error object carries `members` too. */ +const badRequest = ( + members: { readonly source?: { readonly parameter: string } } = {}, +): Canned => ({ + status: 400, + body: { errors: [{ status: "400", title: "Bad Request", ...members }] }, +}); + +/** The query a canned request carries. */ +const queryOf = (request: { readonly path: string }): URLSearchParams => + new URLSearchParams(request.path.split("?")[1] ?? ""); + +/** A canned request's path without its query. */ +const withoutQuery = (request: R): R => ({ + ...request, + path: request.path.replace(/\?.*$/, ""), +}); + /** * A correct-enough server: negotiates per §5, answers well-formed documents, * projects sparse fieldsets, rejects unknown query parameters and absent ids. @@ -949,6 +967,15 @@ describe("Conformance: detects a deliberately broken server", () => { }, ); + // `/articles` declares no `sort`: a server that drops it instead of refusing + // it answers the collection as if it had never been sent (#278). + broken( + "a sort on a collection endpoint that does not declare it, ignored", + "spec/query/sort-unsupported-endpoint", + (canned, request) => + queryOf(request).has("sort") ? conformantServe(withoutQuery(request)) : canned, + ); + it("does not flag anything else when one rule is broken", async () => { const report = await verifyCanned((request) => { const canned = conformantServe(request); @@ -961,6 +988,208 @@ describe("Conformance: detects a deliberately broken server", () => { }); }); +// --------------------------------------------------------------------------- +// `include` / `sort` on an endpoint that does not declare them (#278) +// --------------------------------------------------------------------------- + +/** + * The main fixture declares `include` on every read endpoint, so the include + * rule has nothing to probe there. This api drops it from `get` and keeps it on + * `list`, which declares no `sort`: one endpoint for each rule to probe. + */ +describe("Conformance: include / sort on an endpoint that does not declare them", () => { + const INCLUDE = "spec/query/include-unsupported-endpoint"; + const SORT = "spec/query/sort-unsupported-endpoint"; + + const undeclaredApi = HttpApi.make("undeclared").add( + Group.make( + Article, + Endpoint.get(Article, { fields: true }), + Endpoint.list(Article, { include: true, fields: true }), + ), + ); + const verifyUndeclared = verifyOver(undeclaredApi); + + /** The baseline server, refusing `include` on `/articles/1`, which does not declare it. */ + const undeclaredServe = (request: CannedRequest): Canned => + request.path.startsWith("/articles/1") && queryOf(request).has("include") + ? badRequest({ source: { parameter: "include" } }) + : conformantServe(request); + + it("passes against a server that refuses both, each having probed its endpoint", async () => { + const report = await verifyUndeclared(undeclaredServe); + expect(failed(report)).toEqual([]); + const include = outcomeFor(report, INCLUDE); + const sort = outcomeFor(report, SORT); + expect(include).toMatchObject({ _tag: "Passed", probes: 2, note: undefined }); + expect(sort).toMatchObject({ _tag: "Passed", probes: 2, note: undefined }); + }); + + it("probes with a relationship name and an attribute name the baseline response shows", async () => { + const seen: Array = []; + await verifyUndeclared( + (request) => { + seen.push(request.path); + return undeclaredServe(request); + }, + { only: [INCLUDE, SORT] }, + ); + expect(seen).toEqual([ + "/articles/1", + "/articles/1?include=author", + "/articles", + "/articles?sort=title", + ]); + }); + + it("fails the include rule alone when the endpoint ignores `include`", async () => { + // `conformantServe` serves `?include=author` on `/articles/1` as a compound + // document — exactly what an endpoint without `include` must not do. + const report = await verifyUndeclared(conformantServe); + expect(failed(report)).toEqual([INCLUDE]); + expect(outcomeFor(report, INCLUDE)).toMatchObject({ + _tag: "Failed", + findings: [ + { + detail: + "`?include=author` on /articles/1, which does not declare `include`, was not rejected", + expected: "400 Bad Request", + observed: expect.stringMatching(/^200 /), + probe: { url: "/articles/1?include=author" }, + }, + ], + }); + }); + + it("fails the sort rule alone when the collection endpoint ignores `sort`", async () => { + const report = await verifyUndeclared((request) => + undeclaredServe(queryOf(request).has("sort") ? withoutQuery(request) : request), + ); + expect(failed(report)).toEqual([SORT]); + expect(outcomeFor(report, SORT)).toMatchObject({ + _tag: "Failed", + findings: [ + { + detail: "`?sort=title` on /articles, which does not declare `sort`, was not rejected", + observed: expect.stringMatching(/^200 /), + probe: { url: "/articles?sort=title" }, + }, + ], + }); + }); + + it("does not take a 4xx other than 400 for the refusal", async () => { + const report = await verifyUndeclared((request) => + queryOf(request).has("include") || queryOf(request).has("sort") + ? { status: 422, body: { errors: [{ status: "422", source: { parameter: "include" } }] } } + : undeclaredServe(request), + ); + const unprocessable = { + _tag: "Failed", + findings: [{ observed: expect.stringMatching(/^422 /) }], + }; + expect(outcomeFor(report, INCLUDE)).toMatchObject(unprocessable); + expect(outcomeFor(report, SORT)).toMatchObject(unprocessable); + }); + + it("fails a 400 whose `source.parameter` blames another parameter", async () => { + const report = await verifyUndeclared((request) => + queryOf(request).has("include") && request.path.startsWith("/articles/1") + ? badRequest({ source: { parameter: "fields[articles]" } }) + : undeclaredServe(request), + ); + expect(failed(report)).toEqual([INCLUDE]); + expect(outcomeFor(report, INCLUDE)).toMatchObject({ + _tag: "Failed", + findings: [ + { + expected: `source: { parameter: "include" }`, + observed: "source.parameter: `fields[articles]`", + }, + ], + }); + }); + + it("passes a 400 that names no `source.parameter` — JSON:API makes `source` optional — and says so", async () => { + const report = await verifyUndeclared((request) => { + const canned = undeclaredServe(request); + return canned.status === 400 ? badRequest() : canned; + }); + expect(failed(report)).toEqual([]); + const noted = { _tag: "Passed", note: expect.stringContaining("named no `source.parameter`") }; + expect(outcomeFor(report, INCLUDE)).toMatchObject(noted); + expect(outcomeFor(report, SORT)).toMatchObject(noted); + }); + + it("probes with a placeholder when the baseline shows no name to use", async () => { + const seen: Array = []; + await verifyUndeclared( + (request) => { + seen.push(request.path); + // Every baseline resource bare: no attributes or relationships to learn from. + const bare = { type: "articles", id: "1" }; + if (request.path === "/articles/1") return { body: { data: bare } }; + if (request.path === "/articles") return { body: { data: [bare] } }; + return undeclaredServe(request); + }, + { only: [INCLUDE, SORT] }, + ); + expect(seen).toContain("/articles/1?include=notARelationshipPath"); + expect(seen).toContain("/articles?sort=notASortableField"); + }); + + it("skips — never passes — when every read endpoint declares `include`", async () => { + const report = await verifyCanned(conformantServe, { only: [INCLUDE] }); + expect(outcomeFor(report, INCLUDE)).toMatchObject({ + _tag: "Skipped", + reason: "every read endpoint declares `include`", + }); + }); + + it("skips, naming the missing option, when no endpoint without `include` resolves", async () => { + const report = await verifyUndeclared(undeclaredServe, { ids: {}, only: [INCLUDE] }); + expect(outcomeFor(report, INCLUDE)).toMatchObject({ + _tag: "Skipped", + reason: expect.stringContaining(`ids["articles"]`), + }); + }); + + it("skips when every collection endpoint declares `sort`", async () => { + const sorted = HttpApi.make("sorted").add( + Group.make(Article, Endpoint.list(Article, { sort: true })), + ); + const report = await verifyOver(sorted)(conformantServe, { only: [SORT] }); + expect(outcomeFor(report, SORT)).toMatchObject({ + _tag: "Skipped", + reason: "every list and related endpoint declares `sort`", + }); + }); + + it("does not probe `sort` on an endpoint that answers a single resource", async () => { + // §Sorting's MUST covers collection endpoints only: a to-one related + // endpoint answering one resource is not one, whatever its role. + const toOne = HttpApi.make("toOne").add( + Group.make(Article, Endpoint.get(Article), Endpoint.related(Article, "author")), + ); + const seen: Array = []; + const report = await verifyOver(toOne)( + (request) => { + seen.push(request.path); + return request.path.startsWith("/articles/1/author") + ? { body: { data: { type: "people", id: "9", attributes: { firstName: "Dan" } } } } + : conformantServe(request); + }, + { only: [SORT] }, + ); + expect(outcomeFor(report, SORT)).toMatchObject({ + _tag: "Skipped", + reason: + "no list or related endpoint without `sort` answered with a resource collection as primary data", + }); + expect(seen.some((path) => path.includes("sort="))).toBe(false); + }); +}); + // --------------------------------------------------------------------------- // The filter grammar profile rules // --------------------------------------------------------------------------- @@ -1274,6 +1503,9 @@ describe("Conformance: the write fixture", () => { const route = `${request.method} ${request.path}`; if (route === "POST /articles") return onCreate(request); if (route === "POST /operations") return onOperations(request); + // `writeApi` declares `include` on no endpoint, so it refuses one on every + // endpoint, as JSON:API requires (#278). + if (queryOf(request).has("include")) return badRequest({ source: { parameter: "include" } }); return Option.getOrElse(onStored(request), () => conformantServe(request)); }; }; @@ -2355,13 +2587,21 @@ describe("Conformance: in-process", () => { const Live = ArticlesLive.pipe(Layer.provideMerge(Middleware.layer)); - const run = (options?: Conformance.Options) => - Effect.runPromise( - Conformance.verify(api, { ids: { articles: "1" }, ...options }).pipe( - Effect.provide(Live), - Effect.scoped, - ) as Effect.Effect, - ); + /** A run of `target` in process, its handlers and middleware from `live`. */ + const runOver = + ( + target: HttpApi.HttpApi, + live: Layer.Layer, + ) => + (options?: Conformance.Options) => + Effect.runPromise( + Conformance.verify(target, { ids: { articles: "1" }, ...options }).pipe( + Effect.provide(live), + Effect.scoped, + ) as Effect.Effect, + ); + + const run = runOver(api, Live); it("drives the real router, middleware and handlers", async () => { const report = await run(); @@ -2377,6 +2617,34 @@ describe("Conformance: in-process", () => { expect(outcomeFor(report, "spec/content-negotiation/response-media-type")._tag).toBe("Passed"); }); + it("holds the middleware to the 400 for `sort` on a collection endpoint without it (#261)", async () => { + // `list` declares `include` and `fields` but no `sort`. + const report = await run({ only: ["spec/query/sort-unsupported-endpoint"] }); + expect(outcomeFor(report, "spec/query/sort-unsupported-endpoint")).toMatchObject({ + _tag: "Passed", + probes: 2, + note: undefined, + }); + }); + + it("holds the middleware to the 400 for `include` on an endpoint without it (#261)", async () => { + const undeclared = HttpApi.make("undeclared").add( + Group.make(Article, Endpoint.get(Article, { fields: true })), + ); + const UndeclaredLive = HttpApiBuilder.group(undeclared, "articles", (handlers) => + handlers.handle("get", () => Effect.succeed(Handlers.data(article, { self: "/articles/1" }))), + ).pipe(Layer.provideMerge(Middleware.layer)); + const report = await runOver( + undeclared, + UndeclaredLive, + )({ only: ["spec/query/include-unsupported-endpoint"] }); + expect(outcomeFor(report, "spec/query/include-unsupported-endpoint")).toMatchObject({ + _tag: "Passed", + probes: 2, + note: undefined, + }); + }); + it("holds the middleware to the Accept-weight rule #101 fixed", async () => { // `q` is an Accept-header weight, not a media type parameter (RFC 9110 // §12.4.2). The kit reported this against the shipped middleware before diff --git a/src/internal/conformance/core.ts b/src/internal/conformance/core.ts index 908cb8c3..7cec13a0 100644 --- a/src/internal/conformance/core.ts +++ b/src/internal/conformance/core.ts @@ -797,6 +797,19 @@ export const errorObjectsOf = (body: unknown): ReadonlyArray => + errorObjectsOf(observation.body) + .map((error) => error["source"]) + .filter(isRecord) + .map((source) => source["parameter"]) + .filter(Predicate.isString); + /** * Appends query pairs to a path, percent-encoding values but leaving brackets * readable in keys — the spelling `Query.serialise` emits, and the one a server diff --git a/src/internal/conformance/profile.ts b/src/internal/conformance/profile.ts index 2bfc5f22..e1bbe6ed 100644 --- a/src/internal/conformance/profile.ts +++ b/src/internal/conformance/profile.ts @@ -27,7 +27,6 @@ import { coverageNote, describe, type Discovered, - errorObjectsOf, finding, type Finding, isRecord, @@ -39,6 +38,7 @@ import { type RuleImpl, settle, skip, + sourceParametersOf, withQuery, } from "./core.js"; @@ -219,11 +219,7 @@ const rejections: RuleImpl = { ); continue; } - const parameters = errorObjectsOf(observation.body) - .map((error) => error["source"]) - .filter(isRecord) - .map((source) => source["parameter"]) - .filter((parameter): parameter is string => typeof parameter === "string"); + const parameters = sourceParametersOf(observation); if (!parameters.includes(probe.key)) { findings.push( finding(rejections.rule, { diff --git a/src/internal/conformance/spec.ts b/src/internal/conformance/spec.ts index 94ee5f39..bca3c595 100644 --- a/src/internal/conformance/spec.ts +++ b/src/internal/conformance/spec.ts @@ -22,6 +22,7 @@ import { Match, Option, Predicate, + Record as Rec, Result, Schema, } from "effect"; @@ -44,10 +45,12 @@ import { parseMediaType, probeable, resourcesOf, + type Role, type Rule, type RuleImpl, settle, skip, + sourceParametersOf, withQuery, type Outcome, type Payload, @@ -104,9 +107,17 @@ const atomicRule = ( requirement, }); +/** The roles of every endpoint whose successful response is a JSON:API document. */ +const READ_ROLES: ReadonlyArray = ["collection", "resource", "related", "relationship"]; + +/** + * The roles of an endpoint that may respond with a resource collection — a + * list, or a related endpoint, which does when its relationship is to-many. + */ +const COLLECTION_ROLES: ReadonlyArray = ["collection", "related"]; + /** Every endpoint whose successful response is a JSON:API document. */ -const readable = (ctx: Context) => - probeable(ctx, ["collection", "resource", "related", "relationship"]); +const readable = (ctx: Context) => probeable(ctx, READ_ROLES); // --------------------------------------------------------------------------- // Content negotiation @@ -1214,6 +1225,171 @@ const unsupportedSort: RuleImpl = { }), }; +/** + * The endpoints of `roles` whose discovered query does not declare `family` — + * the ones that must refuse it — split as `probeable` splits them. + */ +const lacking = (ctx: Context, roles: ReadonlyArray, family: string) => + probeable( + { ...ctx, endpoints: ctx.endpoints.filter(({ queryKeys }) => !queryKeys.includes(family)) }, + roles, + ); + +/** `true` when `probeable` found no endpoint at all, resolvable or not. */ +const noEndpoint = (found: ReturnType): boolean => + Arr.isReadonlyArrayEmpty(found.resolved) && Arr.isReadonlyArrayEmpty(found.unresolved); + +/** The attribute names the first resource object of a collection carries. */ +const attributeNamesOf = (data: ReadonlyArray): ReadonlyArray => { + const attributes = data.find(isRecord)?.["attributes"]; + return isRecord(attributes) ? Rec.keys(attributes) : []; +}; + +/** + * Settles a rule on the answer to `?=…` sent to an endpoint that + * does not declare `parameter`. Only a 400 is the refusal; a 400 whose + * `source.parameter` names other parameters but not this one refused something + * else. JSON:API makes `source` a SHOULD, so a 400 naming no parameter at all + * still passes — with a note saying the status alone decided it. + */ +const settleRefusal = ( + impl: Rule, + probes: number, + refusal: { + readonly parameter: string; + readonly where: string; + readonly observation: Observation; + }, +): Outcome => { + const { parameter, where, observation } = refusal; + const sent = `\`${observation.probe.url.slice(observation.probe.url.indexOf("?"))}\``; + if (observation.status !== 400) { + return settle(impl, probes, [ + finding(impl, { + detail: `${sent} on ${where}, which does not declare \`${parameter}\`, was not rejected`, + expected: "400 Bad Request", + observed: describe(observation), + probe: observation.probe, + }), + ]); + } + return Arr.match(sourceParametersOf(observation), { + onEmpty: () => + settle( + impl, + probes, + [], + `the 400 for ${sent} named no \`source.parameter\` (optional in JSON:API), so its status alone decided this rule`, + ), + onNonEmpty: (parameters) => + settle( + impl, + probes, + parameters.includes(parameter) + ? [] + : [ + finding(impl, { + detail: `the 400 for ${sent} on ${where} does not name \`${parameter}\` in \`source.parameter\`, so it refused something else`, + expected: `source: { parameter: "${parameter}" }`, + observed: `source.parameter: ${parameters.map((name) => `\`${name}\``).join(", ")}`, + probe: observation.probe, + }), + ], + ), + }); +}; + +const includeUnsupportedEndpoint: RuleImpl = { + rule: rule( + "spec/query/include-unsupported-endpoint", + "Inclusion of Related Resources", + "fetching-includes", + "MUST", + "If an endpoint does not support the `include` parameter, it MUST respond with 400 Bad Request to any requests that include it.", + ), + run: (ctx) => + Effect.gen(function* () { + const impl = includeUnsupportedEndpoint.rule; + if (noEndpoint(readable(ctx))) return skip(impl, noProbeReason("JSON:API read endpoint", [])); + const candidates = lacking(ctx, READ_ROLES, "include"); + if (noEndpoint(candidates)) return skip(impl, "every read endpoint declares `include`"); + const target = Arr.head(candidates.resolved); + if (Option.isNone(target)) + return skip(impl, noProbeReason("read endpoint without `include`", candidates.unresolved)); + const { path } = target.value; + // A relationship the resource carries inline linkage for is the one an + // endpoint that did process `include` would visibly honour, so a server + // that ignores the parameter is caught answering 200 with `included`. + const baseline = yield* ctx.request({ url: path, headers: jsonApiAccept }); + const name = Option.getOrElse( + Arr.head(includableOf(baseline.body)), + () => "notARelationshipPath", + ); + const observation = yield* ctx.request({ + url: withQuery(path, [["include", name]]), + headers: jsonApiAccept, + }); + return settleRefusal(impl, 2, { parameter: "include", where: path, observation }); + }), +}; + +/** + * Probes `sort` on the first of `targets` whose baseline response has a + * resource collection as primary data — the only endpoints §Sorting covers; a + * to-one related endpoint answers a single resource, and is passed over. + */ +const sortFirstCollection = ( + ctx: Context, + impl: Rule, + targets: ReadonlyArray<{ readonly path: string }>, + probes: number, +): Effect.Effect => + Arr.matchLeft(targets, { + onEmpty: () => + Effect.succeed( + skip( + impl, + "no list or related endpoint without `sort` answered with a resource collection as primary data", + ), + ), + onNonEmpty: ({ path }, rest) => + Effect.gen(function* () { + const baseline = yield* ctx.request({ url: path, headers: jsonApiAccept }); + const data = isRecord(baseline.body) ? baseline.body["data"] : undefined; + if (!Array.isArray(data)) return yield* sortFirstCollection(ctx, impl, rest, probes + 1); + const name = Option.getOrElse(Arr.head(attributeNamesOf(data)), () => "notASortableField"); + const observation = yield* ctx.request({ + url: withQuery(path, [["sort", name]]), + headers: jsonApiAccept, + }); + return settleRefusal(impl, probes + 2, { parameter: "sort", where: path, observation }); + }), + }); + +const sortUnsupportedEndpoint: RuleImpl = { + rule: rule( + "spec/query/sort-unsupported-endpoint", + "Sorting", + "fetching-sorting", + "MUST", + "If the server does not support sorting as specified in the query parameter `sort`, it MUST return 400 Bad Request; this applies to any endpoint that responds with a resource collection as primary data.", + ), + run: (ctx) => { + const impl = sortUnsupportedEndpoint.rule; + if (noEndpoint(probeable(ctx, COLLECTION_ROLES))) + return Effect.succeed(skip(impl, noProbeReason("list or related endpoint", []))); + const candidates = lacking(ctx, COLLECTION_ROLES, "sort"); + if (noEndpoint(candidates)) + return Effect.succeed(skip(impl, "every list and related endpoint declares `sort`")); + if (Arr.isReadonlyArrayEmpty(candidates.resolved)) { + return Effect.succeed( + skip(impl, noProbeReason("list or related endpoint without `sort`", candidates.unresolved)), + ); + } + return sortFirstCollection(ctx, impl, candidates.resolved, 0); + }, +}; + // --------------------------------------------------------------------------- // Status codes // --------------------------------------------------------------------------- @@ -1867,6 +2043,8 @@ export const rules: ReadonlyArray = [ unknownQueryParameter, unsupportedInclude, unsupportedSort, + includeUnsupportedEndpoint, + sortUnsupportedEndpoint, resourceNotFound, createResponseDocument, createLocation,