Skip to content
Open
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
42 changes: 42 additions & 0 deletions sdk/js/src/libp2p-http-abort.test.ts
Original file line number Diff line number Diff line change
@@ -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);
}
});
64 changes: 64 additions & 0 deletions sdk/js/src/libp2p-http-informational.test.ts
Original file line number Diff line number Diff line change
@@ -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: </style.css>; 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");
});
34 changes: 34 additions & 0 deletions sdk/js/src/libp2p-http-upload.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
42 changes: 30 additions & 12 deletions sdk/js/src/libp2p-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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> | Response;
Expand Down Expand Up @@ -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<Response> {
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
Expand All @@ -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);
Expand Down
Loading