Skip to content

Commit c07edcb

Browse files
frenzzyryansolid
andauthored
fix(web): fail a call on a response the runtime did not write (#3088)
* fix(web): fail a call on a response the runtime did not write (#3087) Only the protocol's error header and a 5xx counted as failure, so every other non-2xx was decoded as a result — and decoding a login page, or an empty 405, yields nothing. The call resolved to `undefined`, reading as "the function returned nothing" where the request had not reached it. A response at 300 or above carrying neither the error header nor a body format now fails the call with the status on the error. Undecoded, because its body is someone else's; and before the passthrough that control flow uses, because a foreign refusal carries a `Location` of its own often enough — an SSO interstitial is exactly that — that the passthrough would have swallowed it. The runtime never puts a redirect on the wire as a 3xx, so nothing of its own falls in the range. `BodyFormat.Void` marks the one response the runtime encodes without a format to carry, so a void result with a status stays a result, matching what the equivalent bare `Response` already did. * fix(web): leave redirects to the passthrough The check covered 300 and up, on the reasoning that an SSO interstitial answers a refusal with a `Location` of its own. Driving a browser against a real origin says otherwise: `fetch` follows redirects, so the interstitial arrives as its login page at 200, and `redirect: "manual"` yields an opaqueredirect at status 0 — neither is a 3xx by the time the transport sees it. The clause only ever fired server-side, in tests, and on synthesized responses. What it cost there was real: a verbatim `X-Content-Raw` passthrough carrying a `Location` — the documented escape hatch for answering a call with a response of one's own — stopped reaching the caller, and a `live()` source facing a foreign 3xx reconnected forever instead of ending, because the retry classifier reads 4xx as definite and everything else as transient. Back to 400 and up, with the redirect passthrough pinned. * refactor(web): drop two conditions nothing could observe Reverting each part of the rule one at a time found two that no test could watch, because no input reaches them. The error header never appears without a body format: every path that tags a thrown result encodes it too, so testing for both markers asked the same question twice. One marker, and the invariant it rests on, is stated where the check is. The explicit decode case for a void body answered `undefined`, which is what the fallthrough beneath it already answered. The runtime cannot produce a void response carrying a body, so nothing else could reach the case either. --------- Co-authored-by: Ryan Carniato <[email protected]>
1 parent 0043643 commit c07edcb

5 files changed

Lines changed: 318 additions & 1 deletion

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
Fail a server function call on a response the runtime did not write, instead of resolving it to `undefined` (#3087).
6+
7+
Only the protocol's error header and a 5xx counted as failure, so every other non-2xx was decoded as a result — and decoding a login page, or an empty 405, yields nothing. A response at 400 or above carrying no body format now fails the call with the status on the error, undecoded, and before the passthrough control flow uses: a refusal can carry a `Location` of its own, and the passthrough would have handed it back as control flow. Redirects are left alone — `fetch` follows them, so an interstitial arrives as its page at 200, and a 3xx only reaches the transport where something opted out of following one.
8+
9+
`BodyFormat.Void` marks the one response the runtime encodes without a format to carry — a function that returned nothing — so `respond(undefined, { status: 400 })` stays a result alongside `new Response(null, { status: 404 })` and `respond(value, { status: 400 })`. A client that predates the tag decodes it the same way; a client that has it, talking to a server that does not, reads an untagged void 4xx as a refusal.
10+
11+
A 2xx is not judged at all: a login page served at 200 is indistinguishable from a void result by header alone. One runtime-produced shape is caught with the foreign ones — a verbatim `X-Content-Raw` response at a non-2xx status, which an integration's `responseHandler` claims before the check.

‎packages/web/server-functions/src/client.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,16 @@ async function fetchServerFunction(base, id, options, args, meta, callArgs = arg
584584
if (handled !== undefined) return handled;
585585
}
586586

587+
// Every response the runtime encodes carries the body format — a void one
588+
// and a thrown one included — so at 400 and up its absence means the peer
589+
// refused. Answered before the passthrough beneath, because a refusal can
590+
// carry a `Location` of its own and the passthrough would hand it back as
591+
// control flow; and undecoded, because its body is someone else's, not a
592+
// payload for the caller.
593+
if (response.status >= 400 && !response.headers.has(BODY_FORMAT_HEADER)) {
594+
throw serverFunctionFailure(response, undefined);
595+
}
596+
587597
// Proxies may omit the protocol error header on 5xx responses.
588598
const failed = response.headers.has(ERROR_HEADER) || response.status >= 500;
589599

‎packages/web/server-functions/src/server.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1374,6 +1374,7 @@ function encodeResult(value, headers, status, codec, signal) {
13741374
// client load its decode half (see shared.js loadSerializer). Negotiated
13751375
// per response: mixed pages simply carry both formats.
13761376
if (value === undefined) {
1377+
headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
13771378
return new Response(null, { status, headers });
13781379
}
13791380
// By the time a result is being encoded the function has already run —

‎packages/web/server-functions/src/shared.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -539,7 +539,14 @@ export const BodyFormat = {
539539
* legs: argument lists on the request, results (single-flight envelopes
540540
* included) on the response.
541541
*/
542-
Json: "8"
542+
Json: "8",
543+
/**
544+
* No body at all — a function that returned nothing. It marks the response
545+
* as one the runtime encoded, which separates a void result with a status
546+
* on it from a refusal answered by something else. Decoding falls through
547+
* to `undefined`, which is what a peer predating the tag reads too.
548+
*/
549+
Void: "9"
543550
};
544551

545552
// Nesting deeper than this is not JSON-safe. The guard itself walks an
Lines changed: 288 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,288 @@
1+
/**
2+
* What the transport does with a response the runtime did not write (#3087).
3+
*
4+
* Its own responses are recognisable: they carry the error header, or the
5+
* body format every encoding path stamps — a void result included. Anything
6+
* else at 400 and up is the peer refusing, and decoding one yields nothing,
7+
* which used to resolve the call to `undefined`. These pin the refusals that
8+
* now fail, the value-shaped statuses that must not, and the limit of what a
9+
* status can tell you.
10+
*
11+
* Like the extension specs, these run against the built bundles
12+
* (server-functions/dist/*, wired up in vite.config.server.mjs).
13+
*/
14+
import { AsyncLocalStorage } from "node:async_hooks";
15+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
16+
import { redirect, respond } from "@solidjs/web";
17+
import {
18+
handleServerFunctionRequest,
19+
registerServerFunction
20+
} from "@solidjs/web/server-functions/server";
21+
import {
22+
configureServerFunctionsClient,
23+
createServerReference
24+
} from "@solidjs/web/server-functions/client";
25+
26+
const RequestContext = Symbol.for("solid.RequestContext");
27+
28+
beforeAll(() => {
29+
(globalThis as any)[RequestContext] = new AsyncLocalStorage();
30+
});
31+
32+
afterAll(() => {
33+
delete (globalThis as any)[RequestContext];
34+
});
35+
36+
/**
37+
* The transport's fetch. `answer` replaces the handler with a response from
38+
* somewhere else; `rewrite` sends the call to a different address.
39+
*/
40+
function connectTransport({
41+
answer,
42+
rewrite,
43+
method,
44+
site = "same-origin"
45+
}: {
46+
answer?: () => Response;
47+
rewrite?: (address: string) => string;
48+
method?: string;
49+
site?: string;
50+
} = {}) {
51+
const original = globalThis.fetch;
52+
globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
53+
if (answer) return Promise.resolve(answer());
54+
const address = input instanceof Request ? input.url : input.toString();
55+
const request = new Request(new URL(rewrite ? rewrite(address) : address, "http://localhost"), {
56+
...(input instanceof Request ? input : init),
57+
...(method ? { method, body: undefined } : {})
58+
});
59+
request.headers.set("Sec-Fetch-Site", site);
60+
return handleServerFunctionRequest(request);
61+
}) as typeof fetch;
62+
return () => {
63+
globalThis.fetch = original;
64+
};
65+
}
66+
67+
const foreign = (status: number, body: BodyInit | null, type?: string) => () =>
68+
new Response(body, { status, headers: type ? { "content-type": type } : undefined });
69+
70+
describe("server-function transport failures (#3087)", () => {
71+
it("fails the call when the handler refuses it", async () => {
72+
const restore = connectTransport();
73+
try {
74+
// a client that outlived the build registering its function
75+
await expect(createServerReference("fail-never-registered")()).rejects.toMatchObject({
76+
status: 404
77+
});
78+
} finally {
79+
restore();
80+
}
81+
});
82+
83+
it("fails the call when the handler rejects the request itself", async () => {
84+
registerServerFunction("fail-args", async () => "ok");
85+
// something under `args` that is not an argument array: a 400 for every
86+
// caller of that url
87+
const restore = connectTransport({ rewrite: address => `${address}?args=nope` });
88+
try {
89+
await expect(createServerReference("fail-args")()).rejects.toMatchObject({ status: 400 });
90+
} finally {
91+
restore();
92+
}
93+
});
94+
95+
it("fails the call on a response nothing in the runtime wrote", async () => {
96+
registerServerFunction("fail-foreign", async () => "ok");
97+
for (const answer of [
98+
foreign(404, "<h1>Not found</h1>", "text/html"),
99+
foreign(401, "<html>login</html>", "text/html"),
100+
foreign(403, null)
101+
]) {
102+
const restore = connectTransport({ answer });
103+
try {
104+
await expect(createServerReference("fail-foreign")()).rejects.toMatchObject({
105+
status: answer().status
106+
});
107+
} finally {
108+
restore();
109+
}
110+
}
111+
});
112+
113+
it("fails one carrying integration metadata of its own", async () => {
114+
registerServerFunction("fail-interstitial", async () => "ok");
115+
// an SSO interstitial answers 403 with a Location, and a gateway can
116+
// answer 404 with anything — neither is the runtime's control flow, so
117+
// neither may take the passthrough that control flow uses
118+
for (const [status, headers] of [
119+
[403, { "content-type": "text/html", Location: "https://sso.example/login" }],
120+
[404, { "X-Revalidate": "stories" }]
121+
] as const) {
122+
const restore = connectTransport({ answer: () => new Response(null, { status, headers }) });
123+
try {
124+
await expect(createServerReference("fail-interstitial")()).rejects.toMatchObject({
125+
status
126+
});
127+
} finally {
128+
restore();
129+
}
130+
}
131+
});
132+
133+
it("fails with an Error even when the foreign body sniffs as a known encoding", async () => {
134+
registerServerFunction("fail-sniffed", async () => "ok");
135+
// content-type sniffing would decode this as URLSearchParams; a refusal's
136+
// body is not a payload, and a caller reads `.status`, not a form
137+
const restore = connectTransport({
138+
answer: foreign(403, "reason=blocked", "application/x-www-form-urlencoded")
139+
});
140+
try {
141+
await expect(createServerReference("fail-sniffed")()).rejects.toMatchObject({ status: 403 });
142+
await expect(createServerReference("fail-sniffed")()).rejects.toBeInstanceOf(Error);
143+
} finally {
144+
restore();
145+
}
146+
});
147+
148+
it("resolves a value-shaped status the function itself produced", async () => {
149+
registerServerFunction("fail-validated", async () =>
150+
respond({ field: "required" }, { status: 400 })
151+
);
152+
registerServerFunction("fail-void", async () => respond(undefined, { status: 400 }));
153+
registerServerFunction("fail-empty", async () => new Response(null, { status: 404 }));
154+
const restore = connectTransport();
155+
try {
156+
expect(await createServerReference("fail-validated")()).toEqual({ field: "required" });
157+
// nothing, with a status on it — both spellings answer the same way
158+
expect(await createServerReference("fail-void")()).toBeUndefined();
159+
expect(await createServerReference("fail-empty")()).toBeNull();
160+
} finally {
161+
restore();
162+
}
163+
});
164+
165+
it("leaves the runtime's own control flow on its passthrough", async () => {
166+
registerServerFunction("fail-redirect", async () => {
167+
throw redirect("/login");
168+
});
169+
const restore = connectTransport();
170+
try {
171+
const response = await createServerReference("fail-redirect")();
172+
expect(response).toBeInstanceOf(Response);
173+
expect((response as Response).headers.get("Location")).toBe("/login");
174+
} finally {
175+
restore();
176+
}
177+
});
178+
179+
it("leaves a redirect the peer answered with to the passthrough", async () => {
180+
registerServerFunction("fail-3xx", async () => "ok");
181+
// `fetch` follows redirects, so an interstitial arrives as its page at
182+
// 200 and a 3xx only reaches the transport where something opted out of
183+
// following one — control flow the runtime does not produce and the
184+
// caller may still want to read
185+
const restore = connectTransport({
186+
answer: () => new Response(null, { status: 302, headers: { Location: "/login" } })
187+
});
188+
try {
189+
const response = await createServerReference("fail-3xx")();
190+
expect((response as Response).status).toBe(302);
191+
} finally {
192+
restore();
193+
}
194+
});
195+
196+
it("cannot judge a 2xx, and does not try", async () => {
197+
registerServerFunction("fail-spa", async () => "ok");
198+
// a login page or an SPA index served at 200 is indistinguishable from a
199+
// void result by header alone; the status is all this rule reads
200+
const restore = connectTransport({ answer: foreign(200, "<html>login</html>", "text/html") });
201+
try {
202+
expect(await createServerReference("fail-spa")()).toBeUndefined();
203+
} finally {
204+
restore();
205+
}
206+
});
207+
208+
it("fails on the gates that answer without a body", async () => {
209+
registerServerFunction("fail-gated", async () => "ok");
210+
// the method allowlist and the origin gate answer 405 and 403 with
211+
// nothing in the body, which is the shape that used to decode to
212+
// `undefined`
213+
const method = connectTransport({ method: "GET" });
214+
try {
215+
await expect(createServerReference("fail-gated")()).rejects.toMatchObject({ status: 405 });
216+
} finally {
217+
method();
218+
}
219+
const origin = connectTransport({ site: "cross-site" });
220+
try {
221+
await expect(createServerReference("fail-gated")()).rejects.toMatchObject({ status: 403 });
222+
} finally {
223+
origin();
224+
}
225+
});
226+
227+
it("reads a void result the way a peer without the tag wrote it", async () => {
228+
registerServerFunction("fail-untagged", async () => "ok");
229+
// a server built before `BodyFormat.Void`: a void result with a status
230+
// and no format header is indistinguishable from a refusal, and fails
231+
const restore = connectTransport({ answer: () => new Response(null, { status: 400 }) });
232+
try {
233+
await expect(createServerReference("fail-untagged")()).rejects.toMatchObject({ status: 400 });
234+
} finally {
235+
restore();
236+
}
237+
});
238+
239+
it("fails a verbatim passthrough that carries a refusal's status", async () => {
240+
registerServerFunction(
241+
"fail-raw",
242+
async () => new Response("nope", { status: 404, headers: { "X-Content-Raw": "1" } })
243+
);
244+
registerServerFunction(
245+
"fail-raw-ok",
246+
async () => new Response("here", { status: 200, headers: { "X-Content-Raw": "1" } })
247+
);
248+
const restore = connectTransport();
249+
try {
250+
// a raw body is for whoever claims the response; a call site with no
251+
// integration could not read it at either status, and a status beats
252+
// minting `undefined`
253+
await expect(createServerReference("fail-raw")()).rejects.toMatchObject({ status: 404 });
254+
expect(await createServerReference("fail-raw-ok")()).toBeUndefined();
255+
} finally {
256+
restore();
257+
}
258+
});
259+
260+
it("leaves the response to an integration that claims it", async () => {
261+
registerServerFunction(
262+
"fail-claimed",
263+
async () => new Response("frame", { status: 404, headers: { "X-Content-Raw": "1" } })
264+
);
265+
const restore = connectTransport();
266+
configureServerFunctionsClient({
267+
responseHandler: { handle: (response: Response) => response.status }
268+
});
269+
try {
270+
// the seam runs before the check, which is what keeps server
271+
// components free to answer with a status of their own
272+
expect(await createServerReference("fail-claimed")()).toBe(404);
273+
} finally {
274+
configureServerFunctionsClient({ responseHandler: null as any });
275+
restore();
276+
}
277+
});
278+
279+
it("leaves an ordinary call alone", async () => {
280+
registerServerFunction("fail-plain", async (word: string) => word.toUpperCase());
281+
const restore = connectTransport();
282+
try {
283+
expect(await createServerReference("fail-plain")("solid")).toBe("SOLID");
284+
} finally {
285+
restore();
286+
}
287+
});
288+
});

0 commit comments

Comments
 (0)