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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .changeset/conformance-link-followup.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.
11 changes: 11 additions & 0 deletions .changeset/conformance-same-origin-redirects.md
Original file line number Diff line number Diff line change
@@ -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`; 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"; 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`.

`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.
13 changes: 7 additions & 6 deletions docs/conformance.md

Large diffs are not rendered by default.

466 changes: 450 additions & 16 deletions src/Conformance.test.ts

Large diffs are not rendered by default.

25 changes: 17 additions & 8 deletions src/Conformance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
175 changes: 173 additions & 2 deletions src/internal/conformance/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"));

Expand Down Expand Up @@ -37,3 +40,171 @@ describe("answeredAsDeployed (the in-process transport)", () => {
).toEqual([true, true]);
});
});

/** Runs `effect` to its value; a failure or defect fails the test. */
const valueOf = async <A>(effect: Effect.Effect<A>): Promise<A> => {
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<string>;
}

/**
* 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<Sent> = [];
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("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());
});

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);
});
});
Loading
Loading