Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .changeset/empty-vocabulary-unsupported.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
"@thomasfosterau/effect-jsonapi": patch
---

**Behaviour change: an `include` or `sort` family declared with an empty vocabulary now counts as unsupported, so a request that used to succeed can now answer 400.** This covers `include: { paths: [] }`, `include: true` on a resource with no relationships, and `sort: true` on a resource with no attributes. The `SchemaErrors` middleware now answers any `?include=` or `?sort=` on such an endpoint exactly as it answers one on an endpoint that never declared the family: a 400 naming the parameter in `source.parameter`, with the detail saying the endpoint does not support it. That includes an empty value (`?include=`, `?sort=`), which used to answer 200, and a bracketed member such as `include[x]`, which used to be ignored. A non-empty value used to answer 400 with the detail `Expected never` and `meta.includablePaths: []` / `meta.sortableFields: []`. It now gets that same unsupported-parameter 400, without the `meta` (#282).
**Behaviour change: an `include` or `sort` family declared with an empty vocabulary now counts as unsupported, so a request that used to succeed can now answer 400.** This covers `include: { paths: [] }`, `include: true` on a resource with no relationships, and `sort: true` on a resource with no attributes. The `SchemaErrors` middleware now answers any `?include=` or `?sort=` on such an endpoint exactly as it answers one on an endpoint that never declared the family: a 400 naming the parameter in `source.parameter`, with the detail saying the endpoint does not support it. That includes an empty value (`?include=`, `?sort=`), which used to answer 200, and a bracketed member such as `include[x]`, which used to be ignored. A non-empty value used to answer 400 with the detail `Expected never` and `meta.includablePaths: []` / `meta.sortableFields: []`. It now gets that same unsupported-parameter 400, without the `meta` (#282). Because the middleware answers it before content negotiation, such a request that also carries an unacceptable `Accept` or an unsupported `Content-Type` now answers this 400 where it used to answer 406 or 415, as on an endpoint that never declared the family.

Only the endpoint's own decoded `include` / `sort` property counts, read through a union and through `Schema.suspend`. A hand-built query whose `include` is `Query.IncludeList`, or whose `sort` is a custom codec, publishes no vocabulary and keeps the family supported, and so does a union in which any member's vocabulary is non-empty. A vocabulary under another property name, such as a second `Query.Include` the query declares as `other`, never decides it.

Where such a value still reaches the codec, its rejection now says why: an `allowedQueryParameters` entry that admits the family, or a direct decode with `Query.Include`, `Query.Sort` or `Query.schema`. The detail is `This endpoint supports no include paths.` or `This endpoint supports no sortable fields.` in place of `Expected never`.
2 changes: 1 addition & 1 deletion .changeset/reject-unsupported-include-sort.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@

**Behaviour change — a request that used to succeed can now answer 400:** an `include` or `sort` query parameter on an endpoint whose `query` schema does not declare it is now rejected with **400 Bad Request** instead of being ignored, as JSON:API 1.1 requires. For `include`, §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." For `sort` on an endpoint that responds with a resource collection, §Sorting: "If the server does not support sorting as specified in the query parameter `sort`, it **MUST** return `400 Bad Request`" (that section "applies to any endpoint that responds with a resource collection as primary data"). For `sort` on any other endpoint, such as a single-resource `GET`, the general rule of §Implementation-Specific Query Parameters: "If a server encounters a query parameter that does not follow the naming conventions above, or the server does not know how to process it as a query parameter from this specification, it **MUST** return `400 Bad Request`." For example `GET /articles/1?include=author` on `Endpoint.get(Article)` declared without `include`, `GET /articles/1?sort=title` on any `Endpoint.get`, `GET /articles?sort=title` on an `Endpoint.list` without `sort`, or either parameter on a `DELETE`. Any value is rejected, an empty `?include=` included, as is a bracketed member such as `include[x]`. A client that sends one of these and relied on it being ignored must stop sending it.

The 400 carries one error object per offending parameter, naming it in `source.parameter` (`code: "bad_request"`), with a detail saying the endpoint does not support the parameter. The `SchemaErrors` middleware every `Endpoint` constructor attaches answers it before the endpoint decodes anything, under `Middleware.layer`, `Middleware.layerWith`, `Middleware.layerHostNegotiated` and `Middleware.SchemaErrorsLive` alike, and `Middleware.checkQueryParameters` applies the same rule: it rejects `include` and `sort` unless `declared` lists them. An endpoint that declares the family with at least one legal value keeps answering as before; one whose vocabulary is empty is covered by a separate entry (#282). Listing `include` or `sort` in `allowedQueryParameters` admits it on every endpoint, which then ignores it. An undeclared `fields[TYPE]`, `page[…]` or `filter[…]` is still ignored.
The 400 carries one error object per offending parameter, naming it in `source.parameter` (`code: "bad_request"`), with a detail saying the endpoint does not support the parameter. The `SchemaErrors` middleware every `Endpoint` constructor attaches answers it before the endpoint decodes anything, under `Middleware.layer`, `Middleware.layerWith`, `Middleware.layerHostNegotiated` and `Middleware.SchemaErrorsLive` alike, and `Middleware.checkQueryParameters` applies the same rule: it rejects `include` and `sort` unless `declared` lists them. An endpoint that declares the family with at least one legal value keeps answering as before; one whose vocabulary is empty is covered by a separate entry (#282). Listing `include` or `sort` in `allowedQueryParameters` admits it on every endpoint: one that does not declare it then ignores it, and one that declares it with an empty vocabulary decodes it, so its codec rejects any value that names a path or field. An undeclared `fields[TYPE]`, `page[…]` or `filter[…]` is still ignored.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1286,7 +1286,7 @@ Layer.provide(

Each entry must be such a base name: `lang[region]`, `Lang`, ` lang` or `""` throws `Middleware.InvalidAllowedQueryParameter` when the layer is built, rather than silently admitting nothing (list a bracketed member by its base name; a name with any other character is never rejected, so it needs no entry).

An allowed name never reaches the endpoint's decoded `query`, which keeps only what its `query` schema declares — also when that schema declares nothing ([#260](https://github.com/thomasfosterau/effect-jsonapi/issues/260)); it is only no longer rejected. Listing `include` or `sort` switches off the specification's 400 for that family on every endpoint that doesn't declare it, which then ignores the parameter instead ([Query parameters](#query-parameters)); an endpoint that declares it still decodes it. `Middleware.checkQueryParameters(names, { declared, allowedQueryParameters })` is the same check standalone, for a hook that decodes requests itself: it returns the 400 document, or `undefined`.
An allowed name never reaches the endpoint's decoded `query`, which keeps only what its `query` schema declares — also when that schema declares nothing ([#260](https://github.com/thomasfosterau/effect-jsonapi/issues/260)); it is only no longer rejected. Listing `include` or `sort` switches off the specification's 400 for that family on every endpoint that doesn't declare it, which then ignores the parameter instead ([Query parameters](#query-parameters)); an endpoint that declares it still decodes it, so one that declares it with an empty vocabulary answers any path or field with its codec's 400 (`This endpoint supports no include paths.`). `Middleware.checkQueryParameters(names, { declared, allowedQueryParameters })` is the same check standalone, for a hook that decodes requests itself: it returns the 400 document, or `undefined`.

And to call it — the same definitions drive a fully typed client:

Expand Down
218 changes: 218 additions & 0 deletions src/Middleware.query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,25 @@ describe("spec families an endpoint does not support (#261)", () => {
// without the unsupported parameter, the same request is the 415
expect((await serve("/people/1", middleware, contentType)).status).toBe(415);
});

// A family declared with an empty vocabulary is unsupported (#282), so
// its 400 takes the same precedence; before #282 the request reached the
// negotiation, which answered 406 / 415 first.
it.each(layers)(
"for a family declared with an empty vocabulary, over a 406 and a 415, under %s",
async (_, middleware) => {
const accept = { headers: { accept: parameterised } };
const path = await serve("/tags/1?include=author", middleware, accept);
expect(path.status).toBe(400);
expect(path.body).toEqual({ errors: [unsupported("include", "include")] });
expect((await serve("/tags/1", middleware, accept)).status).toBe(406);
const contentType = { headers: { "content-type": parameterised } };
const field = await serve("/tags?sort=", middleware, contentType);
expect(field.status).toBe(400);
expect(field.body).toEqual({ errors: [unsupported("sort", "sort")] });
expect((await serve("/tags", middleware, contentType)).status).toBe(415);
},
);
});

it("applies under the host-negotiated layer too", async () => {
Expand Down Expand Up @@ -745,3 +764,202 @@ describe("spec families an endpoint does not support (#261)", () => {
expect(field.body.errors[0].source).toEqual({ parameter: "sort" });
});
});

describe("which declared `include` / `sort` an endpoint supports (#282)", () => {
// The support check reads the vocabulary the `include` / `sort` codecs
// publish, on the decoded property of that name only. A family counts as
// unsupported when every value its property could decode is drawn from an
// empty vocabulary; one that publishes no vocabulary (`Query.IncludeList`,
// a custom codec) or a non-empty one somewhere is supported.
const Person = Resource.make("people", { attributes: { name: Schema.NonEmptyString } });
const Post = Resource.make("posts", {
attributes: { title: Schema.NonEmptyString },
relationships: { author: Relationship.one(() => Person) },
});
const Tag = Resource.make("tags", { attributes: {} });

// A recursive codec with no vocabulary, so the walk must not loop on it.
// Its recursive member comes first, so a walk that reads union members in
// order reaches the recursion before the string that settles the answer.
type Nested = { readonly next?: Nested } | string;
const Nested: Schema.Codec<Nested> = Schema.Union([
Schema.Struct({
next: Schema.optionalKey(Schema.suspend((): Schema.Codec<Nested> => Nested)),
}),
Schema.String,
]);

const endpoints = {
"include-list": Schema.Struct({ include: Schema.optionalKey(Query.IncludeList) }),
"custom-sort": Schema.Struct({ sort: Schema.optionalKey(Schema.String) }),
"recursive-include": Schema.Struct({ include: Schema.optionalKey(Nested) }),
"union-of-queries": Schema.Union([
Query.schema(Tag, { include: { paths: [] } }),
Query.schema(Post, { include: true }),
]),
"union-of-sorts": Schema.Struct({
sort: Schema.optionalKey(Schema.Union([Query.Sort([]), Query.Sort(["title"])])),
}),
"union-with-open-include": Schema.Struct({
include: Schema.optionalKey(Schema.Union([Query.Include(Tag), Query.IncludeList])),
}),
"open-include-beside-empty": Schema.Struct({
include: Schema.optionalKey(Query.IncludeList),
Other: Schema.optionalKey(Query.Include(Tag)),
}),
"empty-include-beside-other": Schema.Struct({
include: Schema.optionalKey(Query.Include(Tag)),
other: Schema.optionalKey(Query.Include(Post)),
}),
"empty-sort-beside-other": Schema.Struct({
sort: Schema.optionalKey(Query.Sort([])),
order: Schema.optionalKey(Query.Sort(["title"])),
}),
"suspended-query": Schema.suspend(() => Query.schema(Tag, { include: { paths: [] } })),
"suspended-include": Schema.Struct({
include: Schema.optionalKey(Schema.suspend(() => Query.Include(Tag))),
}),
// `Schema.optional` decodes `undefined` too, which carries no value.
"optional-include": Schema.Struct({ include: Schema.optional(Query.Include(Tag)) }),
// Only the family's own vocabulary counts.
"sort-codec-as-include": Schema.Struct({ include: Schema.optionalKey(Query.Sort([])) }),
} as const;
type Name = keyof typeof endpoints;
const endpoint = <const N extends Name>(name: N) =>
HttpApiEndpoint.get(name, `/${name}`, {
query: endpoints[name],
success: Schema.Unknown,
}).middleware(Middleware.SchemaErrors);
const VocabulariesApi = HttpApi.make("vocabularies").add(
HttpApiGroup.make("vocabularies").add(
endpoint("include-list"),
endpoint("custom-sort"),
endpoint("recursive-include"),
endpoint("union-of-queries"),
endpoint("union-of-sorts"),
endpoint("union-with-open-include"),
endpoint("open-include-beside-empty"),
endpoint("empty-include-beside-other"),
endpoint("empty-sort-beside-other"),
endpoint("suspended-query"),
endpoint("suspended-include"),
endpoint("optional-include"),
endpoint("sort-codec-as-include"),
),
);
// Each handler answers the decoded `query` it received.
const echo = ({ query }: { readonly query: unknown }) => Effect.succeed(query);
const VocabulariesLive = HttpApiBuilder.group(VocabulariesApi, "vocabularies", (handlers) =>
handlers.handleAll({
"include-list": echo,
"custom-sort": echo,
"recursive-include": echo,
"union-of-queries": echo,
"union-of-sorts": echo,
"union-with-open-include": echo,
"open-include-beside-empty": echo,
"empty-include-beside-other": echo,
"empty-sort-beside-other": echo,
"suspended-query": echo,
"suspended-include": echo,
"optional-include": echo,
"sort-codec-as-include": echo,
}),
);

const serve = async (url: string) => {
const appLayer = HttpApiBuilder.layer(VocabulariesApi).pipe(
Layer.provide(VocabulariesLive),
Layer.provide(Middleware.SchemaErrorsLive),
Layer.provide(platformLayer),
);
const { dispose, handler } = HttpRouter.toWebHandler(appLayer);
const response = await handler(new Request(`http://localhost${url}`)).finally(dispose);
return { status: response.status, body: decodeJson(await response.text()) };
};

const unsupported = (family: "include" | "sort") => ({
errors: [
{
status: "400",
code: "bad_request",
title: "Bad Request",
detail: expect.stringContaining(`does not support the "${family}" parameter`),
source: { parameter: family },
},
],
});

it.each([
[
"`Query.IncludeList`, which publishes no vocabulary",
"/include-list?include=author",
{
include: ["author"],
},
],
["`Query.IncludeList`, an empty value", "/include-list?include=", { include: [] }],
["a custom `sort` codec", "/custom-sort?sort=-anything", { sort: "-anything" }],
[
"a recursive `include` codec with no vocabulary",
"/recursive-include?include=a",
{
include: "a",
},
],
[
"a union of an empty and a non-empty query",
"/union-of-queries?include=author",
{
include: ["author"],
},
],
[
"a union of an empty and a non-empty `sort`",
"/union-of-sorts?sort=title",
{
sort: [{ field: "title", direction: "asc" }],
},
],
[
"a union of an empty `include` and `Query.IncludeList`",
"/union-with-open-include?include=author",
{
include: ["author"],
},
],
[
"`Query.IncludeList` beside an empty vocabulary under another name",
"/open-include-beside-empty?include=author",
{
include: ["author"],
},
],
["another family's empty vocabulary", "/sort-codec-as-include?include=", { include: [] }],
] as const)("supports %s", async (_, url, query) => {
const response = await serve(url);
expect(response.status).toBe(200);
expect(response.body).toEqual(query);
});

it.each([
[
"an empty `include` beside a non-empty one under another name",
"/empty-include-beside-other?include=author",
"include",
],
[
"an empty `sort` beside a non-empty one under another name",
"/empty-sort-beside-other?sort=title",
"sort",
],
["a suspended query", "/suspended-query?include=author", "include"],
["a suspended query, an empty value", "/suspended-query?include=", "include"],
["a suspended `include` codec", "/suspended-include?include=author", "include"],
["an optional `include`", "/optional-include?include=", "include"],
] as const)("rejects an empty vocabulary as unsupported: %s", async (_, url, family) => {
const response = await serve(url);
expect(response.status).toBe(400);
expect(response.body).toEqual(unsupported(family));
});
});
Loading
Loading