Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk/js: HEAD keeps the declared length, a cancelled body closes its reader
Antonio Ojea3af528241642
diff --git a/sdk/js/src/authorizer.test.ts b/sdk/js/src/authorizer.test.tsindex 039b7891..b528e1c4 100644--- a/sdk/js/src/authorizer.test.ts+++ b/sdk/js/src/authorizer.test.ts@@ -93,8 +93,11 @@ test("the empty target is the protocol in the system namespace", async () => {await assert.rejects(authorizeCaller(request(token, "mcp://calc"), options([])), AuthorizationError);});-test("a service the role was not granted is denied", async () => {- await assert.rejects(authorizeCaller(request(nodeToken(CALLER), "mcp://other"), options(NODE_ROLE_GRANTS)), AuthorizationError);+test("a service the role was not granted is denied, and the refusal names the check", async () => {+ await assert.rejects(+ authorizeCaller(request(nodeToken(CALLER), "mcp://other"), options(NODE_ROLE_GRANTS)),+ (err: unknown) => err instanceof AuthorizationError && /FailedLogic/.test(err.message) && !/\[object Object\]/.test(err.message),+ );});test("a role with no grants at all is denied", async () => {diff --git a/sdk/js/src/authorizer.ts b/sdk/js/src/authorizer.tsindex d5bf4a36..efe843f3 100644--- a/sdk/js/src/authorizer.ts+++ b/sdk/js/src/authorizer.ts@@ -52,8 +52,16 @@ export class AuthorizationError extends Error {}}+// biscuit-wasm throws plain objects ({ FailedLogic: ... }, { RunLimit: ... }).function describe(err: unknown): string {- return err instanceof Error ? err.message : String(err);+ if (err instanceof Error) {+ return err.message;+ }+ try {+ return JSON.stringify(err);+ } catch {+ return String(err);+ }}function timeFact(now: Date): string {diff --git a/sdk/js/src/http1.test.ts b/sdk/js/src/http1.test.tsindex 68ee6bbb..d0374eae 100644--- a/sdk/js/src/http1.test.ts+++ b/sdk/js/src/http1.test.ts@@ -103,6 +103,18 @@ test("a chunked body is reassembled, extensions and trailers skipped, and stream}assert.deepEqual(pieces, ["hello", " world"]);assert.ok(finished);+ // Cancelling the stream reports the reason once and closes the generator,+ // so nothing is read after the caller has gone.+ const slow = new ByteReader(source("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n", 3));+ await readResponseHead(slow);+ const reasons: (Error | undefined)[] = [];+ const cancelled = bodyStream(slow, { kind: "chunked" }, (err) => reasons.push(err));+ const r = cancelled.getReader();+ assert.ok("hello".startsWith(dec.decode((await r.read()).value)));+ await r.cancel(new Error("gone"));+ assert.equal(reasons.length, 1);+ assert.equal(reasons[0]?.message, "gone");+ assert.deepEqual(await r.read(), { done: true, value: undefined });// Each malformed size line is followed by a body that would otherwise// parse, so only the size check can be what refuses it.for (const bad of ["zz\r\nhello\r\n0\r\n\r\n", "5g\r\nhello\r\n0\r\n\r\n", "5 g\r\nhello\r\n0\r\n\r\n", "-5\r\nhello\r\n0\r\n\r\n", "\r\nhello\r\n0\r\n\r\n", "123456789\r\n0\r\n\r\n"]) {diff --git a/sdk/js/src/http1.ts b/sdk/js/src/http1.tsindex a0519be0..07811e50 100644--- a/sdk/js/src/http1.ts+++ b/sdk/js/src/http1.ts@@ -387,8 +387,10 @@ export function bodyStream(reader: ByteReader, framing: BodyFraming, onDone: (erfinish(e);}},- cancel(reason) {+ async cancel(reason) {+ // The stream is torn down first, so a read the generator is blocked on ends.finish(reason instanceof Error ? reason : new Error(String(reason)));+ await chunks.return(undefined).catch(() => {});},});}diff --git a/sdk/js/src/libp2p-http.test.ts b/sdk/js/src/libp2p-http.test.tsindex aec23b19..0bc05183 100644--- a/sdk/js/src/libp2p-http.test.ts+++ b/sdk/js/src/libp2p-http.test.ts@@ -174,6 +174,10 @@ before(async () => {});return new Response(body, { headers: { "content-type": "text/event-stream" } });}+ if (url.pathname === "/sized") {+ // An agent that declares its length, as a static file server would.+ return new Response(request.method === "HEAD" ? null : "x".repeat(42), { headers: { "content-type": "text/plain", "content-length": "42" } });+ }return Response.json({ path: url.pathname + url.search, method: request.method, peer: request.headers.get("x-peer-id"), biscuit: request.headers.get("x-sam-biscuit"), echo: await request.text() });};await handlerAgent.handle(HTTP_PROTOCOL, httpIngressHandler(a2aEndpoint({ handler }), providerOptions(mint(handlerAgent.peerId.toString(), ROLE_NODE))), {@@ -244,6 +248,20 @@ test("a fetch handler sees the caller and the path, and its streaming body goesassert.equal(res.status, 200);assert.deepEqual(JSON.parse(res.text()), { path: "/tasks?x=1", method: "POST", peer: caller.peerId.toString(), biscuit: null, echo: "hello" });+ // HEAD: the head a GET would get, the declared length kept, no body sent.+ const sized = await httpRequestOverStream(conn, callerBiscuit, "a2a://agent", "/sized");+ assert.equal(sized.text(), "x".repeat(42));+ const head = await httpRequestOverStream(conn, callerBiscuit, "a2a://agent", "/sized", { method: "HEAD" });+ assert.equal(head.status, 200);+ assert.equal(head.headers["content-length"], "42");+ assert.equal(head.headers["content-type"], "text/plain");+ assert.equal(head.body.length, 0);+ // A handler that built a body for HEAD anyway: no length is invented.+ const headJson = await httpRequestOverStream(conn, callerBiscuit, "a2a://agent", "/card", { method: "HEAD" });+ assert.equal(headJson.status, 200);+ assert.equal(headJson.headers["content-length"], undefined);+ assert.equal(headJson.body.length, 0);+const response = await fetchOverStream(conn, callerBiscuit, new Request(meshURL(handlerAgent.peerId.toString(), "a2a://agent", "/stream")));assert.equal(response.status, 200);assert.equal(response.headers.get("content-type"), "text/event-stream");diff --git a/sdk/js/src/libp2p-http.ts b/sdk/js/src/libp2p-http.tsindex ab1672bd..8b544641 100644--- a/sdk/js/src/libp2p-http.ts+++ b/sdk/js/src/libp2p-http.ts@@ -252,7 +252,18 @@ async function writeResponse(stream: Stream, response: Response, headOnly: boole}});headers.set("connection", "close");- const body = headOnly ? null : response.body;+ if (headOnly) {+ // The same head a GET would get (RFC 9110 section 9.3.2): the length the+ // agent declared, if any; the body it may have built is not sent.+ const declared = response.headers.get("content-length");+ if (declared !== null) {+ headers.set("content-length", declared);+ }+ void response.body?.cancel().catch(() => {});+ await sendAll(stream, encodeResponseHead(response.status, response.statusText, headers));+ return;+ }+ const body = response.body;if (body === null) {headers.set("content-length", "0");await sendAll(stream, encodeResponseHead(response.status, response.statusText, headers));@@ -440,7 +451,7 @@ export async function fetchOverStream(conn: Connection, biscuit: Uint8Array, reqreturn new Response(responseBody, { status: head.status, statusText: head.statusText, headers: head.headers });} catch (err) {stream.abort(asError(err));- throw signal.aborted ? signal.reason : err;+ throw signal.aborted ? (signal.reason ?? err) : err;}}