diff --git a/sdk/js/src/libp2p-http-abort.test.ts b/sdk/js/src/libp2p-http-abort.test.ts new file mode 100644 index 00000000..769907a3 --- /dev/null +++ b/sdk/js/src/libp2p-http-abort.test.ts @@ -0,0 +1,42 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { Connection } from "@libp2p/interface"; +import { fetchOverStream } from "./libp2p-http.ts"; + +test("an already aborted mesh fetch leaves the connection untouched", async () => { + for (const source of ["options", "request"] as const) { + const reason = new Error("caller cancelled"); + const signal = AbortSignal.abort(reason); + let streams = 0; + const connection = { + remotePeer: "peer", + async newStream() { + streams++; + throw new Error("opened a stream"); + }, + } as unknown as Connection; + const request = new Request( + "http://mesh/mesh/peer/a2a/agent/message", + source === "request" ? { signal } : undefined, + ); + const error = await fetchOverStream( + connection, new Uint8Array(), request, source === "options" ? { signal } : {}, + ).catch((err: unknown) => err); + assert.equal(streams, 0, `${source} signal opened a stream`); + assert.equal(error, reason); + } +}); diff --git a/sdk/js/src/libp2p-http-informational.test.ts b/sdk/js/src/libp2p-http-informational.test.ts new file mode 100644 index 00000000..93b86679 --- /dev/null +++ b/sdk/js/src/libp2p-http-informational.test.ts @@ -0,0 +1,64 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { Connection } from "@libp2p/interface"; +import { HTTPParseError } from "./http1.ts"; +import { fetchOverStream } from "./libp2p-http.ts"; + +// A connection whose one stream answers any request with the given bytes. +function answering(response: string): { connection: Connection; aborted: () => boolean } { + let sent = false; + let aborted = false; + const stream = Object.assign(new EventTarget(), { + send() { return true; }, + pause() {}, + resume() { + if (sent) return; + sent = true; + queueMicrotask(() => stream.dispatchEvent(Object.assign(new Event("message"), { + data: new TextEncoder().encode(response), + }))); + }, + abort() { + aborted = true; + stream.dispatchEvent(new Event("close")); + }, + async close() { stream.dispatchEvent(new Event("close")); }, + }); + const connection = { remotePeer: "peer", async newStream() { return stream; } } as unknown as Connection; + return { connection, aborted: () => aborted }; +} + +const request = () => new Request("http://mesh/mesh/peer/a2a/agent/message"); +const continued = (n: number) => "HTTP/1.1 100 Continue\r\n\r\n".repeat(n); +const final = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"; + +test("a mesh fetch returns the final response after informational responses", { timeout: 5000 }, async () => { + const earlyHints = "HTTP/1.1 103 Early Hints\r\nLink: ; rel=preload\r\n\r\n"; + for (const prefix of ["", earlyHints + continued(1), continued(10)]) { + const { connection } = answering(prefix + final); + const response = await fetchOverStream(connection, new Uint8Array(), request()); + assert.equal(response.status, 200); + assert.equal(await response.text(), "ok"); + assert.equal(response.headers.has("link"), false); + } +}); + +test("a mesh fetch refuses a peer that keeps sending informational responses", { timeout: 5000 }, async () => { + const { connection, aborted } = answering(continued(11) + final); + await assert.rejects(fetchOverStream(connection, new Uint8Array(), request()), HTTPParseError); + assert.equal(aborted(), true, "the stream is aborted"); +}); diff --git a/sdk/js/src/libp2p-http-upload.test.ts b/sdk/js/src/libp2p-http-upload.test.ts new file mode 100644 index 00000000..6f64e5a1 --- /dev/null +++ b/sdk/js/src/libp2p-http-upload.test.ts @@ -0,0 +1,34 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { Connection } from "@libp2p/interface"; +import { fetchOverStream } from "./libp2p-http.ts"; + +test("a mesh fetch releases any stream opened for an unreadable request body", async () => { + let streams = 0; + let aborted = 0; + const stream = Object.assign(new EventTarget(), { + abort() { aborted++; }, + }); + const connection = { + remotePeer: "peer", + async newStream() { streams++; return stream; }, + } as unknown as Connection; + const request = new Request("http://mesh/mesh/peer/a2a/agent/message", { method: "POST", body: "fixture" }); + assert.equal(await request.text(), "fixture"); + await assert.rejects(fetchOverStream(connection, new Uint8Array(), request), TypeError); + assert.equal(streams - aborted, 0, "request body failure leaked the libp2p stream"); +}); diff --git a/sdk/js/src/libp2p-http.ts b/sdk/js/src/libp2p-http.ts index c779878c..0e2be402 100644 --- a/sdk/js/src/libp2p-http.ts +++ b/sdk/js/src/libp2p-http.ts @@ -74,6 +74,12 @@ const MAX_AGENT_CARD_BYTES = 1 << 20; /** Largest request body the ingress reads whole for a handler or url target. */ export const MAX_INGRESS_BODY_BYTES = 8 * 1024 * 1024; const REQUEST_TIMEOUT_MS = 60_000; +/** + * Informational (1xx) heads a mesh fetch reads before the final response. + * A server sends a 100 Continue, a 103 Early Hints, a few 102 Processing; + * a peer that keeps sending them never answers and is cut off. + */ +const MAX_INFORMATIONAL_RESPONSES = 10; /** A fetch-style handler in this process. */ export type HTTPHandler = (request: Request, caller: VerifiedBiscuit) => Promise | Response; @@ -618,6 +624,8 @@ export async function fetchOverStream(conn: Connection, biscuit: Uint8Array, req } async function sendOverStream(conn: Connection, biscuit: Uint8Array, request: Request, options: HTTPStreamOptions): Promise { + options.signal?.throwIfAborted(); + request.signal.throwIfAborted(); const { target } = splitMeshURL(new URL(request.url)); const peerId = conn.remotePeer.toString(); // One controller ends the exchange: the caller's signal at any time, the @@ -641,22 +649,32 @@ async function sendOverStream(conn: Connection, biscuit: Uint8Array, request: Re const abortStream = () => stream.abort(asError(signal.reason)); signal.addEventListener("abort", abortStream, { once: true }); - const headers = new Headers(); - request.headers.forEach((value, name) => { - if (name !== "host" && name !== "content-length" && name !== "transfer-encoding" && name !== HEADER_MESH_BISCUIT && name !== HEADER_PEER_ID) { - headers.set(name, value); - } - }); - headers.set("host", peerId); - headers.set(HEADER_MESH_BISCUIT, toBase64(biscuit)); - const body = request.body === null ? new Uint8Array(0) : new Uint8Array(await request.arrayBuffer()); - headers.set("content-length", String(body.length)); - try { + signal.throwIfAborted(); + const headers = new Headers(); + request.headers.forEach((value, name) => { + if (name !== "host" && name !== "content-length" && name !== "transfer-encoding" && name !== HEADER_MESH_BISCUIT && name !== HEADER_PEER_ID) { + headers.set(name, value); + } + }); + headers.set("host", peerId); + headers.set(HEADER_MESH_BISCUIT, toBase64(biscuit)); + const body = request.body === null ? new Uint8Array(0) : new Uint8Array(await request.arrayBuffer()); + headers.set("content-length", String(body.length)); + signal.throwIfAborted(); await sendAll(stream, encodeRequestHead(request.method, target, headers)); await sendAll(stream, body); const reader = new ByteReader(streamSource(stream)); - const head = await readResponseHead(reader); + let head = await readResponseHead(reader); + for (let informational = 0; head.status >= 100 && head.status < 200; informational++) { + if (head.status === 101) { + throw new HTTPParseError("protocol switching is not supported by mesh fetch"); + } + if (informational === MAX_INFORMATIONAL_RESPONSES) { + throw new HTTPParseError(`peer sent more than ${MAX_INFORMATIONAL_RESPONSES} informational responses`); + } + head = await readResponseHead(reader); + } headersIn = true; signal.throwIfAborted(); const framing = responseBodyFraming(request.method, head);