Open-source AI coworkers that each get a computer of their own: a browser, files and tools, with every action decided before it happens and recorded after. Bring any AG-UI agent.
Validate headers on POST /api/agents/test-connection (#428)
Felix-Ayush47fcba5d8d0a
diff --git a/server/src/agents/routes.ts b/server/src/agents/routes.tsindex dc398f7a..a3177ec8 100644--- a/server/src/agents/routes.ts+++ b/server/src/agents/routes.ts@@ -120,6 +120,68 @@ function isAgentInputObject(input: unknown): input is AgentInputObject {return typeof input === "object" && input !== null && !Array.isArray(input);}+/**+ * Parse and validate the headers a person attaches to a connection test.+ *+ * Unvalidated, the route cast any object straight into the probe `fetch`, so an array value, a+ * nested object, or a `__proto__` key travelled into the network call and threw a TypeError 500 —+ * or probed header handling the deployment never meant to exercise. Names follow the same rule as+ * the stored agent auth header; values must be strings; the whole map is capped so a pasted dump+ * cannot balloon the probe.+ */+export function parseConnectionHeaders(+ input: unknown,+):+ | { ok: true; value: Record<string, string> | undefined }+ | { ok: false; error: string } {+ if (input === undefined) return { ok: true, value: undefined };+ if (typeof input !== "object" || input === null || Array.isArray(input)) {+ return { ok: false, error: "Headers must be an object of name to value." };+ }+ /*+ * A JSON body carrying `__proto__` does not arrive as an own property: `JSON.parse` sets the+ * object's prototype instead, so `Object.entries` never sees it and a name block-list below+ * would pass it straight through into the probe fetch. Refuse any headers object whose prototype+ * is not a plain one before reading entries.+ */+ if (Object.getPrototypeOf(input) !== Object.prototype) {+ return { ok: false, error: "Headers must be an object of name to value." };+ }+ const entries = Object.entries(input);+ if (entries.length > 32) {+ return { ok: false, error: "Headers must have at most 32 entries." };+ }+ const headers: Record<string, string> = {};+ for (const [name, value] of entries) {+ if (+ name === "__proto__" ||+ name === "constructor" ||+ name === "prototype" ||+ !/^[A-Za-z0-9-]+$/.test(name) ||+ name.length > 64+ ) {+ return {+ ok: false,+ error: `That is not a valid header name: ${name.slice(0, 64)}.`,+ };+ }+ if (typeof value !== "string") {+ return {+ ok: false,+ error: `Header "${name}" must be a string value.`,+ };+ }+ if (value.length > 4096) {+ return {+ ok: false,+ error: `Header "${name}" must be at most 4096 characters.`,+ };+ }+ headers[name] = value;+ }+ return { ok: true, value: entries.length === 0 ? undefined : headers };+}+/*** The local development actor, which is not a row in `users`.*@@ -306,10 +368,11 @@ export function createAgentRoutes(endpoint?: unknown;headers?: unknown;} | null;- const headers =- body?.headers && typeof body.headers === "object"- ? (body.headers as Record<string, string>)- : undefined;+ const parsed = parseConnectionHeaders(body?.headers);+ if (!parsed.ok) {+ return context.json({ error: parsed.error }, 400);+ }+ const headers = parsed.value;const result = await testAgentConnection(body?.endpoint, {headers,allowPrivateHosts,diff --git a/server/tests/agent-test-connection-headers.test.ts b/server/tests/agent-test-connection-headers.test.tsnew file mode 100644index 00000000..7b8272e7--- /dev/null+++ b/server/tests/agent-test-connection-headers.test.ts@@ -0,0 +1,91 @@+import { describe, expect, test } from "bun:test";+import type { MiddlewareHandler } from "hono";+import type { AppVariables } from "../src/auth/guards";+import {+ createAgentRoutes,+ parseConnectionHeaders,+} from "../src/agents/routes";++describe("parseConnectionHeaders", () => {+ test("absent headers stay absent", () => {+ expect(parseConnectionHeaders(undefined)).toEqual({+ ok: true,+ value: undefined,+ });+ });++ test("a valid map passes through", () => {+ expect(parseConnectionHeaders({ Authorization: "Bearer x" })).toEqual({+ ok: true,+ value: { Authorization: "Bearer x" },+ });+ });++ test.each([+ ["an array", ["Authorization"]],+ ["a string", "Authorization: Bearer x"],+ ["a number", 42],+ ["an array value", { Authorization: ["Bearer x"] }],+ ["a numeric value", { Authorization: 42 }],+ ["a nested value", { Authorization: { token: "x" } }],+ ["a null value", { Authorization: null }],+ // An object literal cannot carry its own __proto__: the syntax sets the prototype instead, so+ // the value travels through JSON text the way a real request body does.+ ["a __proto__ key", JSON.parse('{"__proto__":"polluted"}')],+ ["a constructor key", { constructor: "x" }],+ ["an invalid name", { "X Bad Name!": "x" }],+ ["an empty name", { "": "x" }],+ ])("rejects %s", (_name, input) => {+ const parsed = parseConnectionHeaders(input);+ expect(parsed.ok).toBe(false);+ });+});++describe("POST /test-connection header validation", () => {+ function appFor() {+ const requireUser: MiddlewareHandler<{ Variables: AppVariables }> = async (+ context,+ next,+ ) => {+ context.set("actor", {+ id: "user-1",+ email: "[email protected]",+ role: "user",+ });+ await next();+ };+ return createAgentRoutes({} as never, requireUser, true);+ }++ test("invalid headers answer 400 without probing", async () => {+ const app = appFor();+ const response = await app.request("http://openbot.test/test-connection", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ endpoint: "https://agent.example/ag-ui",+ headers: { Authorization: ["Bearer x"] },+ }),+ });++ expect(response.status).toBe(400);+ const body = (await response.json()) as { error: string };+ expect(body.error).toMatch(/must be a string value/);+ });++ test("a __proto__ key answers 400", async () => {+ const app = appFor();+ // Built as text: an object literal cannot carry its own __proto__ through JSON.stringify, so+ // a real request carrying one arrives as raw JSON exactly like this.+ const rawBody = JSON.stringify({+ endpoint: "https://agent.example/ag-ui",+ }).replace(/}$/, ',"headers":{"__proto__":"polluted"}}');+ const response = await app.request("http://openbot.test/test-connection", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: rawBody,+ });++ expect(response.status).toBe(400);+ });+});