The Open Framework for Building Agents
fix(eve): follow OpenAPI redirects only within the base URL's origin (#5196)
Ben Pankowcbc87aef4919
diff --git a/.changeset/openapi-same-origin-redirects.md b/.changeset/openapi-same-origin-redirects.mdnew file mode 100644index 000000000..96df93f03--- /dev/null+++ b/.changeset/openapi-same-origin-redirects.md@@ -0,0 +1,5 @@+---+"eve": patch+---++OpenAPI connection tool calls now follow redirects only within the base URL's origin. A redirect to another origin is returned as the tool result, with its target in `location`, instead of followed, so credentials in custom headers, such as an `apiKey` security scheme's header, no longer reach the redirect target. A same-origin redirect loop now fails after 10 hops with an explicit error.diff --git a/docs/connections/openapi.mdx b/docs/connections/openapi.mdxindex 062eab774..cadfe660e 100644--- a/docs/connections/openapi.mdx+++ b/docs/connections/openapi.mdx@@ -39,6 +39,8 @@ Use `baseUrl` when the spec is missing server data, points at the wrong environmThe resolved base URL must use `https` too (loopback hosts may use `http` for local development), since operation calls carry the connection's credentials.+For the same reason, operation calls follow redirects only within the base URL's origin, up to 10 hops; a longer chain fails the call as a redirect loop. A redirect to another origin is not followed. The tool returns the redirect response with its absolute target in `location`, such as `{ status: 302, statusText, body, location: "https://storage.example.com/..." }`, and the connection's credentials never reach the other host. Endpoints that hand downloads off to a storage host return that `location`, which the agent can fetch without the connection's credentials. If an API has moved to a new domain, point `baseUrl` at the new domain.+```ts title="agent/connections/crm.ts"import { defineOpenAPIConnection } from "eve/connections";diff --git a/packages/eve/src/runtime/connections/openapi-client.test.ts b/packages/eve/src/runtime/connections/openapi-client.test.tsindex dfe79b470..7d2d46188 100644--- a/packages/eve/src/runtime/connections/openapi-client.test.ts+++ b/packages/eve/src/runtime/connections/openapi-client.test.ts@@ -443,6 +443,98 @@ describe("OpenApiConnectionClient", () => {expect(result.body).toEqual({ error: "nope" });});+ it("follows same-origin redirects with the connection's credentials", async () => {+ const fetchMock = vi.fn(async (url: URL, _init: RequestInit) =>+ url.pathname === "/v1/projects/prj_1"+ ? new Response(null, { status: 308, headers: { location: "/v2/projects/prj_1" } })+ : new Response(JSON.stringify({ id: "prj_1" }), {+ status: 200,+ headers: { "content-type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const client = new OpenApiConnectionClient(+ makeConnection({+ authorization: { getToken: async () => ({ token: "secret" }), principalType: "app" },+ }),+ );+ const result = await client.executeTool("getProject", { id: "prj_1" }, EXECUTE_OPTIONS);++ expect(result.body).toEqual({ id: "prj_1" });+ const [calledUrl, init] = fetchMock.mock.calls[1]!;+ expect(calledUrl.toString()).toBe("https://api.example.com/v2/projects/prj_1");+ expect(init.redirect).toBe("manual");+ expect((init.headers as Record<string, string>).Authorization).toBe("Bearer secret");+ });++ it("re-sends a POST redirected with 303 as a bodiless GET", async () => {+ const fetchMock = vi.fn(async (url: URL, _init: RequestInit) =>+ url.pathname === "/v1/projects"+ ? new Response(null, { status: 303, headers: { location: "/v1/projects/prj_1" } })+ : new Response(null, { status: 200 }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const client = new OpenApiConnectionClient(makeConnection());+ await client.executeTool("createProject", { body: { name: "demo" } }, EXECUTE_OPTIONS);++ const [, init] = fetchMock.mock.calls[1]!;+ expect(init.method).toBe("GET");+ expect(init.body).toBeUndefined();+ expect(init.headers).not.toHaveProperty("content-type");+ });++ it("returns a cross-origin redirect without sending credentials to its target", async () => {+ const fetchMock = vi.fn(+ async (_url: URL, _init: RequestInit) =>+ new Response("moved", {+ status: 302,+ headers: { location: "https://storage.example.net/archive.tar.gz" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const client = new OpenApiConnectionClient(+ makeConnection({+ authorization: { getToken: async () => ({ token: "secret" }), principalType: "app" },+ spec: {+ ...SPEC,+ components: {+ ...(SPEC.components as Record<string, unknown>),+ securitySchemes: { apiKey: { type: "apiKey", in: "header", name: "X-API-Key" } },+ },+ security: [{ apiKey: [] }],+ },+ }),+ );+ const result = await client.executeTool("getProject", { id: "prj_1" }, EXECUTE_OPTIONS);++ expect(result).toEqual({+ status: 302,+ statusText: expect.any(String),+ body: "moved",+ location: "https://storage.example.net/archive.tar.gz",+ });+ expect(fetchMock).toHaveBeenCalledOnce();+ const [, init] = fetchMock.mock.calls[0]!;+ expect(init.redirect).toBe("manual");+ expect(init.headers).toHaveProperty("X-API-Key", "secret");+ });++ it("fails with a clear error when same-origin redirects loop", async () => {+ const fetchMock = vi.fn(+ async () => new Response(null, { status: 302, headers: { location: "/v1/projects/prj_1" } }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const client = new OpenApiConnectionClient(makeConnection());++ await expect(+ client.executeTool("getProject", { id: "prj_1" }, EXECUTE_OPTIONS),+ ).rejects.toThrow(/stopped after 10 redirects/);+ });+it("throws for an unknown tool name", async () => {const client = new OpenApiConnectionClient(makeConnection());await expect(client.executeTool("nonexistent", {}, EXECUTE_OPTIONS)).rejects.toThrow(diff --git a/packages/eve/src/runtime/connections/openapi-client.ts b/packages/eve/src/runtime/connections/openapi-client.tsindex 1f4a6f8d5..34ed3c06f 100644--- a/packages/eve/src/runtime/connections/openapi-client.ts+++ b/packages/eve/src/runtime/connections/openapi-client.ts@@ -67,6 +67,8 @@ interface OpenApiToolResult {readonly status: number;readonly statusText: string;readonly body: unknown;+ /** Target of a redirect to another origin, which eve returns instead of following. */+ location?: string;}/**@@ -455,21 +457,89 @@ export class OpenApiConnectionClient implements ConnectionClient {headers["content-type"] = operation.requestBody.contentType;}- const response = await fetch(url, {- method: operation.method.toUpperCase(),- headers,- body,- signal: options?.abortSignal,- });+ const { response, location } = await fetchWithinOrigin(+ url,+ {+ method: operation.method.toUpperCase(),+ headers,+ body,+ signal: options?.abortSignal,+ },+ this.#connection.connectionName,+ );- return {+ const result: OpenApiToolResult = {status: response.status,statusText: response.statusText,body: await readResponseBody(response),};+ if (location !== undefined) result.location = location;+ return result;+ }+}++const MAX_REDIRECTS = 10;+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);++interface OperationRequestInit {+ readonly method: string;+ readonly headers: Record<string, string>;+ readonly body: string | undefined;+ readonly signal: AbortSignal | undefined;+}++/**+ * Sends an operation request, following redirects only within the request's+ * origin. Every hop carries the connection's credentials, and fetch forwards+ * custom headers such as an api-key header to any origin a redirect names. A+ * cross-origin redirect is therefore returned with its resolved `location`+ * instead of followed, so the caller can fetch the target without credentials.+ */+async function fetchWithinOrigin(+ url: URL,+ init: OperationRequestInit,+ connectionName: string,+): Promise<{ readonly response: Response; readonly location?: string }> {+ let current = url;+ let request = init;+ for (let redirects = 0; ; redirects++) {+ const response = await fetch(current, { ...request, redirect: "manual" });+ const location = response.headers.get("location");+ if (!REDIRECT_STATUSES.has(response.status) || location === null) {+ return { response };+ }+ const next = URL.parse(location, current.href);+ if (next === null) {+ return { response };+ }+ if (next.origin !== url.origin) {+ return { response, location: next.href };+ }+ await response.body?.cancel();+ if (redirects >= MAX_REDIRECTS) {+ throw new Error(+ `OpenAPI connection "${connectionName}" stopped after ${MAX_REDIRECTS} redirects from "${url.origin}${url.pathname}", last to "${next.pathname}". The API may be redirecting in a loop.`,+ );+ }+ current = next;+ request = redirectedRequest(request, response.status);}}+/** Applies fetch's method rewrite: 303, and 301/302 after a POST, re-send as a bodiless GET. */+function redirectedRequest(init: OperationRequestInit, status: number): OperationRequestInit {+ const becomesGet =+ (status === 303 && init.method !== "GET" && init.method !== "HEAD") ||+ ((status === 301 || status === 302) && init.method === "POST");+ if (!becomesGet) {+ return init;+ }+ const headers = Object.fromEntries(+ Object.entries(init.headers).filter(([name]) => name.toLowerCase() !== "content-type"),+ );+ return { ...init, method: "GET", headers, body: undefined };+}+function appendQuery(query: URLSearchParams, name: string, value: unknown): void {if (isArray(value)) {for (const item of value) {