diff --git a/packages/contracts/src/facades/remote.ts b/packages/contracts/src/facades/remote.ts index 820d3c79b67..abf4b6a367c 100644 --- a/packages/contracts/src/facades/remote.ts +++ b/packages/contracts/src/facades/remote.ts @@ -1,3 +1,5 @@ +import type { ReasonTable } from '@agent-device/kernel/errors'; + export type { CompanionTunnelScope, MetroBridgeScope } from '../companion-tunnel-scope.ts'; export type { MetroBridgeResult, @@ -22,6 +24,13 @@ export { PROVIDER_PROFILE_FIELD_FLAG_ALIASES, PROVIDER_PROFILE_FIELD_FLAGS, } from '../remote-config-fields.ts'; + +/** Why a provider response was rejected before its body was accepted. */ +export const PROVIDER_RESPONSE_REASONS = { + // A provider answered with more bytes than the response budget allows. + tooLarge: { reason: 'provider_response_too_large' }, +} as const satisfies ReasonTable<'provider response'>; + export type { CloudProviderProfileFields, DaemonRpcMode, diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index 098e6076e4c..ef3d0698b9d 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -22,6 +22,27 @@ test('uses the public Revyl backend when no URL is configured', () => { assert.equal(client.backendUrl, REVYL_DEFAULT_BACKEND_URL); }); +test('rejects an oversized provider answer before accepting its body', async () => { + const client = clientResponding( + () => + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)); + }, + }), + { status: 200, headers: { 'content-type': 'application/json' } }, + ), + ); + await assert.rejects( + client.verifyCredentials(), + (error: unknown) => + error instanceof AppError && + error.details?.reason === 'provider_response_too_large' && + error.details?.limitBytes === 32 * 1024 * 1024, + ); +}); + test('keeps plain HTTP only on loopback', () => { assert.equal(resolveRevylBackendUrl('http://127.0.0.1:8787'), 'http://127.0.0.1:8787'); assert.equal(resolveRevylBackendUrl('http://localhost:8787'), 'http://localhost:8787'); diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index 11caa8523a9..a9261272b7e 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -6,6 +6,7 @@ import { } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; +import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/remote'; import fs from 'node:fs'; import { Readable } from 'node:stream'; import { setTimeout as sleep } from 'node:timers/promises'; @@ -30,6 +31,8 @@ export const REVYL_DEFAULT_BACKEND_URL = 'https://backend.revyl.ai'; const REVYL_ATTRIBUTION = 'agent-device'; const DEFAULT_REQUEST_TIMEOUT_MS = 30_000; +const MAX_REVYL_RESPONSE_BYTES = 32 * 1024 * 1024; + /** How long `start_device` may take to answer: Revyl assigns a worker and boots the device in it. */ export const REVYL_START_DEVICE_TIMEOUT_MS = 120_000; const RETRY_DELAYS_MS = [500, 1_500] as const; @@ -379,9 +382,10 @@ async function sendOnce( return Object.freeze({ status: response.status, contentType: response.headers.get('content-type') ?? undefined, - body: new Uint8Array(await response.arrayBuffer()), + body: await readRevylResponseBody(response), }); } catch (error) { + if (error instanceof AppError) return error; if (request.signal?.aborted) return requestCanceled(request, error); if (timeout.aborted) return requestTimedOut(request, error); return new AppError( @@ -393,6 +397,29 @@ async function sendOnce( } } +async function readRevylResponseBody(response: Response): Promise { + if (!response.body) return new Uint8Array(); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) return new Uint8Array(Buffer.concat(chunks, bytes)); + bytes += value.byteLength; + if (bytes > MAX_REVYL_RESPONSE_BYTES) { + throw new AppError('COMMAND_FAILED', 'Revyl response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, + limitBytes: MAX_REVYL_RESPONSE_BYTES, + }); + } + chunks.push(value); + } + } finally { + void reader.cancel().catch(() => {}); + } +} + /** * Only a request that never reached Revyl, or a status Revyl marks transient, is replayed. A * cancellation is the caller's own answer, and a timeout has already spent the request's budget, so diff --git a/packages/provider-webdriver/src/webdriver-transport.test.ts b/packages/provider-webdriver/src/webdriver-transport.test.ts index 61bb44bf4c6..8016db15b7b 100644 --- a/packages/provider-webdriver/src/webdriver-transport.test.ts +++ b/packages/provider-webdriver/src/webdriver-transport.test.ts @@ -26,6 +26,28 @@ afterEach(() => { globalThis.fetch = realFetch; }); +test('WebDriver stops reading a response after its byte limit', async () => { + const transport = new WebDriverTransport({ + clientVersion: '0.0.0-test', + endpoint: 'https://cloud-webdriver.test/wd/hub/', + }); + globalThis.fetch = async () => + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)); + }, + }), + ); + await assert.rejects( + transport.requestValue('GET', '/session/x/source'), + (error: unknown) => + error instanceof AppError && + error.details?.reason === 'provider_response_too_large' && + error.details?.dispatched === 'unknown', + ); +}); + // The transport's own deadline must surface as a machine-readable reason, not // as fetch's `AbortError`/`TimeoutError` DOMException name: the session manager // keys its "the provider may still be creating a billed session" branch on diff --git a/packages/provider-webdriver/src/webdriver-transport.ts b/packages/provider-webdriver/src/webdriver-transport.ts index 717aa9e3552..6ec7dd25e42 100644 --- a/packages/provider-webdriver/src/webdriver-transport.ts +++ b/packages/provider-webdriver/src/webdriver-transport.ts @@ -1,7 +1,12 @@ import { setTimeout as sleep } from 'node:timers/promises'; import { AppError, type DispatchDisclosure, type ReasonTable } from '@agent-device/kernel/errors'; import { agentDeviceRequestHeaders } from './request-headers.ts'; -import { basicAuthHeader, trimLeadingSlash, withTrailingSlash } from './webdriver-utils.ts'; +import { + basicAuthHeader, + readProviderTextBody, + trimLeadingSlash, + withTrailingSlash, +} from './webdriver-utils.ts'; /** Why a WebDriver request failed at the transport. */ const WEBDRIVER_TRANSPORT_REASONS = { @@ -261,8 +266,20 @@ export class WebDriverTransport { throw classifyWebDriverFetchFailure(error, failure, 'request'); } try { - return { ok: response.ok, status: response.status, text: await response.text() }; + return { + ok: response.ok, + status: response.status, + text: await readProviderTextBody(response), + }; } catch (error) { + if (error instanceof AppError) { + throw new AppError( + error.code, + error.message, + { ...error.details, ...dispatchDisclosure('unknown') }, + error, + ); + } throw classifyWebDriverFetchFailure(error, failure, 'response'); } } diff --git a/packages/provider-webdriver/src/webdriver-utils.test.ts b/packages/provider-webdriver/src/webdriver-utils.test.ts index d2b62f826ff..48358440e78 100644 --- a/packages/provider-webdriver/src/webdriver-utils.test.ts +++ b/packages/provider-webdriver/src/webdriver-utils.test.ts @@ -63,6 +63,11 @@ test('the hub upload helper posts with credentials and returns the vendor refere assert.equal(await postHubAppUpload(form, hub), 'hub://APP1'); }); +test('the hub upload helper parses a response with a UTF-8 byte-order mark', async () => { + globalThis.fetch = async () => new Response('\ufeff{"ref":"hub://APP1"}'); + assert.equal(await postHubAppUpload(new FormData(), hub), 'hub://APP1'); +}); + test('the hub upload helper fails typed with the status on an error page or a missing reference', async () => { for (const response of [ new Response('502 Bad Gateway', { status: 502 }), diff --git a/packages/provider-webdriver/src/webdriver-utils.ts b/packages/provider-webdriver/src/webdriver-utils.ts index 07057f3010e..d584b958b9d 100644 --- a/packages/provider-webdriver/src/webdriver-utils.ts +++ b/packages/provider-webdriver/src/webdriver-utils.ts @@ -9,6 +9,7 @@ import type { } from '@agent-device/contracts/device'; import { PROVIDER_DEVICE_ORIENTATIONS, + PROVIDER_RESPONSE_REASONS, type ProviderDeviceOrientation, } from '@agent-device/contracts/remote'; import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors'; @@ -74,6 +75,32 @@ export function withTrailingSlash(url: URL): URL { type HubCredentials = { username: string; accessKey: string }; +const MAX_PROVIDER_RESPONSE_BYTES = 32 * 1024 * 1024; + +/** Bound provider answers even when a peer omits or lies about Content-Length. */ +export async function readProviderTextBody(response: Response): Promise { + if (!response.body) return ''; + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) return new TextDecoder().decode(Buffer.concat(chunks, bytes)); + bytes += value.byteLength; + if (bytes > MAX_PROVIDER_RESPONSE_BYTES) { + throw new AppError('COMMAND_FAILED', 'Provider response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, + limitBytes: MAX_PROVIDER_RESPONSE_BYTES, + }); + } + chunks.push(value); + } + } finally { + void reader.cancel().catch(() => {}); + } +} + /** * A multipart form carrying the local app file under the hub's field name. Upload APIs take one * regular file, so anything else (an extracted `.app` directory, a missing path) is refused here, @@ -142,6 +169,7 @@ export async function postHubAppUpload( json = await readProviderJsonBody(response); } catch (error) { if (signal?.aborted) throw error; + if (error instanceof AppError) throw error; const timedOut = timeoutSignal.aborted; throw new AppError( 'COMMAND_FAILED', @@ -325,6 +353,7 @@ export async function fetchProviderSessionDetails( }); json = await readProviderJsonBody(response); } catch (error) { + if (error instanceof AppError) throw error; throw new AppError( 'COMMAND_FAILED', `${options.service} session details lookup failed.`, @@ -347,7 +376,7 @@ export async function fetchProviderSessionDetails( /** A provider response body parsed as JSON, or `undefined` when it is empty or not JSON (a gateway error page). */ async function readProviderJsonBody(response: Response): Promise { - const text = await response.text(); + const text = await readProviderTextBody(response); if (text.length === 0) return undefined; try { return JSON.parse(text) as unknown; diff --git a/src/core/interactors/limrun-http-response.test.ts b/src/core/interactors/limrun-http-response.test.ts new file mode 100644 index 00000000000..403aa59704c --- /dev/null +++ b/src/core/interactors/limrun-http-response.test.ts @@ -0,0 +1,33 @@ +import { expect, test } from 'vitest'; +import { readLimrunControlJson } from './limrun-http-response.ts'; + +test('stops an oversized Limrun control response before accepting its body', async () => { + const response = new Response('{}', { + headers: { 'content-length': String(32 * 1024 * 1024 + 1) }, + }); + + await expect(readLimrunControlJson(response)).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'provider_response_too_large', limitBytes: 32 * 1024 * 1024 }, + }); +}); + +test('stops a streaming Limrun control response without a declared length', async () => { + const response = new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)); + }, + }), + ); + + await expect(readLimrunControlJson(response)).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'provider_response_too_large', limitBytes: 32 * 1024 * 1024 }, + }); +}); + +test('parses a bounded Limrun control response with a UTF-8 byte-order mark', async () => { + const response = new Response('\ufeff{"synced":true}'); + await expect(readLimrunControlJson(response)).resolves.toEqual({ synced: true }); +}); diff --git a/src/core/interactors/limrun-http-response.ts b/src/core/interactors/limrun-http-response.ts new file mode 100644 index 00000000000..0e2a1940ed3 --- /dev/null +++ b/src/core/interactors/limrun-http-response.ts @@ -0,0 +1,48 @@ +import { AppError } from '@agent-device/kernel/errors'; +import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/remote'; + +const MAX_LIMRUN_CONTROL_RESPONSE_BYTES = 32 * 1024 * 1024; + +export async function readLimrunControlText( + response: Response, + signal?: AbortSignal, +): Promise { + signal?.throwIfAborted(); + const declaredBytes = Number(response.headers.get('content-length')); + if (Number.isFinite(declaredBytes) && declaredBytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) { + await response.body?.cancel().catch(() => {}); + throw responseTooLarge(); + } + if (!response.body) return ''; + const reader = response.body.getReader(); + const cancel = () => void reader.cancel(signal?.reason).catch(() => {}); + signal?.addEventListener('abort', cancel, { once: true }); + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + while (true) { + const { done, value } = await reader.read(); + signal?.throwIfAborted(); + if (done) return new TextDecoder().decode(Buffer.concat(chunks, bytes)); + bytes += value.byteLength; + if (bytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) { + throw responseTooLarge(); + } + chunks.push(value); + } + } finally { + signal?.removeEventListener('abort', cancel); + void reader.cancel().catch(() => {}); + } +} + +function responseTooLarge(): AppError { + return new AppError('COMMAND_FAILED', 'Limrun response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, + limitBytes: MAX_LIMRUN_CONTROL_RESPONSE_BYTES, + }); +} + +export async function readLimrunControlJson(response: Response): Promise { + return JSON.parse(await readLimrunControlText(response)) as T; +} diff --git a/src/core/interactors/limrun-ios-files.ts b/src/core/interactors/limrun-ios-files.ts index 9ad197b71d6..7d96f7184d0 100644 --- a/src/core/interactors/limrun-ios-files.ts +++ b/src/core/interactors/limrun-ios-files.ts @@ -9,6 +9,7 @@ import { import type { LimrunRuntimeDependencies } from '@agent-device/provider-limrun'; import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import { downloadLimrunFile } from '../limrun-download-file.ts'; +import { readLimrunControlJson } from './limrun-http-response.ts'; type Session = Parameters[0]; type Files = AppleToolProvider['simulatorFiles']; @@ -95,7 +96,9 @@ export function createLimrunSimulatorFiles( const list = () => operation(container, async (signal) => { const response = await request('GET', urlFor('files/list', '', container), signal); - const result = (await response.json()) as { entries: Array<{ name: string }> }; + const result = await readLimrunControlJson<{ entries: Array<{ name: string }> }>( + response, + ); return result.entries.map((entry) => entry.name); }); try { @@ -141,7 +144,7 @@ export function createLimrunSimulatorFiles( signal, await fs.readFile(localPath, { signal }), ); - return (await response.json()) as { path: string }; + return await readLimrunControlJson<{ path: string }>(response); }).catch(async (error: unknown) => { await remove().catch(() => {}); throw error; diff --git a/src/core/interactors/limrun-ios-runner-products.ts b/src/core/interactors/limrun-ios-runner-products.ts index c4cc114849f..ff305f0e81d 100644 --- a/src/core/interactors/limrun-ios-runner-products.ts +++ b/src/core/interactors/limrun-ios-runner-products.ts @@ -1,4 +1,5 @@ import { limrunRunnerError } from './limrun-ios-runner-errors.ts'; +import { readLimrunControlJson } from './limrun-http-response.ts'; import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { runnerListenerEnv, @@ -305,7 +306,7 @@ export async function uploadLimrunRunnerProducts( }, ); } - return (await response.json()) as { ok?: boolean; needFull?: string[] }; + return await readLimrunControlJson<{ ok?: boolean; needFull?: string[] }>(response); } finally { stream.destroy(); await compression; diff --git a/src/core/interactors/limrun-ios-runner.test.ts b/src/core/interactors/limrun-ios-runner.test.ts index d39348077a9..50c37871fa0 100644 --- a/src/core/interactors/limrun-ios-runner.test.ts +++ b/src/core/interactors/limrun-ios-runner.test.ts @@ -136,16 +136,16 @@ test('an admitted XCTest stream survives its launch deadline', async () => { test('a stalled rejection body respects the launch deadline and does not claim the occupied slot', async () => { const timeout = new AbortController(); - let markReadStarted!: () => void; - const readStarted = new Promise((resolve) => { - markReadStarted = resolve; + let markBodyRead!: () => void; + const bodyRead = new Promise((resolve) => { + markBodyRead = resolve; }); - const readText = Response.prototype.text; + const getBody = Object.getOwnPropertyDescriptor(Response.prototype, 'body')!.get!; const responseBody = vi - .spyOn(Response.prototype, 'text') + .spyOn(Response.prototype, 'body', 'get') .mockImplementation(function (this: Response) { - if (this.status === 409) markReadStarted(); - return readText.call(this); + if (this.status === 409) markBodyRead(); + return getBody.call(this); }); const realTimeout = AbortSignal.timeout.bind(AbortSignal); const timer = vi @@ -163,7 +163,7 @@ test('a stalled rejection body respects the launch deadline and does not claim t { healthCheck: false }, ); const failed = expect(prepare()).rejects.toMatchObject({ details: { status: 409 } }); - await readStarted; + await bodyRead; timeout.abort(new DOMException('Admission expired', 'TimeoutError')); await failed; timer.mockRestore(); @@ -240,13 +240,12 @@ test.each([ const conflict = new Promise((resolve) => { conflictRead = resolve; }); - const originalText = Response.prototype.text; + const getBody = Object.getOwnPropertyDescriptor(Response.prototype, 'body')!.get!; const responseBody = vi - .spyOn(Response.prototype, 'text') - .mockImplementation(async function (this: Response) { - const body = await originalText.call(this); + .spyOn(Response.prototype, 'body', 'get') + .mockImplementation(function (this: Response) { if (this.status === 409) conflictRead(); - return body; + return getBody.call(this); }); vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); try { diff --git a/src/core/interactors/limrun-ios-runner.ts b/src/core/interactors/limrun-ios-runner.ts index d906dc8124f..3094bafeff3 100644 --- a/src/core/interactors/limrun-ios-runner.ts +++ b/src/core/interactors/limrun-ios-runner.ts @@ -21,6 +21,7 @@ import { writeLimrunRunnerConfiguration, type LimrunRunnerProducts, } from './limrun-ios-runner-products.ts'; +import { readLimrunControlText } from './limrun-http-response.ts'; type LimrunIosRunner = Awaited>; type Session = Parameters[0]; @@ -187,7 +188,10 @@ export async function createLimrunIosRunner( `Limrun XCTest launch failed (${result.status})`, { status: result.status, - response: await awaitWithSignal(result.text(), launchSignal).catch(() => undefined), + response: await awaitWithSignal( + readLimrunControlText(result, launchSignal), + launchSignal, + ).catch(() => undefined), }, ); if (result.status === 409) lastConflict = failure; diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 4bd8765a666..44078aa0b94 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -901,6 +901,12 @@ These reasons can come from more than one command. | `exit-timeout` | SIGKILL was sent and nothing proved the process exited within the budget it was given. | | `identity-unverified` | Nothing confirmed the pid names the recorded process, so signalling it was refused. | +### Provider response + +| Reason | Meaning | +| --- | --- | +| `provider_response_too_large` | A provider answered with more bytes than the response budget allows. | + ### Proxy RPC ingress | Reason | Meaning |