Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(security): example and reference providers serve servers, not browsers (OH-21) (#357)

0xken157d89576adffa
diff --git a/provider/example-provider/src/server.spec.ts b/provider/example-provider/src/server.spec.ts
index 7c2aaee0f..ad5b76291 100644
--- a/provider/example-provider/src/server.spec.ts
+++ b/provider/example-provider/src/server.spec.ts
@@ -449,3 +449,30 @@ describe('the method surface', () => {
})
})
})
+
+describe('only servers are clients', () => {
+ it('refuses a request a browser made, whatever its credential', async () => {
+ await withServer('/bin/false', async (port) => {
+ for (const headers of [{ origin: 'http://rebind.example' }, { 'sec-fetch-site': 'same-origin' }] as Record<string, string>[]) {
+ const res = await fetch(`http://127.0.0.1:${port}/`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: 'Bearer test-key', ...headers },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent.list', params: {} }),
+ })
+ expect(res.status, JSON.stringify(headers)).toBe(403)
+ }
+ expect(await rpc(port, 'agent.list', {})).toHaveProperty('agents')
+ })
+ })
+
+ it('refuses a body past the request size limit instead of buffering it', async () => {
+ await withServer('/bin/false', async (port) => {
+ const res = await fetch(`http://127.0.0.1:${port}/`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: 'Bearer test-key' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent.list', params: { pad: 'x'.repeat(2 * 1024 * 1024) } }),
+ }).catch(() => null)
+ expect(res?.status).toBe(413)
+ })
+ })
+})
diff --git a/provider/example-provider/src/server.ts b/provider/example-provider/src/server.ts
index f533942f0..f5a9ab010 100644
--- a/provider/example-provider/src/server.ts
+++ b/provider/example-provider/src/server.ts
@@ -66,10 +66,25 @@ async function handle(req: IncomingMessage, res: ServerResponse, deps: Deps): Pr
sendJson(res, 404, { error: 'not found' })
return
}
+ // A provider is called server to server; no browser is a client. A browser always says where a POST
+ // came from, so refusing one that does keeps a web page — including one that re-points its own
+ // hostname at this port — from driving the provider, without a Host rule that a proxy in front of
+ // it would break.
+ if (req.headers.origin !== undefined || req.headers['sec-fetch-site'] !== undefined) {
+ sendJson(res, 403, { error: 'forbidden' })
+ return
+ }
let rpc: RpcRequest
+ let raw: string
try {
- rpc = JSON.parse(await readBody(req)) as RpcRequest
+ raw = await readBody(req)
+ } catch {
+ sendJson(res, 413, { error: 'body too large' })
+ return
+ }
+ try {
+ rpc = JSON.parse(raw) as RpcRequest
} catch {
sendError(res, null, 'invalid_request', 'body is not JSON')
return
@@ -430,10 +445,26 @@ function header(req: IncomingMessage, name: string): string | undefined {
return Array.isArray(v) ? v[0] : v
}
-async function readBody(req: IncomingMessage): Promise<string> {
- let body = ''
- for await (const chunk of req) body += chunk
- return body
+/** A JSON-RPC request is small; anything past this is refused rather than buffered without end. */
+const MAX_BODY_BYTES = 1024 * 1024
+
+/** Rejects when the body passes MAX_BODY_BYTES. The rest is read and discarded, never kept, so memory
+ * stays bounded and the caller can still answer 413 on a connection the client is not writing into. */
+function readBody(req: IncomingMessage): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const chunks: Buffer[] = []
+ let size = 0
+ req.on('data', (chunk: Buffer) => {
+ size += chunk.length
+ if (size <= MAX_BODY_BYTES) chunks.push(chunk)
+ else chunks.length = 0
+ })
+ req.once('end', () => {
+ if (size > MAX_BODY_BYTES) reject(new Error('body too large'))
+ else resolve(Buffer.concat(chunks).toString('utf8'))
+ })
+ req.once('error', reject)
+ })
}
// ── Entry point ──────────────────────────────────────────────────────────────────────────────────
diff --git a/provider/reference-provider/src/server.spec.ts b/provider/reference-provider/src/server.spec.ts
index f671cb4d7..7b645f39c 100644
--- a/provider/reference-provider/src/server.spec.ts
+++ b/provider/reference-provider/src/server.spec.ts
@@ -327,3 +327,26 @@ describe('protocol errors', () => {
expect(result.agents).toBeTruthy()
})
})
+
+describe('only servers are clients', () => {
+ it('refuses a request a browser made, whatever its credential', async () => {
+ for (const headers of [{ origin: 'http://rebind.example' }, { origin: 'null' }, { 'sec-fetch-site': 'same-origin' }] as Record<string, string>[]) {
+ const res = await fetch(base, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${KEY}`, ...headers },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent.list', params: {} }),
+ })
+ expect(res.status, JSON.stringify(headers)).toBe(403)
+ }
+ expect((await rpc('agent.list', {})).status).toBe(200)
+ })
+
+ it('refuses a body past the request size limit instead of buffering it', async () => {
+ const res = await fetch(base, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${KEY}` },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent.list', params: { pad: 'x'.repeat(2 * 1024 * 1024) } }),
+ }).catch(() => null)
+ expect(res?.status).toBe(413)
+ })
+})
diff --git a/provider/reference-provider/src/server.ts b/provider/reference-provider/src/server.ts
index 071de4077..e156940da 100644
--- a/provider/reference-provider/src/server.ts
+++ b/provider/reference-provider/src/server.ts
@@ -44,10 +44,25 @@ async function handle(req: IncomingMessage, res: ServerResponse, store: Store):
sendJson(res, 404, { error: 'not found' })
return
}
+ // A provider is called server to server; no browser is a client. A browser always says where a POST
+ // came from, so refusing one that does keeps a web page — including one that re-points its own
+ // hostname at this port — from driving the provider, without a Host rule that a proxy in front of
+ // it would break.
+ if (req.headers.origin !== undefined || req.headers['sec-fetch-site'] !== undefined) {
+ sendJson(res, 403, { error: 'forbidden' })
+ return
+ }
let rpc: RpcRequest
+ let raw: string
try {
- rpc = JSON.parse(await readBody(req)) as RpcRequest
+ raw = await readBody(req)
+ } catch {
+ sendJson(res, 413, { error: 'body too large' })
+ return
+ }
+ try {
+ rpc = JSON.parse(raw) as RpcRequest
} catch {
sendError(res, null, 'invalid_request', 'body is not JSON')
return
@@ -254,10 +269,26 @@ function header(req: IncomingMessage, name: string): string | undefined {
return Array.isArray(v) ? v[0] : v
}
-async function readBody(req: IncomingMessage): Promise<string> {
- let body = ''
- for await (const chunk of req) body += chunk
- return body
+/** A JSON-RPC request is small; anything past this is refused rather than buffered without end. */
+const MAX_BODY_BYTES = 1024 * 1024
+
+/** Rejects when the body passes MAX_BODY_BYTES. The rest is read and discarded, never kept, so memory
+ * stays bounded and the caller can still answer 413 on a connection the client is not writing into. */
+function readBody(req: IncomingMessage): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const chunks: Buffer[] = []
+ let size = 0
+ req.on('data', (chunk: Buffer) => {
+ size += chunk.length
+ if (size <= MAX_BODY_BYTES) chunks.push(chunk)
+ else chunks.length = 0
+ })
+ req.once('end', () => {
+ if (size > MAX_BODY_BYTES) reject(new Error('body too large'))
+ else resolve(Buffer.concat(chunks).toString('utf8'))
+ })
+ req.once('error', reject)
+ })
}
function sendJson(res: ServerResponse, status: number, body: unknown): void {