From 7944eafe488d216b7a6b66ec098b0dededb895c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 23:26:21 +0000 Subject: [PATCH 1/2] feat(conformance): follow same-origin redirects; close #328 review items Apply the owner's decision on #168: the kit follows a redirect only when its Location stays on the base URL's origin. The transport keeps redirect: "manual"; the runner checks each hop before requesting it, follows at most five, counts each against a rule's request budget and grades the final answer. A redirect it does not follow leaves the request unanswered, naming the Location: a link is not decided, other rules drop the findings it produced, and spec/target/reachable reports it once, telling the caller to point baseUrl at the URL that serves. Also closes the review items left open on #328: related-dereferences requires a string type in resource data, memberOf's label quoting is pinned, the budget skip no longer counts unresolved URLs as searched, and the JSDoc and changeset say a layer-only RequestInit is replaced for the kit's requests. Refs #168 Claude-Session: https://claude.ai/code/session_0187g2QpzaHqEzX8GJxiJBVc Co-Authored-By: Claude --- .changeset/conformance-link-followup.md | 2 +- .../conformance-same-origin-redirects.md | 11 + docs/conformance.md | 13 +- src/Conformance.test.ts | 321 +++++++++++++- src/Conformance.ts | 25 +- src/internal/conformance/core.test.ts | 148 ++++++- src/internal/conformance/core.ts | 390 +++++++++++++++--- src/internal/conformance/crawl.ts | 40 +- src/internal/conformance/links.ts | 26 +- src/internal/conformance/pagination.ts | 10 +- src/internal/conformance/spec.ts | 73 +++- src/internal/conformance/write.test.ts | 3 + src/internal/conformance/write.ts | 8 +- 13 files changed, 957 insertions(+), 113 deletions(-) create mode 100644 .changeset/conformance-same-origin-redirects.md diff --git a/.changeset/conformance-link-followup.md b/.changeset/conformance-link-followup.md index 43d44632..4b4824f1 100644 --- a/.changeset/conformance-link-followup.md +++ b/.changeset/conformance-link-followup.md @@ -11,4 +11,4 @@ The link dereferencing rules (#168) are refined after review: - A read endpoint the request budget left unsearched now makes the rule `Skipped`, naming the budget, as a link left unfollowed already did; it could pass. - A link whose scheme has no origin (`javascript:`) is named by its scheme, not as "another origin, null". -Every `Conformance` probe, over either transport, now leaves a redirect unfollowed: `verifyWith` provides `FetchHttpClient.RequestInit` with `redirect: "manual"` (keeping the rest of the run's `RequestInit`), so a `3xx` answers as itself, as it always has in process, and a server cannot lead the kit to another origin. An answer a transport fetched from another origin all the same is not read; it is recorded as a lost response. `Conformance.verify`'s in-process transport now answers only the router's `RouteNotFound` as a 404; any other router failure dies again, as before #168. +Every `Conformance` probe, over either transport, now keeps a redirect off the transport: `verifyWith` provides `FetchHttpClient.RequestInit` with `redirect: "manual"` (keeping the rest of the run's `RequestInit`), so the transport cannot be led to another origin; which redirects the kit follows itself is described below. An answer a transport fetched from another origin all the same is not read; it is recorded as a lost response. `Conformance.verify`'s in-process transport now answers only the router's `RouteNotFound` as a 404; any other router failure dies again, as before #168. diff --git a/.changeset/conformance-same-origin-redirects.md b/.changeset/conformance-same-origin-redirects.md new file mode 100644 index 00000000..26933fd6 --- /dev/null +++ b/.changeset/conformance-same-origin-redirects.md @@ -0,0 +1,11 @@ +--- +"@thomasfosterau/effect-jsonapi": patch +--- + +`Conformance` now follows a redirect when, and only when, its `Location` stays on the base URL's origin (scheme, host and port), in both transports. Previously every `3xx` answered a probe as itself. The kit checks each hop before requesting it, so it never sends a request to another origin on a server's say-so. It follows at most five hops for one request, each counting against a rule's request budget, and grades the final answer. A `301`, `302` or `303` is followed only for a `GET` or `HEAD`; a `307` or `308` re-sends the same method and body. + +A redirect the kit does not follow leaves the request with no answer to read: one to another origin, past the hop cap or the budget, one that would turn a write into a `GET`, or one whose `Location` does not parse. An `http` → `https` redirect on the same host counts as another origin. A link it leads to is not decided, and the note names the `Location`. Any other rule drops a finding such a request produced, so it never reports a probe that went unanswered as "not rejected". It then passes on the answers it did read, noting the rest, or skips when it read none. `spec/target/reachable` reports such a redirect once instead, as one finding telling the caller to point `baseUrl` at the URL that serves. + +`spec/links/related-dereferences` now requires each resource object in the answer to carry a string `type`, so `{"data":"x"}`, `{"data":["x"]}` and `{"data":[{"id":"1"}]}` are findings. The link rules' budget skip no longer counts a read endpoint whose URL does not resolve as searched. A write rule that could not read the create's answer now names it, rather than a bare `0`. + +`Conformance.verifyWith` keeps the transport from following redirects by providing `FetchHttpClient.RequestInit` with `redirect: "manual"` over the run's own `RequestInit`, so a run's `redirect: "follow"` cannot undo it. A `RequestInit` given only to the client's layer (`FetchHttpClient.layer.pipe(Layer.provide(…))`) is replaced for the kit's requests; give it to the run instead. diff --git a/docs/conformance.md b/docs/conformance.md index 41200a82..fb440c8b 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -45,7 +45,7 @@ This is not an either/or, and it should not be two kits. In-process is the default because it is deterministic, fast (~100–200 requests in well under a second) and needs no fixture beyond sample ids. It still exercises request decoding, routing, middleware, the handler and response encoding — the whole pipeline the rules care about. A request no route serves — which a link the server emitted can lead to — is answered as a deployed server answers it (`HttpServerError.causeResponse` on the router's `RouteNotFound`: an empty 404), not turned into a defect that would make the rule that sent it `Errored` ([#168](https://github.com/thomasfosterau/effect-jsonapi/issues/168)). Only `RouteNotFound` is answered so: any other failure of the router, like any defect, still dies, as a transport that throws does, because what a deployed server would answer to it is not known. `verifyWith` takes `FetchHttpClient` and runs the same rules against a deployed server, for the things only a real deployment has: a reverse proxy rewriting `Content-Type`, a CDN, a gateway that normalises headers. -**No probe follows a redirect.** The in-process transport never has; over the wire, the kit provides `FetchHttpClient.RequestInit` with `redirect: "manual"` for its own requests, keeping the rest of the `RequestInit` the run's context holds. So a `3xx` answers a probe as itself, the status the server sent, in both transports, and a server cannot lead the kit to another origin through a redirect — not from a probe, and not from a link the kit follows (§3). Two limits remain. A transport that follows redirects on its own, outside `fetch`'s `RequestInit` (one wrapped in `HttpClient.followRedirects`, say), still sends the request; the kit then refuses to read an answer whose URL is on another origin and records it as a lost response, naming the origin, but the request has been made, so hand `verifyWith` a client that does not follow redirects. And a `RequestInit` given only to the client's own layer (`FetchHttpClient.layer.pipe(Layer.provide(…))`) is replaced for the kit's requests, since the kit's takes precedence there; provide it to the run instead. +**A redirect is followed only within the base URL's origin** (owner decision on [#168](https://github.com/thomasfosterau/effect-jsonapi/issues/168#issuecomment-6180320627)). The transport itself follows nothing: over the wire the kit provides `FetchHttpClient.RequestInit` with `redirect: "manual"` for its own requests, set over the rest of the `RequestInit` the run's context holds, so a run's own `redirect: "follow"` cannot undo it. The kit then follows a redirect itself, in both transports, after checking where its `Location` leads: only to the base URL's origin — scheme, host and port, so an `http` → `https` redirect on the same host is to another origin — and so no request is ever sent to another origin on a server's say-so. A `301`, `302` or `303` is followed only for a `GET` (or `HEAD`), since `fetch` would turn any other method into a `GET`; a `307` or `308` re-sends the same method and body. At most five hops are followed for one request, each a request of its own that counts against a rule's request budget, and the final answer is what the rule grades. A `3xx` with no `Location` answers as itself. A redirect the kit does not follow — to another origin, past the cap or the budget, turning a write into a `GET`, or to a `Location` that does not parse — leaves the request with no answer to read, and the note names the `Location`. A link the kit follows is then not decided (§3). Any other rule drops a finding such a request produced, so a probe that was never answered is never reported "not rejected"; with no finding left, the rule passes on the answers it did read, noting the rest, or skips when it read none. `spec/target/reachable` reports it once instead: a read endpoint that answers with a redirect the kit does not follow is a finding there, telling the caller to point `baseUrl` at the URL that serves. Two limits remain. A transport that follows redirects on its own, outside `fetch`'s `RequestInit` (one wrapped in `HttpClient.followRedirects`, say), still sends the request; the kit then refuses to read an answer whose URL is on another origin and records it as a lost response, naming the origin, but the request has been made, so hand `verifyWith` a client that does not follow redirects. And a `RequestInit` given only to the client's own layer (`FetchHttpClient.layer.pipe(Layer.provide(…))`) is replaced for the kit's requests, since the kit's takes precedence there; provide it to the run instead. ### 1.3 The fixture contract @@ -158,7 +158,7 @@ The rule skips, saying which, when no list or related endpoint declares a page s | Rule | Level | Follows | Expects | | --- | --- | --- | --- | | `spec/links/resource-self-dereferences` | MUST | every resource object's `links.self` | the same `(type, id)` as primary data. §Resource Links: the links object "**MAY** contain a `self` link that identifies the resource represented by the resource object", and "A server **MUST** respond to a `GET` request to the specified URL with a response that includes the resource as the primary data." | -| `spec/links/related-dereferences` | MUST | every relationship's `links.related` | a 2xx with resource data as primary data: a resource object, an array of them or `null`. §Fetching Resources: "A server **MUST** support fetching resource data for every URL provided as: … a `related` link as part of a relationship-level links object"; §Related Resource Links: "If present, a related resource link **MUST** reference a valid URL, even if the relationship isn't currently associated with any target resources." | +| `spec/links/related-dereferences` | MUST | every relationship's `links.related` | a 2xx with resource data as primary data: a resource object (an object with a string `type`), an array of them or `null`. §Fetching Resources: "A server **MUST** support fetching resource data for every URL provided as: … a `related` link as part of a relationship-level links object"; §Related Resource Links: "If present, a related resource link **MUST** reference a valid URL, even if the relationship isn't currently associated with any target resources." | | `spec/links/related-matches-linkage` | SHOULD | the `links.related` of every relationship that also carries linkage (`data`) | the resources the linkage names. §Related Resource Links: "A "related resource link" provides access to resource objects linked in a relationship. When fetched, the related resource object(s) are returned as the response's primary data." | The levels follow the keywords. The `self` rule is the spec's own MUST sentence. For `related`, the MUST is §Fetching Resources' "support fetching resource data", so `related-dereferences` holds a link only to answering resource data. Which resources it must answer is §Related Resource Links' definition, which is declarative ("are returned") and carries no keyword, so `related-matches-linkage` grades it SHOULD (owner decision on [#312](https://github.com/thomasfosterau/effect-jsonapi/pull/312), 2026-10-09). The two follow the same links and are never both failed by one: a `related` link that does not parse, answers a non-2xx or answers something other than resource data is `related-dereferences`' finding, and `related-matches-linkage` leaves it not decided, naming that rule. @@ -166,13 +166,13 @@ The levels follow the keywords. The `self` rule is the spec's own MUST sentence. The links are collected from one `GET` of every read endpoint whose URL resolves (list, single-resource and related endpoints; a relationship endpoint answers identifiers, which carry none), from primary data and any `included`. A link may be a string or a link object's `href` (§Links: "a link **MUST** be represented as either: a string whose value is a URI-reference …, a link object or `null` if the link does not exist"); one that is neither is a finding, rendered as `Formatter.format` renders it. Each link is resolved against the document that carries it and followed once: a link to a URL the rule already fetched (an article's `self` on the article's own endpoint, say) costs no request. What the answer is held to: - **`self`**: a 2xx whose `data` is a resource object of the same `type` and `id`. -- **`related`** (`related-dereferences`): a 2xx whose primary data is a resource object, an array of them or `null`, whatever the linkage says. A links-only relationship (as every `Relationship.paginated` is) has nothing more to be held to. +- **`related`** (`related-dereferences`): a 2xx whose primary data is a resource object, an array of them or `null`, whatever the linkage says. A resource object is an object with a string `type`, so `{"data":"x"}`, `{"data":["x"]}` and `{"data":[{"id":"1"}]}` are findings. A links-only relationship (as every `Relationship.paginated` is) has nothing more to be held to. - **`related`, to-one linkage** (`related-matches-linkage`): that resource as primary data; for `null` linkage, `null`. - **`related`, to-many linkage** (`related-matches-linkage`): the same set of identities, with no order. A side that is a page relaxes it to a subset: when the answer carries `next` (the related collection pages), every resource it lists must be in the linkage; when the relationship carries `next` (the linkage pages — §Relationships: "Any pagination links in a relationship object **MUST** paginate the relationship data, not the related resources"), every resource the linkage names must be in the answer. When both are pages, nothing can be compared, and the link is not decided. **What the kit cannot identify, it does not decide on, on either side.** An answer listing an item without a string `type` and `id` leaves the link not decided. So does a claim the kit cannot read: a resource object with no string `type` and `id` cannot have its `self` held to it, and linkage naming such an item cannot have its `related` held to it. Such a link is noted as not decided, without a request, rather than dropped (the `self` case) or compared with the unidentified item left out (the linkage case, which would report a resource the linkage does name as one it does not). -The crawl is the pagination walk's (`src/internal/conformance/crawl.ts`, shared): `GET` only, and a link that leads to another origin (scheme, host or port) is never requested and is reported not followed; one whose scheme gives it no origin (`javascript:`, `data:`) is named by its scheme. No request follows a redirect (§1.2), so a link cannot reach another origin that way either: a `3xx` answers the link as itself. A server error, a `429`, a `408` or a lost response leaves that link not decided, never failed. So does a `401` or `403`: access control is outside JSON:API, so a link the kit may not follow is not a broken one. Any other non-2xx — a `404` or a `3xx` included — is a finding: the run has just received the link from the server, so a 404 for it is the server contradicting itself (a live server under writes can legitimately delete a resource between the two requests; the finding names both, so they can be compared). Each rule may make 200 requests per run, the collecting `GET`s included. A crawl the budget cannot finish — a read endpoint it had no request left to search, or a link it had none left to follow — is `Skipped`, naming the budget and how far it got, never a partial pass, unless a link it did follow already broke the rule, which stands. Like the pagination walk, the crawl is bounded in requests, not in time: there is no per-request timeout, so a server that holds one response open holds the run with it (a timeout is a candidate for [#302](https://github.com/thomasfosterau/effect-jsonapi/issues/302)). A rule that decided some links and not others passes with a note naming each it could not decide; with none decided it skips, saying why. With no link to follow it skips, naming the endpoints it searched and how each that did not answer 2xx answered. A failed rule lists its first ten findings and one more counting the rest, and every server value a finding names — a resource's `type:id` included — is quoted cut to 200 UTF-16 code units, so a server with a broken link on every resource, or an id a megabyte long, does not make a report of the same size. +The crawl is the pagination walk's (`src/internal/conformance/crawl.ts`, shared): `GET` only, and a link that leads to another origin (scheme, host or port) is never requested and is reported not followed; one whose scheme gives it no origin (`javascript:`, `data:`) is named by its scheme. A redirect is followed only within the base URL's origin (§1.2), each hop counting against the budget, and the answer it leads to is what the link is held to; one the kit does not follow — off the origin, past five hops — leaves the link not decided, naming its `Location`, so a link cannot reach another origin that way either. A server error, a `429`, a `408` or a lost response leaves that link not decided, never failed. So does a `401` or `403`: access control is outside JSON:API, so a link the kit may not follow is not a broken one. Any other non-2xx — a `404`, or a `3xx` with no `Location` to follow — is a finding: the run has just received the link from the server, so a 404 for it is the server contradicting itself (a live server under writes can legitimately delete a resource between the two requests; the finding names both, so they can be compared). Each rule may make 200 requests per run, the collecting `GET`s included. A crawl the budget cannot finish — a read endpoint it had no request left to search, or a link it had none left to follow — is `Skipped`, naming the budget and how far it got, never a partial pass, unless a link it did follow already broke the rule, which stands. Like the pagination walk, the crawl is bounded in requests, not in time: there is no per-request timeout, so a server that holds one response open holds the run with it (a timeout is a candidate for [#302](https://github.com/thomasfosterau/effect-jsonapi/issues/302)). A rule that decided some links and not others passes with a note naming each it could not decide; with none decided it skips, saying why. With no link to follow it skips, naming the endpoints it searched and how each that did not answer 2xx answered. A failed rule lists its first ten findings and one more counting the rest, and every server value a finding names — a resource's `type:id` included — is quoted cut to 200 UTF-16 code units, so a server with a broken link on every resource, or an id a megabyte long, does not make a report of the same size. **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`). @@ -316,11 +316,13 @@ A kit that fails everything catches every bug and is worthless. The control — **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. +**A target behind redirects** reuses the write fixture's server, every rule run with writes on, behind a transport that redirects every request ([#168](https://github.com/thomasfosterau/effect-jsonapi/issues/168)). When each redirect stays on the run's origin (a `308` to the same path under `/live`), every rule's outcome — verdict, findings, note and reason — is the same as against the server directly; only the request counts differ. When each leads off it (a `302` to another host, or to the same host over `https`), no request is sent there, `spec/target/reachable` fails with one finding naming the `Location` and telling the caller to point `baseUrl` at the URL that serves, no other rule fails or passes, and a create the kit could not read is named by its redirect. `src/internal/conformance/core.test.ts` pins the runner and the budget: a `307` re-sends a `POST` and its body, a `302` does not turn it into a `GET`, a `3xx` without `Location` answers as itself, a `Location` that does not parse or has no origin is not followed, and each hop is a request, a chain the budget cannot finish answering nothing. + **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. **The pagination rule gets its own fixture**, because the main api declares no page size: a `tags` collection of seven, listed under `Query.Page.Offset`, `Query.Page.Number` and `Query.Page.Cursor`, and canned pagers for each that must pass — the cursor pager with opaque cursors and absolute `next` URLs, a fourth paging by default so the reference is a walk of its own — with the requests asserted, so a pass is shown to have walked. Then each way a pager breaks, one at a time, with the finding pinned: pages that repeat a resource, a skipped page (caught only against the reference), a `next` that cycles, one that never ends past the last page, one that serves the same page forever, `prev` on the first page, `last` past the end, `first` on the wrong page, a `next` leading to a 404 or to a 2xx that is not a page, one that is `{"toString":1}`, a walk that reaches a resource the reference does not list, and one that goes on past the collection's size (stopped there). A server value longer than 200 UTF-16 code units is quoted cut, never splitting a surrogate pair. The bounded cases assert the request count too. Ten collections ahead of `tags`, each spending an exact number of requests, pin the request budget of 200. With them, the budget runs out at a chosen request: before `tags` is fetched, mid-walk (not decided, never taken for a collection that ended there), at its `first` link, and at its order recheck. The skips are pinned: a `next` to another origin (never requested), a collection too long for the page budget, an endless `next` of fresh resources, a collection whose order shifts on every request (withheld, quoting §Sorting), a walk cut short to a repeat whose order then shifts, a 503, a 500, a 429, a 408 or a lost response mid-walk, each of those statuses from `first` or `last`, a 503 from the order recheck, a reference walk cut short to a repeat whose order then shifts (the recheck stopping at that first unstable page, its requests asserted), a page, a `first` page or a whole collection of items the kit cannot identify, a reference or a second walk that starts on such a page, no page size declared, a single resource, and a server that ignores the page size. An in-process case holds `Handlers.offsetPaginationLinks` and the real router to the rule. -**The link rules get their own server** (`linked` in `Conformance.test.ts`), because the main fixture's resources carry no links: two articles, each with a `self`, a to-one `author`, a to-many `tags` and a links-only `comments`, every link resolving to what it names. Against it all three rules pass, with the requests asserted, so a pass is shown to have followed each link once (a link to an endpoint already fetched costs nothing; `related-matches-linkage` does not follow the links-only `comments`). Then each way a link breaks, one at a time, with the finding pinned: a `self` that leads to another resource, to a 404 or to `data: null`; a `related` that answers something other than resource data (`related-dereferences`); and a `related` that omits a resource its linkage names, answers one it does not name, answers another to-one resource, or answers a resource where the linkage is `null` (`related-matches-linkage`, while `related-dereferences` passes the same answer). A `related` that answers 404 or is not a link at all fails `related-dereferences` once and is left not decided by `related-matches-linkage`, which skips when no relationship carries linkage. The subset relaxations are pinned both ways — a page of the related collection, and a page of linkage, each passing when it is consistent and failing when it is not — and two pages are not compared; nor are an answer, a resource or linkage holding an item without a string `type` and `id`. Link objects, a relative link (one that resolves differently against the document and against the base URL) and an absolute link to the run's own origin are followed; a link that is `{"toString":1}` is a finding; a link to another origin is never requested (every request is asserted to go to the run's origin) and is noted, or skipped when it is the only one; a `javascript:` link is named by its scheme. A `fetch` that would follow a redirect off the origin is never let to (the `302` is the answer), and an answer a transport fetched from another origin all the same is not read. A 503, a 500, a 429, a 408, a lost response and a 403 leave the link not decided. The budget is pinned at exactly 200 requests over 250 articles (skipped, naming it), and over 201 read endpoints, one never searched (skipped, naming it); a finding made before it ran out still fails the rule. Twenty-five broken links list ten findings and count the rest, and a 300-character id is quoted cut. The roles searched are pinned: a related endpoint's answer is, a relationship endpoint is never requested. The skips name what they searched. An in-process case holds the real router to the rule, including a link to a path no route serves, which fails it rather than killing it; `src/internal/conformance/core.test.ts` pins that only `RouteNotFound` is answered so, any other router failure dying. +**The link rules get their own server** (`linked` in `Conformance.test.ts`), because the main fixture's resources carry no links: two articles, each with a `self`, a to-one `author`, a to-many `tags` and a links-only `comments`, every link resolving to what it names. Against it all three rules pass, with the requests asserted, so a pass is shown to have followed each link once (a link to an endpoint already fetched costs nothing; `related-matches-linkage` does not follow the links-only `comments`). Then each way a link breaks, one at a time, with the finding pinned: a `self` that leads to another resource, to a 404 or to `data: null`; a `related` that answers something other than resource data (`related-dereferences`); and a `related` that omits a resource its linkage names, answers one it does not name, answers another to-one resource, or answers a resource where the linkage is `null` (`related-matches-linkage`, while `related-dereferences` passes the same answer). A `related` that answers 404 or is not a link at all fails `related-dereferences` once and is left not decided by `related-matches-linkage`, which skips when no relationship carries linkage. The subset relaxations are pinned both ways — a page of the related collection, and a page of linkage, each passing when it is consistent and failing when it is not — and two pages are not compared; nor are an answer, a resource or linkage holding an item without a string `type` and `id`. Link objects, a relative link (one that resolves differently against the document and against the base URL) and an absolute link to the run's own origin are followed; a link that is `{"toString":1}` is a finding; a link to another origin is never requested (every request is asserted to go to the run's origin) and is noted, or skipped when it is the only one; a `javascript:` link is named by its scheme. A `fetch` that would follow a redirect off the origin is never let to, even when the run's own `RequestInit` says `redirect: "follow"`, and the link is left not decided, naming the `Location`; an `http` → `https` redirect on the same host is treated the same way. A redirect within the origin is followed, its final answer graded (a different resource there is a finding) and its hop counted; a chain of five hops is followed and one of six is not decided; a relative link in a redirected answer resolves against where the answer came from; and an answer a transport fetched from another origin all the same is not read. A `related` answering `{"data":["x"]}`, `{"data":"x"}` or `{"data":[{"id":"1"}]}` is a finding; `{"data":null}` passes. A label the linkage names is quoted cut like any other. A 503, a 500, a 429, a 408, a lost response and a 403 leave the link not decided. The budget is pinned at exactly 200 requests over 250 articles (skipped, naming it), and over 201 read endpoints, one never searched (skipped, naming it, and not counting a read endpoint whose URL does not resolve as searched); a finding made before it ran out still fails the rule. Twenty-five broken links list ten findings and count the rest, and a 300-character id is quoted cut. The roles searched are pinned: a related endpoint's answer is, a relationship endpoint is never requested. The skips name what they searched. An in-process case holds the real router to the rule, including a link to a path no route serves, which fails it rather than killing it; `src/internal/conformance/core.test.ts` pins that only `RouteNotFound` is answered so, any other router failure dying. ## 10. Open questions @@ -328,6 +330,5 @@ A kit that fails everything catches every bug and is worthless. The control — - **Machine-readable output.** `format` renders text. A JSON rendering of `Report` is trivially derivable (it is plain data) but no stable serialisation is committed to yet. - **Opting out of the pagination walk.** It is the kit's most expensive rule — six to ten requests per paginated collection, at most 200 per run — and it walks a live server's collections. It ships with no dedicated switch: `only` selects rules, so excluding it means listing the others. Whether `Options` should gain an opt-out (or a budget) is open ([#302](https://github.com/thomasfosterau/effect-jsonapi/issues/302)). - **A link the same run just received that answers 404.** The link rules ([#168](https://github.com/thomasfosterau/effect-jsonapi/issues/168)) report it as a finding, and leave a `401` / `403` not decided. #168 left this to be decided; the alternative is to treat a 404 as not decided too, which would excuse exactly the drift (a moved route) the rules exist to catch. An owner decision. -- **A redirect answering a link the kit follows.** No request follows a redirect (§1.2), so a `self` or `related` link that answers `3xx` is a finding, as a `404` is, and a pagination `next` that does is "not a page of the collection". The alternatives are to leave such a link not decided, or to follow a redirect that stays on the run's origin; the first would excuse, and the second pass, a server whose links are not the URLs that serve them. An owner decision. - **Bounding the link crawl.** Each link rule makes at most 200 requests per run and skips when that is not enough, so a server whose read endpoints answer large collections by default gets these rules skipped rather than sampled. Whether to sample (some links per endpoint) or make the budget an option is the same question as the pagination walk's ([#302](https://github.com/thomasfosterau/effect-jsonapi/issues/302)). - **Rule versioning.** Rule ids are the stable surface a consumer pins against; a policy for renaming or retiring one is not yet written. diff --git a/src/Conformance.test.ts b/src/Conformance.test.ts index 00210a2a..4168f90b 100644 --- a/src/Conformance.test.ts +++ b/src/Conformance.test.ts @@ -22,7 +22,7 @@ import { Schema, } from "effect"; import { FetchHttpClient, HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; -import type { HttpClientRequest } from "effect/http"; +import { HttpClientRequest } from "effect/http"; import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "effect/http-api"; import * as Conformance from "./Conformance.js"; import * as Endpoint from "./Endpoint.js"; @@ -1786,6 +1786,97 @@ describe("Conformance: the write fixture", () => { ), ); + /** + * A transport in front of the server that answers every request outside + * `/live` with a `status` redirect to `to(path)` — on the run's origin, or + * not — and serves `/live/…` as the server serves `…`. `sent` is every URL + * the kit sent. + */ + const redirectingAll = (status: number, to: (path: string) => string) => { + const sent: Array = []; + return { + sent, + client: (canned: HttpClient.HttpClient) => + HttpClient.make((request, url) => { + sent.push(url.href); + if (url.pathname.startsWith("/live/")) { + return canned.execute( + HttpClientRequest.setUrl( + request, + `${url.origin}${url.pathname.slice("/live".length)}${url.search}`, + ), + ); + } + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(null, { + status, + headers: { location: to(`${url.pathname}${url.search}`) }, + }), + ), + ); + }), + }; + }; + + /** Every outcome as the report gives it, less the request count a redirect adds to. */ + const verdicts = (report: Conformance.Report) => + report.outcomes.map((outcome) => + Predicate.isTagged(outcome, "Passed") || Predicate.isTagged(outcome, "Failed") + ? { ...outcome, probes: 0 } + : outcome, + ); + + it("grades a target that redirects every request within its origin as the URL that serves", async () => { + const direct = await run(); + const redirected = redirectingAll(308, (path) => `/live${path}`); + const { report } = await run(undefined, undefined, { client: redirected.client }); + expect(redirected.sent.some((url) => url.includes("/live/"))).toBe(true); + expect(redirected.sent.every((url) => url.startsWith("http://fixture.test/"))).toBe(true); + expect(verdicts(report)).toEqual(verdicts(direct.report)); + }); + + it.each([ + ["another host", "https://elsewhere.test"], + // A change of scheme is a change of origin, on the same host as much as any. + ["the same host over https", "https://fixture.test"], + ])( + "reports a target that redirects every request to %s once, as unreachable, and decides nothing on it", + async (_, origin) => { + const redirected = redirectingAll(302, (path) => `${origin}${path}`); + const { report } = await run(undefined, undefined, { client: redirected.client }); + expect(redirected.sent.filter((url) => !url.startsWith("http://fixture.test/"))).toEqual([]); + expect(outcomeFor(report, "spec/target/reachable")).toEqual({ + _tag: "Failed", + rule: expect.anything(), + probes: 1, + findings: [ + { + rule: expect.anything(), + detail: + "every read endpoint the kit probed answered with a redirect it does not follow, so the rules that probe it have no answer to decide on — point `baseUrl` at the URL that serves the api", + expected: + "an answer from the base URL's origin, directly or through redirects that stay on it", + observed: `/articles/1: a 302 redirect to ${origin}/articles/1, which the kit does not follow: ${origin} is another origin than the base URL's, http://fixture.test — the kit follows a redirect only within the base URL's origin, and a change of scheme or port is a change of origin`, + probe: expect.anything(), + }, + ], + }); + // Nothing else is failed on answers the kit never read — no "was not + // rejected" — and nothing passes on them either. + expect(failed(report)).toEqual(["spec/target/reachable"]); + expect(Conformance.summarise(report).passed).toBe(0); + // A create the kit could not read is named by its redirect, not by a bare 0. + expect(outcomeFor(report, "spec/status/create-response-document")).toMatchObject({ + _tag: "Skipped", + reason: expect.stringContaining( + `the server did not accept writes["articles"].create (a 302 redirect to ${origin}/articles,`, + ), + }); + }, + ); + it("runs every write rule against a conformant server, on targets it created", async () => { const { report, store, writes } = await run(); expect(failed(report)).toEqual([]); @@ -3167,6 +3258,29 @@ describe("Conformance: pagination links enumerate the collection", () => { ); }); + it("follows a `next` that redirects within the origin, and leaves one that redirects off it unfinished", async () => { + const onPage2 = (answer: Canned) => (request: CannedRequest) => + queryOf(request).get("page[offset]") === "3" && !queryOf(request).has("moved") + ? answer + : offsetPager()(request); + // The same page, a hop away on the run's origin: the walk goes on. + const report = await verifyOver(offsetApi)( + onPage2({ status: 307, headers: { location: "/tags?page[offset]=3&page[limit]=3&moved=1" } }), + { only: [RULE] }, + ); + expect(outcomeFor(report, RULE)._tag).toBe("Passed"); + expect( + await skipReason( + onPage2({ + status: 302, + headers: { location: "https://elsewhere.test/tags?page[offset]=3" }, + }), + ), + ).toBe( + "no paginated collection could be walked to a verdict (/tags: `next` on page 1 (/tags?page[limit]=3) answered a 302 redirect to https://elsewhere.test/tags?page[offset]=3, which the kit does not follow: https://elsewhere.test is another origin than the base URL's, http://fixture.test — the kit follows a redirect only within the base URL's origin, and a change of scheme or port is a change of origin, so the walk could not be finished)", + ); + }); + it("does not hold a lost response mid-walk against `next`", async () => { const report = await verifyOver(offsetApi)(offsetPager(), { only: [RULE] }, (client) => HttpClient.make((request) => @@ -4318,13 +4432,35 @@ describe("Conformance: `self` and `related` links dereference", () => { }); }); + it("counts a read endpoint whose URL does not resolve as not searched", async () => { + // 202 list endpoints, one of them given a path that is no URL: the budget + // fetches 200 of the other 201, so 200 were searched — not 201. + const many = Arr.makeBy(202, (n) => Resource.make(`r${n}`, { attributes: {} })); + const wide = HttpApi.make("wide").add( + ...Arr.map(many, (resource) => Group.make(resource, Endpoint.list(resource))), + ); + const report = await verifyOver(wide)(() => ({ body: { data: [] } }), { + only: [SELF], + paths: { "r201.list": "http://[" }, + }); + expect(outcomeFor(report, SELF)).toMatchObject({ + _tag: "Skipped", + reason: + "the rule's budget of 200 requests ran out with 200 of 202 read endpoints searched for links — a partial crawl is not passed", + }); + }); + /** A JSON body for a hand-built `Response`. */ const jsonText = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); - it("lets no transport follow a redirect, to another origin least of all", async () => { + /** + * A `fetch` over `linked()` that follows a redirect unless told not to, as + * the platform's does: `/articles/2` redirects to `elsewhere`. It records + * every URL it was sent and the `credentials` each request carried. + */ + const redirectingFetch = (elsewhere: string) => { const sent: Array = []; const credentials: Array = []; - const elsewhere = "https://elsewhere.test/articles/2"; const respond = (url: URL): Response => { const canned = linked()({ method: "GET", @@ -4336,7 +4472,6 @@ describe("Conformance: `self` and `related` links dereference", () => { headers: { "content-type": MEDIA_TYPE }, }); }; - // A `fetch` that follows a redirect unless told not to, as the platform's does. const fetch = (input: RequestInfo | URL, init?: RequestInit): Promise => { const url = new URL(input instanceof Request ? input.url : input); sent.push(url.href); @@ -4350,7 +4485,15 @@ describe("Conformance: `self` and `related` links dereference", () => { sent.push(elsewhere); return Promise.resolve(respond(new URL(elsewhere))); }; - const exit = await Effect.runPromiseExit( + return { sent, credentials, fetch }; + }; + + /** A `self` run over `fetch`, with `init` as the run's own `RequestInit`. */ + const overFetch = ( + fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, + init: RequestInit, + ) => + Effect.runPromiseExit( Effect.gen(function* () { const client = yield* HttpClient.HttpClient; return yield* Conformance.verifyWith(api, { @@ -4362,20 +4505,172 @@ describe("Conformance: `self` and `related` links dereference", () => { }).pipe( Effect.provide(FetchHttpClient.layer), Effect.provideService(FetchHttpClient.Fetch, fetch), - // The run's own `RequestInit` is kept; only `redirect` is overridden. - Effect.provideService(FetchHttpClient.RequestInit, { credentials: "include" }), + Effect.provideService(FetchHttpClient.RequestInit, init), ), - ); + ).then((exit) => { + if (Exit.isFailure(exit)) return expect.unreachable(Cause.pretty(exit.cause)); + return exit.value; + }); + + it("never sends a request off the run's origin on a redirect's say-so, and leaves the link not decided", async () => { + const elsewhere = "https://elsewhere.test/articles/2"; + const { sent, credentials, fetch } = redirectingFetch(elsewhere); + // The run's own `RequestInit` is kept; only `redirect` is overridden. + const report = await overFetch(fetch, { credentials: "include" }); expect(sent.filter((url) => !url.startsWith("http://fixture.test/"))).toEqual([]); expect(credentials.every((value) => value === "include")).toBe(true); - // A redirect answers as itself, as it always has in process. - expect(Exit.isSuccess(exit)).toBe(true); - if (!Exit.isSuccess(exit)) return; - expect(findingsOf(outcomeFor(exit.value, SELF))).toEqual([ - "the `self` link of articles:2 (in /articles, at /data/1) answered 302 | 302", + expect(outcomeFor(report, SELF)).toMatchObject({ + _tag: "Passed", + note: "1 link not decided: the `self` link of articles:2 (in /articles, at /data/1) answered a 302 redirect to https://elsewhere.test/articles/2, which the kit does not follow: https://elsewhere.test is another origin than the base URL's, http://fixture.test — the kit follows a redirect only within the base URL's origin, and a change of scheme or port is a change of origin", + }); + }); + + it("keeps redirects off the transport even when the run's `RequestInit` says to follow them", async () => { + // `redirect: "manual"` is applied over the run's own `RequestInit`, never + // under it: a run that asks `fetch` to follow cannot let it. + const { sent, fetch } = redirectingFetch("https://elsewhere.test/articles/2"); + const report = await overFetch(fetch, { redirect: "follow", credentials: "include" }); + expect(sent.filter((url) => !url.startsWith("http://fixture.test/"))).toEqual([]); + expect(outcomeFor(report, SELF)).toMatchObject({ + _tag: "Passed", + note: expect.stringContaining("answered a 302 redirect to https://elsewhere.test/articles/2"), + }); + }); + + /** `serve`, with `from` redirecting (`status`) to `to`. */ + const redirecting = + ( + from: string, + to: string, + serve: (request: CannedRequest) => Canned = linked(), + status = 302, + ) => + (request: CannedRequest): Canned => + withoutQuery(request).path === from ? { status, headers: { location: to } } : serve(request); + + it("follows a redirect that stays on the run's origin, grading the final answer, and counts the hop", async () => { + const plain = recording(linked()); + const direct = await run(plain.serve, plain.client); + const hopped = recording( + redirecting( + "/old/2", + "/articles/2", + linked({ self: (id) => (id === "2" ? "/old/2" : `/articles/${id}`) }), + ), + ); + const report = await run(hopped.serve, hopped.client); + expect(outcomeFor(report, SELF)).toMatchObject({ _tag: "Passed", note: undefined }); + expect(hopped.paths()).toContain("/old/2"); + expect(hopped.urls.every((url) => url.startsWith("http://fixture.test/"))).toBe(true); + // The hop is a request of its own, counted against the rule's budget. + const probesOf = (outcome: Conformance.Outcome) => + Predicate.isTagged(outcome, "Passed") ? outcome.probes : -1; + expect(probesOf(outcomeFor(report, SELF))).toBe(probesOf(outcomeFor(direct, SELF)) + 1); + // What the redirect leads to is what is graded. + expect( + await failureOf( + SELF, + redirecting( + "/old/2", + "/articles/1", + linked({ self: (id) => (id === "2" ? "/old/2" : `/articles/${id}`) }), + ), + ), + ).toEqual([ + "the `self` link of articles:2 (in /articles, at /data/1) answers a different resource as primary data | articles:1", ]); }); + it("treats an http → https redirect on the same host as a redirect to another origin", async () => { + const hopped = recording(redirecting("/articles/2", "https://fixture.test/articles/2")); + expect(await noteOf(SELF, hopped.serve)).toBe( + "1 link not decided: the `self` link of articles:2 (in /articles, at /data/1) answered a 302 redirect to https://fixture.test/articles/2, which the kit does not follow: https://fixture.test is another origin than the base URL's, http://fixture.test — the kit follows a redirect only within the base URL's origin, and a change of scheme or port is a change of origin", + ); + const report = await run(hopped.serve, hopped.client); + expect(hopped.urls.filter((url) => url.startsWith("https:"))).toEqual([]); + expect(outcomeFor(report, SELF)._tag).toBe("Passed"); + }); + + it("follows at most five redirects for one link, naming the one it stopped at", async () => { + // `/hop/n` redirects to `/hop/n+1`, until `/hop/` redirects to the article. + const chain = + (end: number) => + (request: CannedRequest): Canned => { + const match = /^\/hop\/(\d+)$/.exec(withoutQuery(request).path); + if (match === null) + return linked({ self: (id) => (id === "2" ? "/hop/1" : `/articles/${id}`) })(request); + const n = Number(match[1]); + return { status: 307, headers: { location: n === end ? "/articles/2" : `/hop/${n + 1}` } }; + }; + // Five hops: /hop/1 … /hop/5, then the article. + expect(await noteOf(SELF, chain(5))).toBeUndefined(); + expect(await noteOf(SELF, chain(6))).toBe( + "1 link not decided: the `self` link of articles:2 (in /articles, at /data/1) answered a 307 redirect to http://fixture.test/articles/2, which the kit does not follow: it would be redirect 6 in a row, past the kit's cap of 5", + ); + }); + + it("resolves a relative link in a redirected answer against where the answer came from", async () => { + // `/articles` redirects to `/v2/articles`, whose `self` links are + // relative: `articles/1` resolves to `/v2/articles/1`, not `/articles/1`. + const v2 = (request: CannedRequest): Canned => { + const path = withoutQuery(request).path; + if (path === "/articles") return { status: 308, headers: { location: "/v2/articles" } }; + if (path === "/v2/articles") { + return { body: { data: [{ type: "articles", id: "1", links: { self: "articles/1" } }] } }; + } + if (path === "/v2/articles/1") return { body: { data: { type: "articles", id: "1" } } }; + return notFound; + }; + expect(await noteOf(SELF, v2)).toBeUndefined(); + }); + + it("holds `related` to answering resource data: a string or an array of strings is not", async () => { + const answering = (data: Json) => at("/articles/2/author", { body: { data } }); + expect(await failureOf(RELATED, answering(["x"]))).toEqual([ + 'the `related` link of articles:2\'s `author` (in /articles, at /data/1) answers no related resource data as primary data | 200 application/vnd.api+json — {"data":["x"]}', + ]); + expect(await failureOf(RELATED, answering("x"))).toEqual([ + 'the `related` link of articles:2\'s `author` (in /articles, at /data/1) answers no related resource data as primary data | 200 application/vnd.api+json — {"data":"x"}', + ]); + // A resource object carries a string `type`. + expect(await failureOf(RELATED, answering([{ id: "1" }]))).toEqual([ + 'the `related` link of articles:2\'s `author` (in /articles, at /data/1) answers no related resource data as primary data | 200 application/vnd.api+json — {"data":[{"id":"1"}]}', + ]); + expect(await noteOf(RELATED, answering(null))).toBeUndefined(); + }); + + it("quotes the label of a resource its linkage names", async () => { + const long = "y".repeat(300); + const found = await failureOf( + MATCHES, + linked({ + ids: ["1"], + author: (id) => ({ + links: { related: `/articles/${id}/author` }, + data: { type: "people", id: long }, + }), + }), + ); + expect(found).toEqual([ + "the `related` link of articles:1's `author` (in /articles/1, at /data) answers a different resource from the one its linkage names | people:9", + ]); + const outcome = outcomeFor( + await run( + linked({ + ids: ["1"], + author: (id) => ({ + links: { related: `/articles/${id}/author` }, + data: { type: "people", id: long }, + }), + }), + ), + MATCHES, + ); + expect(Predicate.isTagged(outcome, "Failed") && outcome.findings[0]?.expected).toBe( + `${`people:${long}`.slice(0, 199)}… as primary data`, + ); + }); + it("does not read an answer a transport fetched from another origin all the same", async () => { // A transport that follows redirects on its own (`HttpClient.followRedirects`, // say) reports where its answer came from. diff --git a/src/Conformance.ts b/src/Conformance.ts index ed837792..929f4cee 100644 --- a/src/Conformance.ts +++ b/src/Conformance.ts @@ -950,14 +950,23 @@ export const verify = Effect.fnUntraced(function* < * {@link verify} — which is the point, since the two answers to "in-process or * over the wire?" should not be two different kits. * - * No probe follows a redirect, as none does in process: the kit provides - * `FetchHttpClient.RequestInit` with `redirect: "manual"` for its own - * requests (keeping the rest of the `RequestInit` the run's context holds), so - * a `3xx` answers as itself and a server cannot lead the kit to another origin. - * A client that follows redirects by other means (`HttpClient.followRedirects`) - * still sends the request; the kit then does not read an answer from another - * origin, but pass a client that does not follow redirects. There is no - * per-request timeout: a server that holds a response open holds the run. + * The kit follows a redirect only when its `Location` stays on `baseUrl`'s + * origin (scheme, host and port), at most five hops for one request, each + * counted against a rule's request budget, and grades the final answer. It + * checks each hop before requesting it, so it never sends a request to another + * origin on a server's say-so: a redirect it does not follow leaves the + * request with no answer to read, and `spec/target/reachable` reports a read + * endpoint that answers with one — point `baseUrl` at the URL that serves. For + * that, the kit provides `FetchHttpClient.RequestInit` with + * `redirect: "manual"` for its own requests, over the rest of the + * `RequestInit` the run's context holds. A `RequestInit` given only to the + * client's layer (`FetchHttpClient.layer.pipe(Layer.provide(…))`) is replaced + * for the kit's requests, so give it to the run instead. A client that follows + * redirects by other means (`HttpClient.followRedirects`) still sends the + * request: the kit does not read an answer that came from another origin, but + * the request has been made, so pass a client that does not follow redirects. + * There is no per-request timeout: a server that holds a response open holds + * the run. * * @example * ```ts diff --git a/src/internal/conformance/core.test.ts b/src/internal/conformance/core.test.ts index 1d2cd020..f2548193 100644 --- a/src/internal/conformance/core.test.ts +++ b/src/internal/conformance/core.test.ts @@ -2,8 +2,11 @@ import { describe, expect, it } from "vite-plus/test"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; -import { HttpServerError, HttpServerRequest } from "effect/http"; -import { answeredAsDeployed } from "./core.js"; +import * as MutableHashSet from "effect/MutableHashSet"; +import * as Option from "effect/Option"; +import { HttpClient, HttpClientResponse, HttpServerError, HttpServerRequest } from "effect/http"; +import { answeredAsDeployed, type Context, runner } from "./core.js"; +import { budgeted } from "./crawl.js"; const request = HttpServerRequest.fromWeb(new Request("http://in-process.test/articles/1/moved")); @@ -37,3 +40,144 @@ describe("answeredAsDeployed (the in-process transport)", () => { ).toEqual([true, true]); }); }); + +/** Runs `effect` to its value; a failure or defect fails the test. */ +const valueOf = async (effect: Effect.Effect): Promise => { + const exit = await Effect.runPromiseExit(effect); + if (Exit.isFailure(exit)) return expect.unreachable(Cause.pretty(exit.cause)); + return exit.value; +}; + +/** One request a {@link served} client was sent. */ +interface Sent { + readonly method: string; + readonly url: string; + readonly body: Option.Option; +} + +/** + * A client over `answer`, keyed by path: a status, and the `Location` to + * redirect to with it. `sent` is every request. + */ +const served = (answer: (path: string) => readonly [status: number, location?: string]) => { + const sent: Array = []; + const client = HttpClient.make((request, url) => + Effect.sync(() => { + sent.push({ + method: request.method, + url: url.href, + body: + request.body._tag === "Uint8Array" + ? Option.some(new TextDecoder().decode(request.body.body)) + : Option.none(), + }); + const [status, location] = answer(url.pathname); + return HttpClientResponse.fromWeb( + request, + new Response(status === 200 ? '{"data":null}' : null, { + status, + headers: location === undefined ? {} : { location }, + }), + ); + }), + ); + return { sent, request: runner(client, "http://origin.test") }; +}; + +/** `/n` redirects (`status`) to `/n+1` until `/end`, which answers 200. */ +const chain = (status: number, end: number) => (path: string) => { + const n = Number(path.slice(1)); + return n >= end ? ([200] as const) : ([status, `/${n + 1}`] as const); +}; + +describe("runner (redirects)", () => { + it("follows a `307` or `308` with the same method and body, and a `302` only for a `GET`", async () => { + const preserved = served(chain(307, 1)); + const observation = await valueOf( + preserved.request({ method: "POST", url: "/0", body: { data: 1 } }), + ); + expect(observation.status).toBe(200); + expect(observation.redirects).toEqual(["http://origin.test/1"]); + expect( + preserved.sent.map( + ({ method, url, body }) => `${method} ${url} ${Option.getOrElse(body, () => "")}`, + ), + ).toEqual(['POST http://origin.test/0 {"data":1}', 'POST http://origin.test/1 {"data":1}']); + const changed = served(chain(302, 1)); + const refused = await valueOf( + changed.request({ method: "POST", url: "/0", body: { data: 1 } }), + ); + expect(changed.sent).toHaveLength(1); + expect(refused.status).toBe(0); + expect(Option.map(refused.unfollowed, ({ reason }) => reason)).toEqual(Option.some("method")); + const read = served(chain(302, 1)); + expect((await valueOf(read.request({ url: "/0" }))).status).toBe(200); + }); + + it("answers a `3xx` without a `Location` as itself", async () => { + const observation = await valueOf(served(() => [302]).request({ url: "/0" })); + expect(observation.status).toBe(302); + expect(observation.unfollowed).toEqual(Option.none()); + }); + + it.each([ + ["does not parse", "http://[", "unparseable"], + ["has no origin", "javascript:alert(1)", "offsite"], + ] as const)("does not follow a `Location` that %s", async (_, location, reason) => { + const target = served((path) => (path === "/0" ? [301, location] : [200])); + const observation = await valueOf(target.request({ url: "/0" })); + expect(target.sent).toHaveLength(1); + expect(Option.map(observation.unfollowed, (unfollowed) => unfollowed.reason)).toEqual( + Option.some(reason), + ); + }); + + it("follows no more redirects than the request allows, the first request included", async () => { + const target = served(chain(302, 3)); + const observation = await valueOf(target.request({ url: "/0", requests: 3 })); + expect(target.sent).toHaveLength(3); + expect(observation.redirects).toHaveLength(2); + expect(Option.map(observation.unfollowed, ({ reason }) => reason)).toEqual( + Option.some("budget"), + ); + }); +}); + +describe("budgeted (each redirect is a request)", () => { + const io = (budget: number, answer: (path: string) => readonly [number, string?]) => { + const target = served(answer); + const ctx: Context = { + endpoints: [], + options: { + baseUrl: "http://origin.test", + ids: {}, + paths: {}, + absentId: "absent", + extensions: [], + mutating: false, + writes: {}, + }, + writes: [], + observed: MutableHashSet.empty(), + request: target.request, + }; + return { sent: target.sent, io: budgeted(ctx, budget) }; + }; + const at = (path: string) => ({ url: path, href: `http://origin.test${path}` }); + + it("counts every hop it follows against the budget", async () => { + const { io: budget } = io(10, chain(302, 2)); + const answer = await valueOf(budget.fetch(at("/0"))); + expect(Option.map(answer, ({ status }) => status)).toEqual(Option.some(200)); + expect(budget.spent()).toBe(3); + }); + + it("answers nothing when the budget runs out partway through a chain", async () => { + const { io: budget, sent } = io(2, chain(302, 2)); + expect(await valueOf(budget.fetch(at("/0")))).toEqual(Option.none()); + expect(sent).toHaveLength(2); + expect(budget.spent()).toBe(2); + expect(await valueOf(budget.fetch(at("/0")))).toEqual(Option.none()); + expect(sent).toHaveLength(2); + }); +}); diff --git a/src/internal/conformance/core.ts b/src/internal/conformance/core.ts index 8b676e24..78fadce4 100644 --- a/src/internal/conformance/core.ts +++ b/src/internal/conformance/core.ts @@ -17,12 +17,14 @@ import { Predicate, Result, SchemaAST, + type Scope, } from "effect"; import { FetchHttpClient, HttpBody, HttpClient, HttpClientRequest, + type HttpClientResponse, HttpServerError, type HttpServerResponse, } from "effect/http"; @@ -130,6 +132,38 @@ export interface Observation { /** The parsed JSON body, or `undefined` when the body was empty or not JSON. */ readonly body: unknown; readonly transportError: string | undefined; + /** + * Each redirect the kit followed to reach this answer, as the absolute URL + * it then requested, in order; empty when the first answer was the answer. + * Each is one more request (see {@link runner}). + */ + readonly redirects: ReadonlyArray; + /** + * The redirect the kit did not follow, when the answer was one: `status` is + * then `0` and `transportError` says why, as for a lost response, since the + * kit has no answer to read. + */ + readonly unfollowed: Option.Option; +} + +/** + * A redirect the kit did not follow, and why. + * + * @internal + */ +export interface Unfollowed { + /** The `3xx` the server answered. */ + readonly status: number; + /** Its `Location`, resolved against the URL that answered it when it parses. */ + readonly location: string; + /** + * Why: it leads off the base URL's origin, it is one hop past + * {@link HOP_CAP}, the rule's request budget has no request left for it, it + * would turn a write into a `GET`, or its `Location` does not parse. + */ + readonly reason: "offsite" | "cap" | "budget" | "method" | "unparseable"; + /** The reason as a note names it. */ + readonly why: string; } /** @@ -446,6 +480,12 @@ export interface Context { readonly url: string; readonly headers?: Readonly>; readonly body?: unknown; + /** + * The most requests this probe may make, the redirects it follows + * included — what a budgeted rule has left. Defaults to the first request + * and {@link HOP_CAP} redirects. + */ + readonly requests?: number; }) => Effect.Effect; } @@ -482,11 +522,12 @@ const clientRequest = (url: string, probe: Probe): HttpClientRequest.HttpClientR /** * `effect`, with any redirect a `fetch`-based transport would follow left * unfollowed (`redirect: "manual"`), the rest of the run's own - * `FetchHttpClient.RequestInit` kept. A redirect answers as itself, the `3xx` - * the server sent, exactly as the in-process transport has always answered - * one — so a server cannot lead a probe, or a link the kit follows, to - * another origin through a redirect. A transport that is not `fetch`-based - * never reads `RequestInit`, and is unaffected. + * `FetchHttpClient.RequestInit` kept — `redirect` is set last, so a run's + * `redirect: "follow"` cannot override it. A redirect answers the transport as + * itself, the `3xx` the server sent, and the kit decides whether to follow it + * (see {@link runner}), checking where it leads before it is requested. A + * transport that is not `fetch`-based never reads `RequestInit`, and is + * unaffected. */ const unredirected = (effect: Effect.Effect): Effect.Effect => Effect.flatMap(Effect.serviceOption(FetchHttpClient.RequestInit), (init) => @@ -507,7 +548,12 @@ const answeredOffsite = (sent: string, answered: string): Option.Option : Option.none(); /** An `Observation` for a probe the transport returned no answer to read for. */ -const unread = (probe: Probe, transportError: string): Observation => ({ +const unread = ( + probe: Probe, + transportError: string, + redirects: ReadonlyArray = [], + unfollowed: Option.Option = Option.none(), +): Observation => ({ probe, status: 0, headers: {}, @@ -515,14 +561,118 @@ const unread = (probe: Probe, transportError: string): Observation => ({ text: "", body: undefined, transportError, + redirects, + unfollowed, }); +/** + * The most redirects the kit follows for one probe. A chain longer than this + * leaves the probe not decided, naming the `Location` it stopped at. + * + * @internal + */ +export const HOP_CAP = 5; + +/** The statuses that redirect to their `Location`. */ +const REDIRECTS: ReadonlyArray = [301, 302, 303, 307, 308]; + +/** The longest `Location` a note quotes, in UTF-16 code units. */ +const LOCATION_LIMIT = 200; + +/** + * A redirect as a note names it, and why the kit did not follow it: "302 to + * https://elsewhere.test/articles, another origin than the base URL's + * (http://fixture.test) — the kit follows a redirect only within that origin". + * + * @internal + */ +export const unfollowedNote = ({ status, location, why }: Unfollowed): string => + `a ${status} redirect to ${capped(location, LOCATION_LIMIT)}, which the kit does not follow: ${why}`; + +/** Where a `Location` off the base URL's origin leads, as a note names it. */ +const offsiteWhy = (resolved: URL, origin: string): string => + `${resolved.origin === "null" ? `a \`${resolved.protocol}\` URL has no origin` : `${resolved.origin} is another origin than the base URL's, ${origin}`} — the kit follows a redirect only within the base URL's origin, and a change of scheme or port is a change of origin`; + +/** `true` when a redirect re-sends the method it answers: `307` and `308` do; the rest turn it into a `GET`. */ +const keepsMethod = (status: number, method: string): boolean => + status === 307 || status === 308 || method === "GET" || method === "HEAD"; + +/** + * Why the kit does not take a hop to `resolved`, the first that applies in + * order, or none when it takes it. + */ +const refusalOf = ( + status: number, + resolved: URL, + sent: { readonly method: string }, + origin: string, + budget: { readonly hops: number; readonly allowed: number }, +): Option.Option => { + const refusals: ReadonlyArray string]> = [ + [resolved.origin !== origin, "offsite", () => offsiteWhy(resolved, origin)], + [ + !keepsMethod(status, sent.method), + "method", + () => + `a ${status} turns a ${sent.method} into a \`GET\`, which the kit does not send in its place`, + ], + [ + budget.hops >= HOP_CAP, + "cap", + () => `it would be redirect ${budget.hops + 1} in a row, past the kit's cap of ${HOP_CAP}`, + ], + [ + budget.hops + 1 >= budget.allowed, + "budget", + () => "the rule's request budget has no request left for it", + ], + ]; + return Option.map( + Option.fromUndefinedOr(refusals.find(([applies]) => applies)), + ([, reason, why]) => [reason, why()] as const, + ); +}; + +/** The next hop of a redirect `answer` to `sent`, or why the kit does not take it. */ +const hopOf = ( + answer: { readonly status: number; readonly location: string }, + sent: { readonly method: string; readonly url: string }, + origin: string, + budget: { readonly hops: number; readonly allowed: number }, +): Result.Result<{ readonly method: string; readonly url: string }, Unfollowed> => { + const { status, location } = answer; + if (!URL.canParse(location, sent.url)) { + return Result.fail({ + status, + location, + reason: "unparseable", + why: "its `Location` is not a URL the kit can resolve", + }); + } + const resolved = new URL(location, sent.url); + return Option.match(refusalOf(status, resolved, sent, origin, budget), { + onNone: () => Result.succeed({ method: sent.method, url: resolved.href }), + onSome: ([reason, why]) => Result.fail({ status, location: resolved.href, reason, why }), + }); +}; + /** * Builds the probe runner over an `HttpClient`. A transport failure becomes an * `Observation` with `status: 0` rather than an error, so one unreachable * endpoint is reported as a finding instead of aborting the whole run. * - * No probe follows a redirect (see {@link unredirected}). An answer a + * A redirect is followed only when its `Location` stays on the base URL's + * origin (owner decision on #168): the kit requests each hop itself, after + * checking where it leads, so no request is ever sent to another origin on a + * server's say-so. A `301`, `302` or `303` is followed only for a `GET` or + * `HEAD`, since `fetch` would turn any other method into a `GET`; a `307` or + * `308` re-sends the same method and body. At most {@link HOP_CAP} hops are + * followed, and no more than `requests` allows, the first request included. + * The final answer is the observation, with the hops in `redirects`. A redirect + * the kit does not follow leaves the probe with no answer to read: `status: 0`, + * with the redirect in `unfollowed` and named in `transportError`. + * + * The transport itself follows nothing (see {@link unredirected}). An answer a * transport fetched from another origin all the same — it followed a redirect * on its own — is not read: it is recorded as a transport failure, naming the * origin. @@ -531,46 +681,82 @@ const unread = (probe: Probe, transportError: string): Observation => ({ */ export const runner = (client: HttpClient.HttpClient, baseUrl: string): Context["request"] => - (probe) => - Effect.gen(function* () { - const method = probe.method ?? "GET"; - const headers = probe.headers ?? jsonApiAccept; - const url = probe.url.startsWith("http") - ? probe.url - : `${baseUrl.replace(/\/$/, "")}${probe.url}`; - const record: Probe = { method, url: probe.url, headers, body: probe.body }; - const request = clientRequest(url, record); - const result = yield* Effect.result(unredirected(client.execute(request))); - if (result._tag === "Failure") return unread(record, String(result.failure)); - const response = result.success; - const offsite = answeredOffsite(url, response.url); - if (Option.isSome(offsite)) { - return unread( - record, - `the transport followed a redirect to another origin, ${offsite.value}, whose answer the kit does not read`, - ); - } - const textResult = yield* Effect.result(response.text); - const text = textResult._tag === "Success" ? textResult.success : ""; - const headersOut = headerRecord(response.headers); - let body: unknown; - if (text !== "") { - try { - body = JSON.parse(text) as unknown; - } catch { - body = undefined; + (probe) => { + const method = probe.method ?? "GET"; + const headers = probe.headers ?? jsonApiAccept; + const first = probe.url.startsWith("http") + ? probe.url + : `${baseUrl.replace(/\/$/, "")}${probe.url}`; + const record: Probe = { method, url: probe.url, headers, body: probe.body }; + const origin = new URL(URL.canParse(baseUrl) ? baseUrl : first).origin; + const allowed = probe.requests ?? HOP_CAP + 1; + /** Sends one request, then the hop its redirect leads to, if the kit takes it. */ + const send = ( + sent: { readonly method: string; readonly url: string }, + redirects: ReadonlyArray, + ): Effect.Effect => + Effect.gen(function* () { + const request = clientRequest(sent.url, { ...record, method: sent.method }); + const result = yield* Effect.result(unredirected(client.execute(request))); + if (Result.isFailure(result)) return unread(record, String(result.failure), redirects); + const response = result.success; + const offsite = answeredOffsite(sent.url, response.url); + if (Option.isSome(offsite)) { + return unread( + record, + `the transport followed a redirect to another origin, ${offsite.value}, whose answer the kit does not read`, + redirects, + ); } + const location = response.headers["location"]; + if (!REDIRECTS.includes(response.status) || location === undefined) { + return yield* answerOf(record, response, redirects); + } + const hop = hopOf({ status: response.status, location }, sent, origin, { + hops: redirects.length, + allowed, + }); + return yield* Result.match(hop, { + onFailure: (unfollowed) => + Effect.succeed( + unread(record, unfollowedNote(unfollowed), redirects, Option.some(unfollowed)), + ), + onSuccess: (next) => send(next, [...redirects, next.url]), + }); + }); + return send({ method, url: first }, []).pipe(Effect.scoped, Effect.orDie); + }; + +/** The observation of an answer the kit reads: its status, headers and body. */ +const answerOf = ( + probe: Probe, + response: HttpClientResponse.HttpClientResponse, + redirects: ReadonlyArray, +): Effect.Effect => + Effect.gen(function* () { + const textResult = yield* Effect.result(response.text); + const text = Result.isSuccess(textResult) ? textResult.success : ""; + const headersOut = headerRecord(response.headers); + let body: unknown; + if (text !== "") { + try { + body = JSON.parse(text) as unknown; + } catch { + body = undefined; } - return { - probe: record, - status: response.status, - headers: headersOut, - contentType: headersOut["content-type"], - text, - body, - transportError: undefined, - } satisfies Observation; - }).pipe(Effect.scoped, Effect.orDie); + } + return { + probe, + status: response.status, + headers: headersOut, + contentType: headersOut["content-type"], + text, + body, + transportError: undefined, + redirects, + unfollowed: Option.none(), + } satisfies Observation; + }); /** * A router's answer as a deployed server gives it, for the in-process @@ -605,6 +791,13 @@ export interface RuleImpl { * before any create is vetted against it — see `Context.observed`. */ readonly creates?: true; + /** + * Set on a rule that decides for itself what a redirect the kit did not + * follow means for it — `spec/target/reachable`, and the rules that follow + * a server's links, which leave each such link not decided. Every other + * rule is held to {@link undecidedByRedirects}. + */ + readonly ownsRedirects?: true; } /** @internal */ @@ -636,9 +829,9 @@ const MESSAGE_LIMIT = 500; * cut never splits a surrogate pair: a high surrogate it would leave last is * dropped too. */ -const capped = (message: string): string => { - if (message.length <= MESSAGE_LIMIT) return message; - const end = MESSAGE_LIMIT - 1; +const capped = (message: string, limit: number = MESSAGE_LIMIT): string => { + if (message.length <= limit) return message; + const end = limit - 1; const last = message.charCodeAt(end - 1); return `${message.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end)}…`; }; @@ -693,7 +886,18 @@ export const renderThrown = (thrown: unknown): string => * @internal */ export const runRule = (implementation: RuleImpl, ctx: Context): Effect.Effect => - Effect.suspend(() => implementation.run(ctx)).pipe( + Effect.suspend(() => { + if (implementation.ownsRedirects === true) return implementation.run(ctx); + const sent: Array = []; + const watched: Context = { + ...ctx, + request: (probe) => + Effect.tap(ctx.request(probe), (observation) => Effect.sync(() => sent.push(observation))), + }; + return Effect.map(implementation.run(watched), (outcome) => + undecidedByRedirects(outcome, sent), + ); + }).pipe( Effect.catchDefect((defect) => Effect.succeed({ _tag: "Errored", @@ -704,6 +908,80 @@ export const runRule = (implementation: RuleImpl, ctx: Context): Effect.Effect, +): Outcome => { + const unread = sent.filter(({ unfollowed }) => Option.isSome(unfollowed)); + if ( + Arr.isReadonlyArrayEmpty(unread) || + Predicate.isTagged(outcome, "Skipped") || + Predicate.isTagged(outcome, "Errored") + ) { + return outcome; + } + const stands = failedOnRead(outcome, unread); + if (Option.isSome(stands)) return stands.value; + const named = redirectsNamed(unread); + if (unread.length === sent.length) { + return skip( + outcome.rule, + `no answer to decide on: every request the rule sent was answered by a redirect the kit does not follow (${named})`, + ); + } + const note = `${unread.length} of ${sent.length} requests not decided, each answered by a redirect the kit does not follow (${named})`; + return pass( + outcome.rule, + outcome.probes, + Predicate.isTagged(outcome, "Passed") && outcome.note !== undefined + ? `${outcome.note}; ${note}` + : note, + ); +}; + +/** `outcome`, failed on the findings no request in `unread` produced, when there are any. */ +const failedOnRead = ( + outcome: Passed | Failed, + unread: ReadonlyArray, +): Option.Option => { + if (Predicate.isTagged(outcome, "Passed")) return Option.none(); + const lost = unread.map(({ probe }) => probe); + const findings = outcome.findings.filter( + ({ probe }) => probe === undefined || !lost.includes(probe), + ); + return Arr.isReadonlyArrayNonEmpty(findings) + ? Option.some({ ...outcome, findings }) + : Option.none(); +}; + +/** The redirects that answered `unread`, the first {@link REASON_LIMIT} named and the rest counted. */ +const redirectsNamed = (unread: ReadonlyArray): string => { + const notes = Arr.dedupe( + unread.map( + (observation) => + `${observation.probe.method} ${observation.probe.url} answered ${statusOf(observation)}`, + ), + ); + return notes.length > REASON_LIMIT + ? `${notes.slice(0, REASON_LIMIT).join("; ")}; and ${notes.length - REASON_LIMIT} more` + : notes.join("; "); +}; + /** * Turns a rule's collected findings into its outcome: no findings is a pass, * any finding is a failure. Rules never decide their own verdict, so "ran but @@ -744,7 +1022,17 @@ export const finding = ( export const statusOf = (observation: Observation): string => observation.transportError === undefined ? `${observation.status}` - : `no response (${observation.transportError})`; + : unansweredAs(observation, observation.transportError); + +/** + * A probe with no answer to read, as a finding or a note names it: the + * redirect the kit did not follow, or the lost response. + */ +const unansweredAs = (observation: Observation, transportError: string): string => + Option.match(observation.unfollowed, { + onNone: () => `no response (${transportError})`, + onSome: unfollowedNote, + }); /** * `true` when a response came back 2xx. @@ -762,7 +1050,7 @@ export const succeeded = (observation: Observation): boolean => */ export const describe = (observation: Observation): string => { if (observation.transportError !== undefined) - return `no response (${observation.transportError})`; + return unansweredAs(observation, observation.transportError); const type = observation.contentType === undefined ? "" : ` ${observation.contentType}`; const excerpt = observation.text === "" diff --git a/src/internal/conformance/crawl.ts b/src/internal/conformance/crawl.ts index 0a0f10c6..9f549852 100644 --- a/src/internal/conformance/crawl.ts +++ b/src/internal/conformance/crawl.ts @@ -168,6 +168,20 @@ export const stepTo = (href: string, from: Target, baseUrl: string): Step => { : Step.Offsite({ to: offsite(resolved) }); }; +/** + * The URL that answered a request for `target`: the target itself, or the + * last redirect the kit followed to reach the answer. Its `url` stays the one + * requested, as findings name it; its `href` is where the answer came from, so + * a relative link in it resolves as a browser would resolve it. + * + * @internal + */ +export const answeredFrom = (target: Target, observation: Observation): Target => + Option.match(Option.fromUndefinedOr(observation.redirects.at(-1)), { + onNone: () => target, + onSome: (href) => ({ url: target.url, href }), + }); + // --------------------------------------------------------------------------- // Responses that say nothing // --------------------------------------------------------------------------- @@ -200,8 +214,10 @@ export const SAYS_NOTHING = /** * A rule's requests, under its request budget, with each answer remembered - * by href so a link to a URL the rule already fetched costs nothing. `fetch` - * answers `None` once the budget is spent. Every request is a `GET` asking + * by href so a link to a URL the rule already fetched costs nothing. Each + * redirect the kit follows (`Observation.redirects`) costs a request too. + * `fetch` answers `None` once the budget is spent, or when it runs out partway + * through a chain of redirects. Every request is a `GET` asking * for the JSON:API media type. * * @internal @@ -224,13 +240,19 @@ export const budgeted = (ctx: Context, budget: number): Io => { const refetch = (target: Target): Effect.Effect> => Effect.suspend(() => { if (spent >= budget) return Effect.succeed(Option.none()); - spent += 1; - return ctx.request({ url: target.url, headers: jsonApiAccept }).pipe( - Effect.tap((observation) => - Effect.sync(() => MutableHashMap.set(answers, target.href, observation)), - ), - Effect.map(Option.some), - ); + return ctx + .request({ url: target.url, headers: jsonApiAccept, requests: budget - spent }) + .pipe( + Effect.map((observation) => { + // Each redirect followed is a request of its own. + spent += 1 + observation.redirects.length; + if (Option.exists(observation.unfollowed, ({ reason }) => reason === "budget")) { + return Option.none(); + } + MutableHashMap.set(answers, target.href, observation); + return Option.some(observation); + }), + ); }); return { refetch, diff --git a/src/internal/conformance/links.ts b/src/internal/conformance/links.ts index 203955ef..fdce886f 100644 --- a/src/internal/conformance/links.ts +++ b/src/internal/conformance/links.ts @@ -52,6 +52,7 @@ import { succeeded, } from "./core.js"; import { + answeredFrom, budgeted, counted, type Io, @@ -279,10 +280,21 @@ const primaryOf = (observation: Observation): string => { const dataOf = (observation: Observation): unknown => isRecord(observation.body) ? observation.body["data"] : undefined; +/** + * `true` when a JSON value could be a resource object: an object with a string + * `type`, which every resource object carries (§Resource Objects). Its `id` is + * left to the rules that compare identities. + */ +// oxlint-disable-next-line effect/no-unknown-parameters -- reads whatever JSON a server answered; it has no schema to parse it by +const isResourceObject = (value: unknown): boolean => + isRecord(value) && Predicate.isString(value["type"]); + /** `true` when an answer's primary data is resource data: a resource object, an array of them, or `null`. */ const isResourceData = (observation: Observation): boolean => { const data = dataOf(observation); - return data === null || isRecord(data) || (Array.isArray(data) && data.every(isRecord)); + return ( + data === null || isResourceObject(data) || (Array.isArray(data) && data.every(isResourceObject)) + ); }; /** `true` when the related collection a response answers carries a `next` link: it is one page. */ @@ -424,6 +436,9 @@ const judgeAnswer = (judging: Judging, found: Found, observation: Observation): /** The answer to a followed link held against what it claims. */ const judge = (judging: Judging, found: Found, observation: Observation): Verdict => { + if (Option.isSome(observation.unfollowed)) { + return Verdict.Undecided({ why: `${found.where} answered ${statusOf(observation)}` }); + } if (unanswered(observation)) { return Verdict.Undecided({ why: `${found.where} got ${statusOf(observation)} — ${SAYS_NOTHING}`, @@ -686,7 +701,7 @@ const outcomeOf = ( if (left > 0) { return skip( rule, - `the rule's budget of ${REQUEST_BUDGET} requests ran out with ${fetched.length - left} of ${counted(fetched.length, "read endpoint")} searched for links — a partial crawl is not passed`, + `the rule's budget of ${REQUEST_BUDGET} requests ran out with ${fetched.filter(({ observation }) => Option.isSome(observation)).length} of ${counted(fetched.length, "read endpoint")} searched for links — a partial crawl is not passed`, ); } if (result.unfollowed > 0) { @@ -715,6 +730,9 @@ const dereferencing = ( collect: (from: Target, body: Observation["body"]) => ReadonlyArray, ): RuleImpl => ({ rule: judging.rule, + // A link a redirect the kit does not follow answers is left not decided, + // naming the redirect (`judge`), not dropped from the rule. + ownsRedirects: true, run: (ctx) => Effect.gen(function* () { const { rule } = judging; @@ -730,7 +748,9 @@ const dereferencing = ( Option.match(Option.all([observation, target]), { onNone: () => [], onSome: ([answer, from]) => - succeeded(answer) ? collect(from, answer.body).filter(available) : [], + succeeded(answer) + ? collect(answeredFrom(from, answer), answer.body).filter(available) + : [], }), ), ); diff --git a/src/internal/conformance/pagination.ts b/src/internal/conformance/pagination.ts index b190305e..5d77baef 100644 --- a/src/internal/conformance/pagination.ts +++ b/src/internal/conformance/pagination.ts @@ -46,6 +46,7 @@ import { withQuery, } from "./core.js"; import { + answeredFrom, budgeted, counted, type Io, @@ -120,7 +121,7 @@ const pageOf = (target: Target, observation: Observation): Option.Option = const data = isRecord(observation.body) ? observation.body["data"] : undefined; return succeeded(observation) && Array.isArray(data) ? Option.some({ - ...target, + ...answeredFrom(target, observation), observation, items: data.length, members: Arr.filterMap(data, (item) => @@ -410,7 +411,9 @@ const unfinishedOf = (end: End, pages: ReadonlyArray): Option.Option Option.some( - `${on(from)} got ${statusOf(observation)}, so the walk could not be finished — ${SAYS_NOTHING}`, + Option.isSome(observation.unfollowed) + ? `${on(from)} answered ${statusOf(observation)}, so the walk could not be finished` + : `${on(from)} got ${statusOf(observation)}, so the walk could not be finished — ${SAYS_NOTHING}`, ), Opaque: ({ from, items }) => Option.some( @@ -865,6 +868,9 @@ const declaresSize = (endpoint: Discovered): boolean => */ export const linksEnumerateCollection: RuleImpl = { rule, + // A page a redirect the kit does not follow answers leaves its walk + // unfinished, naming the redirect, not dropped from the rule. + ownsRedirects: true, run: (ctx) => Effect.gen(function* () { const { resolved, unresolved } = probeable( diff --git a/src/internal/conformance/spec.ts b/src/internal/conformance/spec.ts index c2457b08..972bb858 100644 --- a/src/internal/conformance/spec.ts +++ b/src/internal/conformance/spec.ts @@ -27,6 +27,7 @@ import { } from "effect"; import * as Linkage from "../linkage.js"; import { MEDIA_TYPE } from "../media.js"; +import { listed } from "./crawl.js"; import { relatedDereferences, relatedMatchesLinkage, resourceSelfDereferences } from "./links.js"; import { linksEnumerateCollection } from "./pagination.js"; import { @@ -70,7 +71,7 @@ import { ownId, pathFor, primaryIdentity, - type Target, + type WriteTarget as Target, targets, undecided, type Verdict, @@ -2018,33 +2019,73 @@ const atomicLidResolution: RuleImpl = { // Reachability // --------------------------------------------------------------------------- +/** + * The one finding for the read endpoints a redirect the kit does not follow + * answered, out of `probed`, or none when no endpoint was. + */ +const redirectedFinding = ( + impl: Rule, + redirected: ReadonlyArray, + probed: number, +): ReadonlyArray => + Arr.match(redirected, { + onEmpty: () => [], + onNonEmpty: ([first, ...rest]) => { + const which = redirected.length === probed ? "every" : `${redirected.length} of ${probed}`; + const them = redirected.length === 1 ? "it" : "them"; + const more = Arr.match(rest, { + onEmpty: () => "", + onNonEmpty: (others) => + `; and ${others.length} more (${listed(others.map(({ probe }) => probe.url))})`, + }); + return [ + finding(impl, { + detail: `${which} read endpoint${probed === 1 ? "" : "s"} the kit probed answered with a redirect it does not follow, so the rules that probe ${them} have no answer to decide on — point \`baseUrl\` at the URL that serves the api`, + expected: + "an answer from the base URL's origin, directly or through redirects that stay on it", + observed: `${first.probe.url}: ${describe(first)}${more}`, + probe: first.probe, + }), + ]; + }, + }); + const reachable: RuleImpl = { rule: rule( "spec/target/reachable", "Conformance preconditions", "introduction", "MUST", - "Every endpoint the kit probes must answer with an HTTP response — a kit cannot report conformance for a target it cannot reach.", + "Every endpoint the kit probes must answer with an HTTP response — a kit cannot report conformance for a target it cannot reach. A redirect is followed only within the base URL's origin, so a read endpoint that redirects anywhere else has not answered.", ), + // A read endpoint a redirect the kit does not follow answers is this rule's + // to report, once, rather than every rule's to be not decided by silently. + ownsRedirects: true, run: (ctx) => Effect.gen(function* () { const { resolved, unresolved } = readable(ctx); if (resolved.length === 0) return skip(reachable.rule, noProbeReason("JSON:API read endpoint", unresolved)); - const findings: Array = []; - for (const { path } of resolved) { - const observation = yield* ctx.request({ url: path, headers: jsonApiAccept }); - if (observation.status === 0) { - findings.push( - finding(reachable.rule, { - detail: `${path} produced no HTTP response`, - expected: "any HTTP response", - observed: describe(observation), - probe: observation.probe, - }), - ); - } - } + const observations = yield* Effect.forEach( + resolved, + ({ path }) => ctx.request({ url: path, headers: jsonApiAccept }), + { concurrency: 1 }, + ); + const redirected = observations.filter(({ unfollowed }) => Option.isSome(unfollowed)); + const lost = observations.filter( + ({ status, unfollowed }) => status === 0 && Option.isNone(unfollowed), + ); + const findings = [ + ...redirectedFinding(reachable.rule, redirected, resolved.length), + ...lost.map((observation) => + finding(reachable.rule, { + detail: `${observation.probe.url} produced no HTTP response`, + expected: "any HTTP response", + observed: describe(observation), + probe: observation.probe, + }), + ), + ]; return settle(reachable.rule, resolved.length, findings, coverageNote(unresolved)); }), }; diff --git a/src/internal/conformance/write.test.ts b/src/internal/conformance/write.test.ts index af484340..e2ace371 100644 --- a/src/internal/conformance/write.test.ts +++ b/src/internal/conformance/write.test.ts @@ -3,6 +3,7 @@ import * as Arr from "effect/Array"; import * as Effect from "effect/Effect"; import * as MutableHashMap from "effect/MutableHashMap"; import * as MutableHashSet from "effect/MutableHashSet"; +import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { HttpApi } from "effect/http-api"; @@ -68,6 +69,8 @@ const context = (): Core.Context => { contentType: undefined, text: "", transportError: undefined, + redirects: [], + unfollowed: Option.none(), ...serve(probe), })), observed, diff --git a/src/internal/conformance/write.ts b/src/internal/conformance/write.ts index ccc150a6..6b4c6028 100644 --- a/src/internal/conformance/write.ts +++ b/src/internal/conformance/write.ts @@ -53,6 +53,7 @@ import { type Rule, settle, skip, + statusOf, type WriteRecord, } from "./core.js"; @@ -79,7 +80,7 @@ type Patch = Omit; * * @internal */ -export interface Target { +export interface WriteTarget { /** The `writes` key — the create endpoint's first literal path segment. */ readonly key: string; readonly create: () => Payload; @@ -89,6 +90,9 @@ export interface Target { readonly endpoint: Discovered; } +/** A {@link WriteTarget}, as this module names it. */ +type Target = WriteTarget; + /** @internal */ export interface Targets { readonly targets: ReadonlyArray; @@ -614,7 +618,7 @@ export const accepted = (target: Target, created: Created): Result.Result Result.succeed({ payload, observation, entry }), onNone: () => Result.fail( - `the server did not accept writes["${target.key}"].create (${observation.status}${ + `the server did not accept writes["${target.key}"].create (${statusOf(observation)}${ observation.text === "" ? "" : ` — ${observation.text.slice(0, 160)}` }) — a write rule needs a payload the server accepts`, ), From 0795fef0abbd59bd5616f76c5848c030bd6bb317 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 23:55:40 +0000 Subject: [PATCH 2/2] fix(conformance): skip a rule a redirect off the origin left undecided; close #333 review items Owner decision on #333 (Q4): a rule some of whose requests were answered by a redirect the kit does not follow is Skipped, naming the redirects and keeping its own note, unless a finding on an answered request stands. It is never passed on the answers it did read alone. Q1-Q3 keep their defaults. - undecidedByRedirects skips instead of passing with a note; comments the Errored pass-through. - A 301/302/303 is followed only for a GET (the kit sends no HEAD). - An empty Location answers as itself, as a missing one does. - write.ts drops its local Target alias for WriteTarget. - Tests: DELETE-only and query-only redirects skip delete-response and include-unsupported-endpoint; error-document-shape still fails on a read 404 beside a redirected ?unknown=1; a partly redirected target pins reachable's "4 of 6" finding and the skip reason's truncation and note; 303 followed for GET, refused for POST/PATCH; a two-hop relative link; {type:1} is no resource object; a pagination walk passes beside an off-origin collection. - Changesets and docs/conformance.md describe the skip. Refs #168 Claude-Session: https://claude.ai/code/session_0187g2QpzaHqEzX8GJxiJBVc Co-Authored-By: Claude --- .changeset/conformance-link-followup.md | 2 +- .../conformance-same-origin-redirects.md | 4 +- docs/conformance.md | 4 +- src/Conformance.test.ts | 151 +++++++++++++++++- src/internal/conformance/core.test.ts | 31 +++- src/internal/conformance/core.ts | 51 +++--- src/internal/conformance/write.ts | 33 ++-- 7 files changed, 221 insertions(+), 55 deletions(-) diff --git a/.changeset/conformance-link-followup.md b/.changeset/conformance-link-followup.md index 4b4824f1..76f81722 100644 --- a/.changeset/conformance-link-followup.md +++ b/.changeset/conformance-link-followup.md @@ -11,4 +11,4 @@ The link dereferencing rules (#168) are refined after review: - A read endpoint the request budget left unsearched now makes the rule `Skipped`, naming the budget, as a link left unfollowed already did; it could pass. - A link whose scheme has no origin (`javascript:`) is named by its scheme, not as "another origin, null". -Every `Conformance` probe, over either transport, now keeps a redirect off the transport: `verifyWith` provides `FetchHttpClient.RequestInit` with `redirect: "manual"` (keeping the rest of the run's `RequestInit`), so the transport cannot be led to another origin; which redirects the kit follows itself is described below. An answer a transport fetched from another origin all the same is not read; it is recorded as a lost response. `Conformance.verify`'s in-process transport now answers only the router's `RouteNotFound` as a 404; any other router failure dies again, as before #168. +Every `Conformance` probe, over either transport, now keeps a redirect off the transport: `verifyWith` provides `FetchHttpClient.RequestInit` with `redirect: "manual"` (keeping the rest of the run's `RequestInit`), so the transport cannot be led to another origin; which redirects the kit follows itself is described in this release's entry on following redirects within the base URL's origin ("`Conformance` now follows a redirect when, and only when, its `Location` stays on the base URL's origin"). An answer a transport fetched from another origin all the same is not read; it is recorded as a lost response. `Conformance.verify`'s in-process transport now answers only the router's `RouteNotFound` as a 404; any other router failure dies again, as before #168. diff --git a/.changeset/conformance-same-origin-redirects.md b/.changeset/conformance-same-origin-redirects.md index 26933fd6..f5954079 100644 --- a/.changeset/conformance-same-origin-redirects.md +++ b/.changeset/conformance-same-origin-redirects.md @@ -2,9 +2,9 @@ "@thomasfosterau/effect-jsonapi": patch --- -`Conformance` now follows a redirect when, and only when, its `Location` stays on the base URL's origin (scheme, host and port), in both transports. Previously every `3xx` answered a probe as itself. The kit checks each hop before requesting it, so it never sends a request to another origin on a server's say-so. It follows at most five hops for one request, each counting against a rule's request budget, and grades the final answer. A `301`, `302` or `303` is followed only for a `GET` or `HEAD`; a `307` or `308` re-sends the same method and body. +`Conformance` now follows a redirect when, and only when, its `Location` stays on the base URL's origin (scheme, host and port), in both transports. Previously every `3xx` answered a probe as itself. The kit checks each hop before requesting it, so it never sends a request to another origin on a server's say-so. It follows at most five hops for one request, each counting against a rule's request budget, and grades the final answer. A `301`, `302` or `303` is followed only for a `GET`; a `307` or `308` re-sends the same method and body. A `3xx` with no `Location`, or an empty one, answers as itself. -A redirect the kit does not follow leaves the request with no answer to read: one to another origin, past the hop cap or the budget, one that would turn a write into a `GET`, or one whose `Location` does not parse. An `http` → `https` redirect on the same host counts as another origin. A link it leads to is not decided, and the note names the `Location`. Any other rule drops a finding such a request produced, so it never reports a probe that went unanswered as "not rejected". It then passes on the answers it did read, noting the rest, or skips when it read none. `spec/target/reachable` reports such a redirect once instead, as one finding telling the caller to point `baseUrl` at the URL that serves. +A redirect the kit does not follow leaves the request with no answer to read: one to another origin, past the hop cap or the budget, one that would turn a write into a `GET`, or one whose `Location` does not parse. An `http` → `https` redirect on the same host counts as another origin. A link it leads to is not decided, and the note names the `Location`. Any other rule drops a finding such a request produced, so it never reports a probe that went unanswered as "not rejected"; a finding on an answer it did read still fails the rule. Otherwise the rule is `Skipped`, naming the redirects and keeping its own note. It is never passed on the answers it did read alone. `spec/target/reachable` reports such a redirect once instead, as one finding telling the caller to point `baseUrl` at the URL that serves. `spec/links/related-dereferences` now requires each resource object in the answer to carry a string `type`, so `{"data":"x"}`, `{"data":["x"]}` and `{"data":[{"id":"1"}]}` are findings. The link rules' budget skip no longer counts a read endpoint whose URL does not resolve as searched. A write rule that could not read the create's answer now names it, rather than a bare `0`. diff --git a/docs/conformance.md b/docs/conformance.md index fb440c8b..da7da28a 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -45,7 +45,7 @@ This is not an either/or, and it should not be two kits. In-process is the default because it is deterministic, fast (~100–200 requests in well under a second) and needs no fixture beyond sample ids. It still exercises request decoding, routing, middleware, the handler and response encoding — the whole pipeline the rules care about. A request no route serves — which a link the server emitted can lead to — is answered as a deployed server answers it (`HttpServerError.causeResponse` on the router's `RouteNotFound`: an empty 404), not turned into a defect that would make the rule that sent it `Errored` ([#168](https://github.com/thomasfosterau/effect-jsonapi/issues/168)). Only `RouteNotFound` is answered so: any other failure of the router, like any defect, still dies, as a transport that throws does, because what a deployed server would answer to it is not known. `verifyWith` takes `FetchHttpClient` and runs the same rules against a deployed server, for the things only a real deployment has: a reverse proxy rewriting `Content-Type`, a CDN, a gateway that normalises headers. -**A redirect is followed only within the base URL's origin** (owner decision on [#168](https://github.com/thomasfosterau/effect-jsonapi/issues/168#issuecomment-6180320627)). The transport itself follows nothing: over the wire the kit provides `FetchHttpClient.RequestInit` with `redirect: "manual"` for its own requests, set over the rest of the `RequestInit` the run's context holds, so a run's own `redirect: "follow"` cannot undo it. The kit then follows a redirect itself, in both transports, after checking where its `Location` leads: only to the base URL's origin — scheme, host and port, so an `http` → `https` redirect on the same host is to another origin — and so no request is ever sent to another origin on a server's say-so. A `301`, `302` or `303` is followed only for a `GET` (or `HEAD`), since `fetch` would turn any other method into a `GET`; a `307` or `308` re-sends the same method and body. At most five hops are followed for one request, each a request of its own that counts against a rule's request budget, and the final answer is what the rule grades. A `3xx` with no `Location` answers as itself. A redirect the kit does not follow — to another origin, past the cap or the budget, turning a write into a `GET`, or to a `Location` that does not parse — leaves the request with no answer to read, and the note names the `Location`. A link the kit follows is then not decided (§3). Any other rule drops a finding such a request produced, so a probe that was never answered is never reported "not rejected"; with no finding left, the rule passes on the answers it did read, noting the rest, or skips when it read none. `spec/target/reachable` reports it once instead: a read endpoint that answers with a redirect the kit does not follow is a finding there, telling the caller to point `baseUrl` at the URL that serves. Two limits remain. A transport that follows redirects on its own, outside `fetch`'s `RequestInit` (one wrapped in `HttpClient.followRedirects`, say), still sends the request; the kit then refuses to read an answer whose URL is on another origin and records it as a lost response, naming the origin, but the request has been made, so hand `verifyWith` a client that does not follow redirects. And a `RequestInit` given only to the client's own layer (`FetchHttpClient.layer.pipe(Layer.provide(…))`) is replaced for the kit's requests, since the kit's takes precedence there; provide it to the run instead. +**A redirect is followed only within the base URL's origin** (owner decision on [#168](https://github.com/thomasfosterau/effect-jsonapi/issues/168#issuecomment-6180320627)). The transport itself follows nothing: over the wire the kit provides `FetchHttpClient.RequestInit` with `redirect: "manual"` for its own requests, set over the rest of the `RequestInit` the run's context holds, so a run's own `redirect: "follow"` cannot undo it. The kit then follows a redirect itself, in both transports, after checking where its `Location` leads: only to the base URL's origin — scheme, host and port, so an `http` → `https` redirect on the same host is to another origin — and so no request is ever sent to another origin on a server's say-so. A `301`, `302` or `303` is followed only for a `GET`, since `fetch` would turn any other method into a `GET`; a `307` or `308` re-sends the same method and body. At most five hops are followed for one request, each a request of its own that counts against a rule's request budget, and the final answer is what the rule grades. A `3xx` with no `Location`, or an empty one, answers as itself. A redirect the kit does not follow — to another origin, past the cap or the budget, turning a write into a `GET`, or to a `Location` that does not parse — leaves the request with no answer to read, and the note names the `Location`. A link the kit follows is then not decided (§3). Any other rule drops a finding such a request produced, so a probe that was never answered is never reported "not rejected", while a finding on an answer the kit did read still fails the rule. Otherwise the rule is `Skipped`, naming the redirects (the first three in full, the rest counted) and keeping the rule's own note: never a partial pass on the answers it did read, and no rule opts out (owner decision on [#333](https://github.com/thomasfosterau/effect-jsonapi/pull/333#issuecomment-6181006987)). The link rules and the pagination walk decide for themselves instead, leaving each such link or collection not decided while the rest are graded. `spec/target/reachable` reports it once instead: a read endpoint that answers with a redirect the kit does not follow is a finding there, telling the caller to point `baseUrl` at the URL that serves. Two limits remain. A transport that follows redirects on its own, outside `fetch`'s `RequestInit` (one wrapped in `HttpClient.followRedirects`, say), still sends the request; the kit then refuses to read an answer whose URL is on another origin and records it as a lost response, naming the origin, but the request has been made, so hand `verifyWith` a client that does not follow redirects. And a `RequestInit` given only to the client's own layer (`FetchHttpClient.layer.pipe(Layer.provide(…))`) is replaced for the kit's requests, since the kit's takes precedence there; provide it to the run instead. ### 1.3 The fixture contract @@ -316,7 +316,7 @@ A kit that fails everything catches every bug and is worthless. The control — **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. -**A target behind redirects** reuses the write fixture's server, every rule run with writes on, behind a transport that redirects every request ([#168](https://github.com/thomasfosterau/effect-jsonapi/issues/168)). When each redirect stays on the run's origin (a `308` to the same path under `/live`), every rule's outcome — verdict, findings, note and reason — is the same as against the server directly; only the request counts differ. When each leads off it (a `302` to another host, or to the same host over `https`), no request is sent there, `spec/target/reachable` fails with one finding naming the `Location` and telling the caller to point `baseUrl` at the URL that serves, no other rule fails or passes, and a create the kit could not read is named by its redirect. `src/internal/conformance/core.test.ts` pins the runner and the budget: a `307` re-sends a `POST` and its body, a `302` does not turn it into a `GET`, a `3xx` without `Location` answers as itself, a `Location` that does not parse or has no origin is not followed, and each hop is a request, a chain the budget cannot finish answering nothing. +**A target behind redirects** reuses the write fixture's server, every rule run with writes on, behind a transport that redirects every request ([#168](https://github.com/thomasfosterau/effect-jsonapi/issues/168)). When each redirect stays on the run's origin (a `308` to the same path under `/live`), every rule's outcome — verdict, findings, note and reason — is the same as against the server directly; only the request counts differ. When each leads off it (a `302` to another host, or to the same host over `https`), no request is sent there, `spec/target/reachable` fails with one finding naming the `Location` and telling the caller to point `baseUrl` at the URL that serves, no other rule fails or passes, and a create the kit could not read is named by its redirect. When only some requests leave the origin, a rule that sent one is skipped rather than passed on the rest: only the `DELETE` redirected skips `spec/status/delete-response`, and only the requests carrying a query string skips `spec/query/include-unsupported-endpoint`, while a 404 that is no error document still fails `spec/errors/error-document-shape` beside a redirected `?unknown=1`. Against six list endpoints, four of them redirected off the origin, `spec/target/reachable` names "4 of 6 read endpoints", and `spec/content-negotiation/response-media-type` skips naming three redirects, counting the fourth, and keeping its coverage note. `src/internal/conformance/core.test.ts` pins the runner and the budget: a `307` re-sends a `POST` and its body, a `302` or `303` does not turn a `POST` or `PATCH` into a `GET` but is followed for a `GET`, a `3xx` without a `Location`, or with an empty one, answers as itself, a `Location` that does not parse or has no origin is not followed, and each hop is a request, a chain the budget cannot finish answering nothing. **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 4168f90b..cf84e29c 100644 --- a/src/Conformance.test.ts +++ b/src/Conformance.test.ts @@ -194,6 +194,10 @@ const withoutQuery = (request: R): R => ({ path: request.path.replace(/\?.*$/, ""), }); +/** A note naming a `302` to `https://elsewhere.test` + `path`, which the kit does not follow. */ +const offsite = (path: string) => + `a 302 redirect to https://elsewhere.test${path}, which the kit does not follow: https://elsewhere.test is another origin than the base URL's, http://fixture.test — the kit follows a redirect only within the base URL's origin, and a change of scheme or port is a change of origin`; + /** * A correct-enough server: negotiates per §5, answers well-formed documents, * projects sparse fieldsets, rejects unknown query parameters and absent ids. @@ -1877,6 +1881,72 @@ describe("Conformance: the write fixture", () => { }, ); + /** + * A transport in front of the server that answers each request `moved` + * picks with a `302` to the same path on another origin, and passes the rest + * to the server. + */ + const redirectingSome = + (moved: (request: HttpClientRequest.HttpClientRequest, url: URL) => boolean) => + (canned: HttpClient.HttpClient) => + HttpClient.make((request, url) => + moved(request, url) + ? Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(null, { + status: 302, + headers: { location: `https://elsewhere.test${url.pathname}${url.search}` }, + }), + ), + ) + : canned.execute(request), + ); + + it("skips a rule some of whose requests were redirected off the origin, rather than passing it on the rest", async () => { + // Only the DELETE leaves: the create before it was answered, the delete was not. + const deletes = await run(undefined, undefined, { + client: redirectingSome((request) => request.method === "DELETE"), + }); + expect(outcomeFor(deletes.report, "spec/status/delete-response")).toMatchObject({ + _tag: "Skipped", + reason: expect.stringMatching( + /^not decided: 1 of 2 requests the rule sent were answered by a redirect the kit does not follow \(DELETE \/articles\/\d+ answered a 302 redirect to https:\/\/elsewhere\.test\/articles\/\d+, which the kit does not follow: .*\), and a rule is not passed on the answers it did read alone$/, + ), + }); + // Only the requests that carry a query leave: the baseline was answered, + // the `include` probe was not. + const queries = await run(undefined, undefined, { + client: redirectingSome((_, url) => url.search !== ""), + }); + expect(outcomeFor(queries.report, "spec/query/include-unsupported-endpoint")).toEqual({ + _tag: "Skipped", + rule: expect.anything(), + reason: `not decided: 1 of 2 requests the rule sent were answered by a redirect the kit does not follow (GET /articles/1?include=author answered ${offsite("/articles/1?include=author")}), and a rule is not passed on the answers it did read alone`, + }); + }); + + it("still fails a rule on a finding from an answer it read, beside a request redirected off the origin", async () => { + // The absent id's 404 is no error document; `?unknown=1` is redirected away. + const { report } = await run( + (canned, request) => + request.method === "GET" && canned.status === 404 && request.path.startsWith("/articles/") + ? { ...canned, body: { errors: "not an array" } } + : canned, + undefined, + { client: redirectingSome((_, url) => url.searchParams.has("unknown")) }, + ); + expect(outcomeFor(report, "spec/errors/error-document-shape")).toMatchObject({ + _tag: "Failed", + findings: [ + { + detail: "a 404 response was not a JSON:API error document", + observed: expect.stringContaining('{"errors":"not an array"}'), + }, + ], + }); + }); + it("runs every write rule against a conformant server, on targets it created", async () => { const { report, store, writes } = await run(); expect(failed(report)).toEqual([]); @@ -2913,9 +2983,9 @@ describe("Conformance: pagination links enumerate the collection", () => { readonly last?: LinkValue; } - /** The offset pager's links, as `Handlers.offsetPaginationLinks` spells them. */ - const offsetLinks = ({ offset, limit, total }: Window): Links => { - const at = (start: number) => `/tags?page[offset]=${start}&page[limit]=${limit}`; + /** The offset pager's links on `path`, as `Handlers.offsetPaginationLinks` spells them. */ + const offsetLinks = ({ offset, limit, total }: Window, path = "/tags"): Links => { + const at = (start: number) => `${path}?page[offset]=${start}&page[limit]=${limit}`; return { first: at(0), prev: offset > 0 ? at(Math.max(offset - limit, 0)) : null, @@ -3281,6 +3351,32 @@ describe("Conformance: pagination links enumerate the collection", () => { ); }); + it("passes on a collection it walked beside one a redirect off the origin left unfinished, noting it", async () => { + // `/cats` pages as `/tags` does, and walks; `/tags` page 2 leaves the origin. + const Cat = Resource.make("cats", { attributes: { name: Schema.String } }); + const twoApi = HttpApi.make("paged").add( + Group.make(Tag, Endpoint.list(Tag, { page: Query.Page.Offset })), + Group.make(Cat, Endpoint.list(Cat, { page: Query.Page.Offset })), + ); + const serve = (request: CannedRequest): Canned => { + if (request.path.startsWith("/cats")) { + return offsetPager({ links: (window) => offsetLinks(window, "/cats") })({ + ...request, + path: request.path.replace(/^\/cats/, "/tags"), + }); + } + return queryOf(request).get("page[offset]") === "3" + ? { status: 302, headers: { location: "https://elsewhere.test/tags?page[offset]=3" } } + : offsetPager()(request); + }; + // The walk owns its redirects: the rule is not skipped for the one it + // could not follow, as a rule that does not would be. + expect(outcomeFor(await verifyPaged(serve, twoApi), RULE)).toMatchObject({ + _tag: "Passed", + note: "1 collection not decided: /tags: `next` on page 1 (/tags?page[limit]=3) answered a 302 redirect to https://elsewhere.test/tags?page[offset]=3, which the kit does not follow: https://elsewhere.test is another origin than the base URL's, http://fixture.test — the kit follows a redirect only within the base URL's origin, and a change of scheme or port is a change of origin, so the walk could not be finished", + }); + }); + it("does not hold a lost response mid-walk against `next`", async () => { const report = await verifyOver(offsetApi)(offsetPager(), { only: [RULE] }, (client) => HttpClient.make((request) => @@ -4610,11 +4706,14 @@ describe("Conformance: `self` and `related` links dereference", () => { }); it("resolves a relative link in a redirected answer against where the answer came from", async () => { - // `/articles` redirects to `/v2/articles`, whose `self` links are - // relative: `articles/1` resolves to `/v2/articles/1`, not `/articles/1`. + // `/articles` redirects to `/v1/articles`, which redirects to + // `/v2/articles`, whose `self` links are relative: `articles/1` resolves + // against the last hop, `/v2/articles/1` — not the first hop's + // `/v1/articles/1`, nor the requested `/articles/1`. const v2 = (request: CannedRequest): Canned => { const path = withoutQuery(request).path; - if (path === "/articles") return { status: 308, headers: { location: "/v2/articles" } }; + if (path === "/articles") return { status: 308, headers: { location: "/v1/articles" } }; + if (path === "/v1/articles") return { status: 308, headers: { location: "/v2/articles" } }; if (path === "/v2/articles") { return { body: { data: [{ type: "articles", id: "1", links: { self: "articles/1" } }] } }; } @@ -4636,6 +4735,10 @@ describe("Conformance: `self` and `related` links dereference", () => { expect(await failureOf(RELATED, answering([{ id: "1" }]))).toEqual([ 'the `related` link of articles:2\'s `author` (in /articles, at /data/1) answers no related resource data as primary data | 200 application/vnd.api+json — {"data":[{"id":"1"}]}', ]); + // …and a `type` that is a string, not merely present. + expect(await failureOf(RELATED, answering([{ type: 1, id: "1" }]))).toEqual([ + 'the `related` link of articles:2\'s `author` (in /articles, at /data/1) answers no related resource data as primary data | 200 application/vnd.api+json — {"data":[{"type":1,"id":"1"}]}', + ]); expect(await noteOf(RELATED, answering(null))).toBeUndefined(); }); @@ -4813,3 +4916,39 @@ describe("Conformance: in-process", () => { ); }); }); + +describe("Conformance: a target that redirects some read endpoints off its origin", () => { + // Six list endpoints, `/r0` … `/r3` redirected to another origin, and a + // `get` with no id to probe, which every read rule notes as not probed. + const lists = Arr.makeBy(6, (n) => Resource.make(`r${n}`, { attributes: {} })); + const Unprobed = Resource.make("unprobed", { attributes: {} }); + const partly = HttpApi.make("partly") + .add(...Arr.map(lists, (resource) => Group.make(resource, Endpoint.list(resource)))) + .add(Group.make(Unprobed, Endpoint.get(Unprobed))); + const serve = (request: CannedRequest): Canned => + /^\/r[0-3]$/.test(request.path) + ? { status: 302, headers: { location: `https://elsewhere.test${request.path}` } } + : { body: { data: [] } }; + + it("reports the redirected endpoints once, and skips a rule that read the rest, keeping its note", async () => { + const report = await verifyOver(partly)(serve, { + only: ["spec/target/reachable", "spec/content-negotiation/response-media-type"], + }); + expect(outcomeFor(report, "spec/target/reachable")).toMatchObject({ + _tag: "Failed", + findings: [ + { + detail: + "4 of 6 read endpoints the kit probed answered with a redirect it does not follow, so the rules that probe them have no answer to decide on — point `baseUrl` at the URL that serves the api", + observed: `/r0: ${offsite("/r0")}; and 3 more (/r1, /r2, /r3)`, + }, + ], + }); + // Four redirects named, three of them in full; the rule's own coverage note kept. + expect(outcomeFor(report, "spec/content-negotiation/response-media-type")).toEqual({ + _tag: "Skipped", + rule: expect.anything(), + reason: `not decided: 4 of 6 requests the rule sent were answered by a redirect the kit does not follow (GET /r0 answered ${offsite("/r0")}; GET /r1 answered ${offsite("/r1")}; GET /r2 answered ${offsite("/r2")}; and 1 more), and a rule is not passed on the answers it did read alone; the rule's own note: 1 endpoint not probed: no sample id for "unprobed" — pass ids["unprobed"] or paths["unprobed.get"]`, + }); + }); +}); diff --git a/src/internal/conformance/core.test.ts b/src/internal/conformance/core.test.ts index f2548193..c05546f4 100644 --- a/src/internal/conformance/core.test.ts +++ b/src/internal/conformance/core.test.ts @@ -114,8 +114,35 @@ describe("runner (redirects)", () => { expect((await valueOf(read.request({ url: "/0" }))).status).toBe(200); }); - it("answers a `3xx` without a `Location` as itself", async () => { - const observation = await valueOf(served(() => [302]).request({ url: "/0" })); + it("follows a `303` for a `GET`", async () => { + const read = served(chain(303, 1)); + const answer = await valueOf(read.request({ url: "/0" })); + expect(answer.status).toBe(200); + expect(answer.redirects).toEqual(["http://origin.test/1"]); + expect(read.sent.map(({ method, url }) => `${method} ${url}`)).toEqual([ + "GET http://origin.test/0", + "GET http://origin.test/1", + ]); + }); + + it.each(["POST", "PATCH"])( + "refuses a `303` that would turn a `%s` into a `GET`", + async (method) => { + const write = served(chain(303, 1)); + const refused = await valueOf(write.request({ method, url: "/0", body: { data: 1 } })); + expect(write.sent).toHaveLength(1); + expect(refused.status).toBe(0); + expect(Option.map(refused.unfollowed, ({ reason }) => reason)).toEqual(Option.some("method")); + }, + ); + + it.each([ + ["no", undefined], + ["an empty", ""], + ] as const)("answers a `3xx` with %s `Location` as itself", async (_, location) => { + const target = served(() => (location === undefined ? [302] : [302, location])); + const observation = await valueOf(target.request({ url: "/0" })); + expect(target.sent).toHaveLength(1); expect(observation.status).toBe(302); expect(observation.unfollowed).toEqual(Option.none()); }); diff --git a/src/internal/conformance/core.ts b/src/internal/conformance/core.ts index 78fadce4..27aca594 100644 --- a/src/internal/conformance/core.ts +++ b/src/internal/conformance/core.ts @@ -593,9 +593,13 @@ export const unfollowedNote = ({ status, location, why }: Unfollowed): string => const offsiteWhy = (resolved: URL, origin: string): string => `${resolved.origin === "null" ? `a \`${resolved.protocol}\` URL has no origin` : `${resolved.origin} is another origin than the base URL's, ${origin}`} — the kit follows a redirect only within the base URL's origin, and a change of scheme or port is a change of origin`; -/** `true` when a redirect re-sends the method it answers: `307` and `308` do; the rest turn it into a `GET`. */ +/** + * `true` when following a redirect sends the method it answers: `307` and + * `308` re-send it; the rest turn it into a `GET`, which only a `GET` keeps. + * The kit sends no `HEAD`. + */ const keepsMethod = (status: number, method: string): boolean => - status === 307 || status === 308 || method === "GET" || method === "HEAD"; + status === 307 || status === 308 || method === "GET"; /** * Why the kit does not take a hop to `resolved`, the first that applies in @@ -664,9 +668,9 @@ const hopOf = ( * A redirect is followed only when its `Location` stays on the base URL's * origin (owner decision on #168): the kit requests each hop itself, after * checking where it leads, so no request is ever sent to another origin on a - * server's say-so. A `301`, `302` or `303` is followed only for a `GET` or - * `HEAD`, since `fetch` would turn any other method into a `GET`; a `307` or - * `308` re-sends the same method and body. At most {@link HOP_CAP} hops are + * server's say-so. A `301`, `302` or `303` is followed only for a `GET`, + * since `fetch` would turn any other method into a `GET`; a `307` or `308` + * re-sends the same method and body. At most {@link HOP_CAP} hops are * followed, and no more than `requests` allows, the first request included. * The final answer is the observation, with the hops in `redirects`. A redirect * the kit does not follow leaves the probe with no answer to read: `status: 0`, @@ -709,7 +713,8 @@ export const runner = ); } const location = response.headers["location"]; - if (!REDIRECTS.includes(response.status) || location === undefined) { + // An empty `Location` names nothing to follow, as a missing one does. + if (!REDIRECTS.includes(response.status) || location === undefined || location === "") { return yield* answerOf(record, response, redirects); } const hop = hopOf({ status: response.status, location }, sent, origin, { @@ -914,12 +919,12 @@ const REASON_LIMIT = 3; /** * A rule's outcome once the requests a redirect the kit did not follow * answered are taken out of it: such a request has no answer to read, so it - * decides nothing — not a "was not rejected", and not a pass. A finding it - * produced is dropped; any other finding still fails the rule. With none left, - * a rule that read some other answer passes, noting each request it could not - * decide; one that read none skips, naming the redirects — which, when every - * request was redirected off the base URL's origin, is a `baseUrl` that does - * not serve (`spec/target/reachable` says so). + * decides nothing — not a "was not rejected", and not a pass (owner decision + * on #333). A finding it produced is dropped; a finding on an answer the kit + * did read still fails the rule. With none left, the rule is skipped, naming + * the redirects and keeping its own note: never a partial pass on the answers + * it did read. When every request was redirected off the base URL's origin, + * `baseUrl` does not serve the api, which `spec/target/reachable` says. * * @internal */ @@ -928,6 +933,8 @@ export const undecidedByRedirects = ( sent: ReadonlyArray, ): Outcome => { const unread = sent.filter(({ unfollowed }) => Option.isSome(unfollowed)); + // A rule's `run` never returns `Errored` itself — `runRule` makes one from a + // defect, after this — but `Outcome` admits it, and it is kept as it is. if ( Arr.isReadonlyArrayEmpty(unread) || Predicate.isTagged(outcome, "Skipped") || @@ -938,19 +945,15 @@ export const undecidedByRedirects = ( const stands = failedOnRead(outcome, unread); if (Option.isSome(stands)) return stands.value; const named = redirectsNamed(unread); - if (unread.length === sent.length) { - return skip( - outcome.rule, - `no answer to decide on: every request the rule sent was answered by a redirect the kit does not follow (${named})`, - ); - } - const note = `${unread.length} of ${sent.length} requests not decided, each answered by a redirect the kit does not follow (${named})`; - return pass( - outcome.rule, - outcome.probes, + const own = Predicate.isTagged(outcome, "Passed") && outcome.note !== undefined - ? `${outcome.note}; ${note}` - : note, + ? `; the rule's own note: ${outcome.note}` + : ""; + return skip( + outcome.rule, + unread.length === sent.length + ? `no answer to decide on: every request the rule sent was answered by a redirect the kit does not follow (${named})${own}` + : `not decided: ${unread.length} of ${sent.length} requests the rule sent were answered by a redirect the kit does not follow (${named}), and a rule is not passed on the answers it did read alone${own}`, ); }; diff --git a/src/internal/conformance/write.ts b/src/internal/conformance/write.ts index 6b4c6028..c8f6ab56 100644 --- a/src/internal/conformance/write.ts +++ b/src/internal/conformance/write.ts @@ -90,12 +90,9 @@ export interface WriteTarget { readonly endpoint: Discovered; } -/** A {@link WriteTarget}, as this module names it. */ -type Target = WriteTarget; - /** @internal */ export interface Targets { - readonly targets: ReadonlyArray; + readonly targets: ReadonlyArray; /** Why each other candidate endpoint could not be driven — names the missing option. */ readonly missing: ReadonlyArray; /** The candidate endpoints considered, so "none in this api" reads apart from "none usable". */ @@ -154,7 +151,7 @@ const usable = ( ctx: Context, role: WriteRole, endpoint: Discovered, -): Result.Result => +): Result.Result => Result.gen(function* () { const noCreate = `${endpoint.method} ${endpoint.path} has no create endpoint to make a disposable target with`; const key = yield* Result.fromOption(Option.fromUndefinedOr(endpoint.segment), () => noCreate); @@ -198,7 +195,7 @@ export const targets = (ctx: Context, role: WriteRole): Targets => { export const atomicTargets = (ctx: Context, operations: Discovered): Targets => { const found = Arr.filterMap(Arr.fromRecord(ctx.options.writes), ([key, fixture]) => usableFixture(key, fixture).pipe( - Result.map((fields): Target => ({ + Result.map((fields): WriteTarget => ({ key, ...fields, createPath: operations.path, @@ -314,7 +311,7 @@ export interface Via { readonly identify: (observation: Observation) => Option.Option; } -const build = (target: Target): Result.Result => +const build = (target: WriteTarget): Result.Result => Result.try({ try: target.create, catch: (error) => `writes["${target.key}"].create threw: ${renderThrown(error)}`, @@ -325,7 +322,7 @@ const build = (target: Target): Result.Result => * * @internal */ -export const buildUpdate = (target: Target): Result.Result => +export const buildUpdate = (target: WriteTarget): Result.Result => Option.match(target.update, { onNone: () => Result.fail(`no update fixture for "${target.key}" — pass writes["${target.key}"].update`), @@ -382,7 +379,7 @@ const isOwnSegment = (id: string): boolean => */ const vet = ( ctx: Context, - target: Target, + target: WriteTarget, payload: Payload, named: Identity, ): Result.Result => { @@ -420,7 +417,7 @@ const vet = ( const record = ( ctx: Context, rule: Rule, - target: Target, + target: WriteTarget, payload: Payload, named: Option.Option, ): Entry => { @@ -477,7 +474,7 @@ const runCleanup = ( ); /** Disposes of one ledger entry, unless it has no id the kit may act on or is already gone. */ -const disposeEntry = (target: Target, entry: Entry): Effect.Effect => { +const disposeEntry = (target: WriteTarget, entry: Entry): Effect.Effect => { const id = entry.id; if (id === undefined || entry.disposal !== "left") return Effect.void; return Option.match(target.cleanup, { @@ -495,7 +492,7 @@ const disposeEntry = (target: Target, entry: Entry): Effect.Effect => { * propagated — whatever it fails with, since {@link renderThrown} is total — * so one bad cleanup cannot cost the rest of the run its report. */ -const dispose = (target: Target, created: Created): Effect.Effect => +const dispose = (target: WriteTarget, created: Created): Effect.Effect => Created.$match(created, { Unbuilt: () => Effect.void, Sent: ({ entry }) => @@ -509,7 +506,7 @@ const isSuccessful = (observation: Observation): boolean => observation.status >= 200 && observation.status < 300; /** Builds the fixture's payload and sends it; a non-2xx answer is taken to have created nothing. */ -const create = (ctx: Context, rule: Rule, target: Target, via: Via): Effect.Effect => +const create = (ctx: Context, rule: Rule, target: WriteTarget, via: Via): Effect.Effect => Result.match(build(target), { onFailure: (reason) => Effect.succeed(Created.Unbuilt({ reason })), onSuccess: (payload) => @@ -540,7 +537,7 @@ const create = (ctx: Context, rule: Rule, target: Target, via: Via): Effect.Effe export const withCreated = ( ctx: Context, rule: Rule, - target: Target, + target: WriteTarget, via: Via, use: (created: Created) => Effect.Effect, ): Effect.Effect => @@ -554,7 +551,7 @@ export const withCreated = ( * * @internal */ -export const viaCreateEndpoint = (ctx: Context, target: Target): Via => ({ +export const viaCreateEndpoint = (ctx: Context, target: WriteTarget): Via => ({ send: (payload) => ctx.request({ method: "POST", @@ -610,7 +607,7 @@ export interface Accepted { * * @internal */ -export const accepted = (target: Target, created: Created): Result.Result => +export const accepted = (target: WriteTarget, created: Created): Result.Result => Created.$match(created, { Unbuilt: ({ reason }) => Result.fail(reason), Sent: ({ payload, observation, entry }) => @@ -644,7 +641,7 @@ export const ownId = (created: Accepted): Result.Result => * @internal */ export const onAccepted = - (target: Target, decide: (created: Accepted) => Effect.Effect) => + (target: WriteTarget, decide: (created: Accepted) => Effect.Effect) => (created: Created): Effect.Effect => Result.match(accepted(target, created), { onFailure: (reason) => Effect.succeed(undecided(reason)), @@ -669,7 +666,7 @@ export const overTargets = ( rule: Rule, found: Targets, what: string, - probe: (target: Target) => Effect.Effect, + probe: (target: WriteTarget) => Effect.Effect, ): Effect.Effect => Effect.gen(function* () { if (!ctx.options.mutating) return skip(rule, MUTATING_SKIP);