From 24f9b1e817cf05011ce1d7938727c1fe38eddd8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 14:03:18 +0100 Subject: [PATCH 01/19] fix(providers): bound credential endpoints and responses --- packages/provider-limrun/src/android.ts | 2 + .../src/device-session.test.ts | 4 + .../provider-limrun/src/device-session.ts | 2 + .../src/runtime-dependencies.ts | 2 + .../provider-revyl/src/revyl-client.test.ts | 38 +++++++++ packages/provider-revyl/src/revyl-client.ts | 59 +++++++++++++- .../src/webdriver-transport.test.ts | 33 ++++++++ .../src/webdriver-transport.ts | 22 ++++- .../src/webdriver-utils.test.ts | 31 +++++++ .../provider-webdriver/src/webdriver-utils.ts | 81 ++++++++++++++++++- .../limrun-ios-runner-products.test.ts | 10 ++- src/core/limrun-download-file.test.ts | 33 ++++++++ src/core/limrun-download-file.ts | 60 +++++++++++++- .../cloud-webdriver-test-server.ts | 2 +- website/docs/docs/error-reasons.md | 4 + 15 files changed, 365 insertions(+), 18 deletions(-) diff --git a/packages/provider-limrun/src/android.ts b/packages/provider-limrun/src/android.ts index a66145d5f5e..344a1220de8 100644 --- a/packages/provider-limrun/src/android.ts +++ b/packages/provider-limrun/src/android.ts @@ -41,6 +41,7 @@ type LimrunAndroidAdbSession = { platform: 'android'; lease: DeviceLease; instanceId: string; + readonly apiUrl: string; readonly ownership: LimrunInstanceOwnership; device: DeviceInfo; syncCache?: LimrunSyncCache; @@ -91,6 +92,7 @@ export async function createLimrunAndroidSession( platform: 'android', lease: options.lease, instanceId: options.instanceId, + apiUrl: options.apiUrl, ownership: options.ownership, device: options.device, client, diff --git a/packages/provider-limrun/src/device-session.test.ts b/packages/provider-limrun/src/device-session.test.ts index d45b03e3abd..6674b58ba5c 100644 --- a/packages/provider-limrun/src/device-session.test.ts +++ b/packages/provider-limrun/src/device-session.test.ts @@ -97,6 +97,7 @@ test('iOS device session exposes reusable capabilities without its raw client', assert.deepEqual(downloadFile.mock.calls.at(-1), [ { url: 'https://ios.example/recording', + expectedOrigin: 'https://ios.example', headers: { Authorization: 'Bearer ios-instance-token' }, destinationPath: '/tmp/ios-recording.mp4', timeoutMs: 60_000, @@ -207,6 +208,7 @@ test('Android device session exposes semantic ADB capabilities without its raw c assert.deepEqual(downloadFile.mock.calls.at(-1), [ { url: 'https://android.example/recording', + expectedOrigin: 'https://android.example', headers: { Authorization: 'Bearer android-instance-token' }, destinationPath: '/tmp/android-recording.mp4', timeoutMs: 60_000, @@ -223,6 +225,7 @@ function iosSession(client: Record): LimrunIosSession { runner: testIosRunner, lease: lease('ios-instance'), instanceId: 'ios-instance', + apiUrl: 'https://ios.example/api', device: device('ios'), client, token: 'ios-instance-token', @@ -238,6 +241,7 @@ function androidSession( platform: 'android', lease: lease('android-instance'), instanceId: 'android-instance', + apiUrl: 'https://android.example/api', device: device('android'), client, adbProvider, diff --git a/packages/provider-limrun/src/device-session.ts b/packages/provider-limrun/src/device-session.ts index 3fa3adc750b..1d027bf876b 100644 --- a/packages/provider-limrun/src/device-session.ts +++ b/packages/provider-limrun/src/device-session.ts @@ -174,6 +174,7 @@ const ATTACHED_RECORDING_PERSIST = Object.freeze({ ttlSeconds: 48 * 60 * 60 }); function createRecordingOperations(session: { readonly client: LimrunRecordingClient; + readonly apiUrl: string; readonly token: string; readonly ownership: LimrunInstanceOwnership; readonly dependencies: { readonly host: Pick }; @@ -193,6 +194,7 @@ function createRecordingOperations(session: { downloadRecording: async (input: { downloadUrl: string; outPath: string }) => { await host.downloadFile({ url: input.downloadUrl, + expectedOrigin: new URL(session.apiUrl).origin, headers: { Authorization: `Bearer ${token}` }, destinationPath: input.outPath, timeoutMs: LIMRUN_RECORDING_DOWNLOAD_TIMEOUT_MS, diff --git a/packages/provider-limrun/src/runtime-dependencies.ts b/packages/provider-limrun/src/runtime-dependencies.ts index fa81df773f5..23b47b764d3 100644 --- a/packages/provider-limrun/src/runtime-dependencies.ts +++ b/packages/provider-limrun/src/runtime-dependencies.ts @@ -157,6 +157,8 @@ export type LimrunAndroidRuntimeAdapter = { /** One authenticated HTTP download the host performs on the provider's behalf, bounded by `timeoutMs`. */ export type LimrunFileDownload = Readonly<{ url: string; + /** The instance API origin allowed to receive its bearer token. */ + expectedOrigin?: string; headers: Readonly>; destinationPath: string; timeoutMs: number; diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index 098e6076e4c..a91fd67d68f 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -22,6 +22,44 @@ 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-invalid', + ); +}); + +test('rejects unsafe provider-supplied artifact URLs before an app upload', async () => { + for (const uploadUrl of [ + 'http://169.254.169.254/upload', + 'http://127.0.0.1:8/upload', + 'https://127.0.0.1/upload', + 'https://[fd00::1]/upload', + 'https://user:pass@storage.example/upload', + ]) { + const client = clientResponding(() => + jsonResponse({ upload_url: uploadUrl, download_url: 'https://storage.example/download' }), + ); + await assert.rejects( + client.createSessionArtifactUpload('session-1', 10, 'application/octet-stream'), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'invalid_provider_url', + ); + } +}); + 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..24b7f58b6c3 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -7,6 +7,7 @@ import { import { isRecord } from '@agent-device/kernel/record'; import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; import fs from 'node:fs'; +import { isIP } from 'node:net'; import { Readable } from 'node:stream'; import { setTimeout as sleep } from 'node:timers/promises'; import type { @@ -30,6 +31,7 @@ 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; @@ -290,16 +292,21 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { assertLifecycleAccepted('stop', response); return response; }, - createSessionArtifactUpload(sessionId, fileSize, contentType, signal) { - return json({ + async createSessionArtifactUpload(sessionId, fileSize, contentType, signal) { + const upload = await json({ method: 'POST', path: `/api/v1/execution/device-sessions/${encodeURIComponent(sessionId)}/artifacts/upload-url`, body: { file_size: fileSize, content_type: contentType }, route: 'session', ...(signal === undefined ? {} : { signal }), }); + return { + upload_url: requireRevylArtifactUrl(upload.upload_url, backendUrl), + download_url: requireRevylArtifactUrl(upload.download_url, backendUrl), + }; }, async uploadSessionArtifact(uploadUrl, file, contentType, signal) { + const admittedUrl = requireRevylArtifactUrl(uploadUrl, backendUrl); // Node streams a request body only in half-duplex mode, which the DOM `RequestInit` type omits. const init: RequestInit & { duplex: 'half' } = { method: 'PUT', @@ -312,7 +319,7 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { }; let response: Response; try { - response = await fetchImpl(uploadUrl, init); + response = await fetchImpl(admittedUrl, init); } catch (error) { throw new AppError( 'COMMAND_FAILED', @@ -357,6 +364,26 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { }); } +function requireRevylArtifactUrl(value: string, backendUrl: string): string { + let url: URL; + try { + url = new URL(value); + } catch { + throw new AppError('COMMAND_FAILED', 'Revyl artifact URL is invalid.', { + reason: REVYL_HTTP_REASONS.invalidProviderUrl.reason, + }); + } + const loopback = isLoopbackHostname(url.hostname) && url.origin === new URL(backendUrl).origin; + const ipLiteral = isIP(url.hostname.replace(/^\[(.*)\]$/, '$1')) !== 0; + if (url.username || url.password || (!loopback && (url.protocol !== 'https:' || ipLiteral))) { + throw new AppError('COMMAND_FAILED', 'Revyl artifact URL is not admitted.', { + reason: REVYL_HTTP_REASONS.invalidProviderUrl.reason, + origin: url.origin, + }); + } + return url.href; +} + async function sendOnce( backendUrl: string, fetchImpl: typeof fetch, @@ -379,9 +406,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 +421,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: REVYL_OUTCOME_REASONS.responseInvalid.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..7ee6c8dd9fe 100644 --- a/packages/provider-webdriver/src/webdriver-transport.test.ts +++ b/packages/provider-webdriver/src/webdriver-transport.test.ts @@ -26,6 +26,39 @@ afterEach(() => { globalThis.fetch = realFetch; }); +test('authenticated WebDriver refuses an insecure remote endpoint before sending credentials', () => { + assert.throws( + () => + new WebDriverTransport({ + clientVersion: '0.0.0-test', + endpoint: 'http://cloud-webdriver.test/wd/hub/', + auth: { username: 'user', accessKey: 'secret' }, + }), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'provider_credential_endpoint_unsafe', + ); +}); + +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', + ); +}); + // 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..437a512975a 100644 --- a/packages/provider-webdriver/src/webdriver-transport.ts +++ b/packages/provider-webdriver/src/webdriver-transport.ts @@ -1,7 +1,13 @@ 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, + requireAuthenticatedProviderEndpoint, + trimLeadingSlash, + withTrailingSlash, +} from './webdriver-utils.ts'; /** Why a WebDriver request failed at the transport. */ const WEBDRIVER_TRANSPORT_REASONS = { @@ -141,7 +147,11 @@ export class WebDriverTransport { private readonly requestPolicy: ResolvedWebDriverRequestPolicy; constructor(options: WebDriverTransportOptions) { - this.endpoint = withTrailingSlash(new URL(options.endpoint)); + this.endpoint = withTrailingSlash( + options.auth + ? requireAuthenticatedProviderEndpoint(options.endpoint) + : new URL(options.endpoint), + ); this.headers = { ...agentDeviceRequestHeaders(options.clientVersion), ...(options.auth ? { Authorization: basicAuthHeader(options.auth) } : {}), @@ -255,14 +265,20 @@ export class WebDriverTransport { ...this.headers, }, body: payload === undefined ? undefined : JSON.stringify(payload), + redirect: 'error', signal, }); } catch (error) { 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 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..61c4511f84b 100644 --- a/packages/provider-webdriver/src/webdriver-utils.test.ts +++ b/packages/provider-webdriver/src/webdriver-utils.test.ts @@ -11,6 +11,7 @@ import { createHubUploadApp, postHubAppUpload, readFlag, + requireAuthenticatedProviderEndpoint, requireConnectFlag, requireConnectPlatform, requireEnv, @@ -49,12 +50,42 @@ const hub = { readAppReference: (body: unknown) => asOptionalRecord(body)?.ref as string | undefined, }; +test('credential-bearing provider endpoints reject cleartext hosts before fetch', async () => { + for (const endpoint of [ + 'http://example.test/upload', + 'http://127.0.0.1.evil.test/upload', + 'ftp://example.test/upload', + 'https://user:pass@example.test/upload', + ]) { + assert.throws( + () => requireAuthenticatedProviderEndpoint(endpoint), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.reason, 'provider_credential_endpoint_unsafe'); + return true; + }, + ); + } + assert.equal(requireAuthenticatedProviderEndpoint('http://127.0.0.2/upload').protocol, 'http:'); + assert.equal(requireAuthenticatedProviderEndpoint('http://[::1]/upload').protocol, 'http:'); + let calls = 0; + globalThis.fetch = async () => { + calls += 1; + return new Response('{}'); + }; + await assert.rejects( + postHubAppUpload(new FormData(), { ...hub, endpoint: 'http://example.test/upload' }), + ); + assert.equal(calls, 0); +}); + test('the hub upload helper posts with credentials and returns the vendor reference', async () => { const form = new FormData(); globalThis.fetch = async (input, init) => { assert.equal(String(input), hub.endpoint); assert.equal(init?.method, 'POST'); assert.equal(init?.body, form); + assert.equal(init?.redirect, 'error'); const headers = init?.headers as Record; assert.equal(headers.Authorization, `Basic ${Buffer.from('user:key').toString('base64')}`); assert.equal(headers['x-agent-device-version'], '0.0.0-test'); diff --git a/packages/provider-webdriver/src/webdriver-utils.ts b/packages/provider-webdriver/src/webdriver-utils.ts index 07057f3010e..1cfc623b3e9 100644 --- a/packages/provider-webdriver/src/webdriver-utils.ts +++ b/packages/provider-webdriver/src/webdriver-utils.ts @@ -1,6 +1,7 @@ import fs from 'node:fs'; import { stat } from 'node:fs/promises'; import path from 'node:path'; +import net from 'node:net'; import type { CliFlags } from '@agent-device/contracts/command'; import type { LeaseLifecycleContext, @@ -42,6 +43,46 @@ export function basicAuthHeader(credentials: { username: string; accessKey: stri return `Basic ${Buffer.from(`${credentials.username}:${credentials.accessKey}`).toString('base64')}`; } +const PROVIDER_RESPONSE_ADMISSION_REASONS = { + // A credential-bearing provider endpoint is neither HTTPS nor loopback HTTP. + credentialEndpointUnsafe: { reason: 'provider_credential_endpoint_unsafe' }, + // A provider answered with more bytes than the response budget allows. + responseTooLarge: { reason: 'provider_response_too_large' }, +} as const satisfies ReasonTable<'webdriver provider'>; + +const LOOPBACK_HOSTS = new net.BlockList(); +LOOPBACK_HOSTS.addSubnet('127.0.0.0', 8, 'ipv4'); +LOOPBACK_HOSTS.addAddress('::1', 'ipv6'); +LOOPBACK_HOSTS.addSubnet('::ffff:127.0.0.0', 104, 'ipv6'); + +function isProviderLoopbackHostname(hostname: string): boolean { + const normalized = hostname + .trim() + .toLowerCase() + .replace(/^\[(.*)\]$/, '$1'); + if (normalized === 'localhost') return true; + if (net.isIPv4(normalized)) return LOOPBACK_HOSTS.check(normalized, 'ipv4'); + if (net.isIPv6(normalized)) return LOOPBACK_HOSTS.check(normalized, 'ipv6'); + return false; +} + +/** Admit a credential-bearing provider URL before a request can send its first byte. */ +export function requireAuthenticatedProviderEndpoint(endpoint: string | URL): URL { + const url = new URL(endpoint); + if ( + url.username || + url.password || + (url.protocol !== 'https:' && + !(url.protocol === 'http:' && isProviderLoopbackHostname(url.hostname))) + ) { + throw new AppError('INVALID_ARGS', 'Provider endpoint must use HTTPS or loopback HTTP.', { + reason: PROVIDER_RESPONSE_ADMISSION_REASONS.credentialEndpointUnsafe.reason, + endpoint: url.origin, + }); + } + return url; +} + export function trimLeadingSlash(value: string): string { let firstNonSlash = 0; while (firstNonSlash < value.length && value.charCodeAt(firstNonSlash) === 47) { @@ -74,6 +115,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 Buffer.concat(chunks, bytes).toString('utf8'); + bytes += value.byteLength; + if (bytes > MAX_PROVIDER_RESPONSE_BYTES) { + throw new AppError('COMMAND_FAILED', 'Provider response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_ADMISSION_REASONS.responseTooLarge.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, @@ -126,17 +193,19 @@ export async function postHubAppUpload( }, signal?: AbortSignal, ): Promise { + const endpoint = requireAuthenticatedProviderEndpoint(options.endpoint); const timeoutSignal = AbortSignal.timeout(HUB_APP_UPLOAD_TIMEOUT_MS); let response: Response; let json: unknown; try { - response = await fetch(options.endpoint, { + response = await fetch(endpoint, { method: 'POST', headers: { ...agentDeviceRequestHeaders(options.clientVersion), Authorization: basicAuthHeader(options.auth), }, body: form, + redirect: 'error', signal: signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal, }); json = await readProviderJsonBody(response); @@ -260,15 +329,17 @@ export async function fetchProviderVerificationJson( hints: ProviderJsonFailureHints; }, ): Promise { + const admittedEndpoint = options.auth ? requireAuthenticatedProviderEndpoint(endpoint) : endpoint; const { service, unauthorizedHint, networkHint } = options.hints; const serviceHint = `Retry connect or check the ${service} service status.`; try { - const response = await fetch(endpoint, { + const response = await fetch(admittedEndpoint, { headers: { ...agentDeviceRequestHeaders(options.clientVersion), ...(options.auth ? { Authorization: basicAuthHeader(options.auth) } : {}), }, signal: AbortSignal.timeout(PROVIDER_API_TIMEOUT_MS), + redirect: 'error', }); if (!response.ok) { const unauthorized = response.status === 401 || response.status === 403; @@ -313,15 +384,17 @@ export async function fetchProviderSessionDetails( service: string; }, ): Promise> { + const admittedEndpoint = requireAuthenticatedProviderEndpoint(endpoint); let response: Response; let json: unknown; try { - response = await fetch(endpoint, { + response = await fetch(admittedEndpoint, { headers: { ...agentDeviceRequestHeaders(options.clientVersion), Authorization: basicAuthHeader(options.auth), }, signal: AbortSignal.timeout(PROVIDER_API_TIMEOUT_MS), + redirect: 'error', }); json = await readProviderJsonBody(response); } catch (error) { @@ -347,7 +420,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-ios-runner-products.test.ts b/src/core/interactors/limrun-ios-runner-products.test.ts index 3e5e1df1dee..3feeddcd0ef 100644 --- a/src/core/interactors/limrun-ios-runner-products.test.ts +++ b/src/core/interactors/limrun-ios-runner-products.test.ts @@ -240,10 +240,10 @@ for (const bindAddress of ['0.0.0.0', 'localhost', '', '::1']) { test('refuses release bytes with a mismatched checksum before extracting or deploying them', async () => { const urls: string[] = []; - vi.stubGlobal('fetch', async (url: string) => { - urls.push(url); + vi.stubGlobal('fetch', async (url: URL) => { + urls.push(url.href); return new Response( - url.endsWith('.json') + url.href.endsWith('.json') ? JSON.stringify({ version: '0.1.0', platform_target: 'iphonesimulator', @@ -293,7 +293,9 @@ test('a Watch lease rejects an iPhone manifest before downloading its runner', a ).rejects.toThrow('Invalid watchsimulator runner release manifest'); expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenCalledWith( - expect.stringContaining('/agent-device-watchos-runner-0.1.0.manifest.json'), + expect.objectContaining({ + href: expect.stringContaining('/agent-device-watchos-runner-0.1.0.manifest.json'), + }), expect.anything(), ); }); diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index 324128028c2..f9859e60ee7 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -49,6 +49,39 @@ test('streams the served file to disk with the bearer token the caller supplied' expect(fs.readFileSync(destinationPath, 'utf8')).toBe('ftypisom-payload'); }); +test('refuses a provider-supplied URL outside the authenticated instance origin', async () => { + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + fs.writeFileSync(destinationPath, 'stale recording'); + await expect( + downloadLimrunFile({ + url: 'https://other.example/recording', + expectedOrigin: 'https://instance.example', + headers: { Authorization: 'Bearer instance-token' }, + destinationPath, + timeoutMs: 5_000, + }), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'limrun_download_unsafe_url' }, + }); + expect(fs.existsSync(destinationPath)).toBe(false); +}); + +test('refuses a recording larger than the download limit before writing it', async () => { + const url = await serve((_request, response) => { + response.writeHead(200, { 'content-length': String(512 * 1024 * 1024 + 1) }); + response.end('not sent'); + }); + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + await expect( + downloadLimrunFile({ url, headers: {}, destinationPath, timeoutMs: 5_000 }), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'limrun_download_too_large' }, + }); + expect(fs.existsSync(destinationPath)).toBe(false); +}); + test('a non-2xx answer is a typed failure carrying the status and no file is left behind', async () => { const url = await serve((_request, response) => { response.writeHead(404); diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index de486705076..401e985f27f 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; -import { Readable } from 'node:stream'; +import { Readable, Transform } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import type { ReadableStream as WebReadableStream } from 'node:stream/web'; import { @@ -9,8 +9,10 @@ import { type ReasonTable, } from '@agent-device/kernel/errors'; import type { LimrunFileDownload } from '@agent-device/provider-limrun'; +import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; const RESPONSE_BODY_PREVIEW_BYTES = 500; +const MAX_LIMRUN_DOWNLOAD_BYTES = 512 * 1024 * 1024; // Why a Limrun file download did not land. The destination is removed on every failure, so each row // means "retry from the same URL", and `limrun_download_failed` adds that the transport itself broke. @@ -21,6 +23,10 @@ const LIMRUN_DOWNLOAD_REASONS = { timeout: { reason: 'limrun_download_timeout' }, // The transfer broke for a reason the service never answered with, kept in `details.cause`. failed: { reason: 'limrun_download_failed' }, + // The provider supplied an invalid, insecure, or cross-origin download URL. + unsafeUrl: { reason: 'limrun_download_unsafe_url' }, + // The downloaded response exceeds the file-size budget. + tooLarge: { reason: 'limrun_download_too_large' }, } as const satisfies ReasonTable<'limrun'>; /** @@ -32,20 +38,46 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise MAX_LIMRUN_DOWNLOAD_BYTES) { + throw new AppError('COMMAND_FAILED', 'Limrun download exceeds the size limit', { + reason: LIMRUN_DOWNLOAD_REASONS.tooLarge.reason, + limitBytes: MAX_LIMRUN_DOWNLOAD_BYTES, + }); + } if (!response.body) { throw new AppError('COMMAND_FAILED', 'Limrun download returned no body', { url: options.url, }); } + let bytes = 0; + const limit = new Transform({ + transform(chunk: Buffer, _encoding, callback) { + bytes += chunk.byteLength; + if (bytes > MAX_LIMRUN_DOWNLOAD_BYTES) { + callback( + new AppError('COMMAND_FAILED', 'Limrun download exceeds the size limit', { + reason: LIMRUN_DOWNLOAD_REASONS.tooLarge.reason, + limitBytes: MAX_LIMRUN_DOWNLOAD_BYTES, + }), + ); + return; + } + callback(null, chunk); + }, + }); await pipeline( Readable.fromWeb(response.body as WebReadableStream), + limit, fs.createWriteStream(options.destinationPath), { signal }, ); @@ -55,6 +87,30 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise { return new AppError('COMMAND_FAILED', `Limrun download failed with HTTP ${response.status}`, { url: options.url, diff --git a/test/integration/provider-scenarios/cloud-webdriver-test-server.ts b/test/integration/provider-scenarios/cloud-webdriver-test-server.ts index a1265a6c75b..f3b1d90628a 100644 --- a/test/integration/provider-scenarios/cloud-webdriver-test-server.ts +++ b/test/integration/provider-scenarios/cloud-webdriver-test-server.ts @@ -32,7 +32,7 @@ export type CloudWebDriverTestResponse = { export abstract class CloudWebDriverTestServer { readonly calls: CloudWebDriverHttpCall[] = []; // fallow-ignore-next-line unused-class-member - readonly url = 'http://cloud-webdriver.test'; + readonly url = 'https://cloud-webdriver.test'; protected abstract respond(call: CloudWebDriverHttpCall): CloudWebDriverTestResponse; diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 4bd8765a666..f38b9ed42dc 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -833,6 +833,8 @@ These reasons can come from more than one command. | `limrun_download_http_error` | The service answered the download with an error status; `details.statusCode` and `details.body` carry its reply. | | `limrun_download_timeout` | The download passed its deadline; `details.timeoutMs` is that deadline. | | `limrun_download_failed` | The transfer broke for a reason the service never answered with, kept in `details.cause`. | +| `limrun_download_unsafe_url` | The provider supplied an invalid, insecure, or cross-origin download URL. | +| `limrun_download_too_large` | The downloaded response exceeds the file-size budget. | ### Limrun provider @@ -1100,3 +1102,5 @@ These reasons can come from more than one command. | `hub_app_upload_timeout` | The app upload to the provider's storage did not answer within its own deadline. | | `hub_app_upload_transport_failed` | The app upload to the provider's storage never completed its transport. | | `provider_app_cwd_missing` | `--provider-app` is a relative path and the request names no working directory to resolve it in. | +| `provider_credential_endpoint_unsafe` | A credential-bearing provider endpoint is neither HTTPS nor loopback HTTP. | +| `provider_response_too_large` | A provider answered with more bytes than the response budget allows. | From e9c71d086ae8a8a35ad62c5030db520678e5522a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:07:47 +0100 Subject: [PATCH 02/19] fix(providers): require origin fences for authenticated downloads --- src/core/interactors/limrun-ios-files.ts | 2 ++ src/core/limrun-download-file.test.ts | 16 ++++++++++++++++ src/core/limrun-download-file.ts | 4 ++++ 3 files changed, 22 insertions(+) diff --git a/src/core/interactors/limrun-ios-files.ts b/src/core/interactors/limrun-ios-files.ts index 9ad197b71d6..8c7fea78747 100644 --- a/src/core/interactors/limrun-ios-files.ts +++ b/src/core/interactors/limrun-ios-files.ts @@ -85,6 +85,7 @@ export function createLimrunSimulatorFiles( copyToHost: async (input) => { await downloadLimrunFile({ url: urlFor('files', input.sourcePath, input).href, + expectedOrigin: new URL(session.apiUrl).origin, headers: { Authorization: `Bearer ${session.token}` }, destinationPath: input.destinationPath, timeoutMs: input.timeoutMs, @@ -188,6 +189,7 @@ export async function readLimrunAppInfo( }).toString(); await downloadLimrunFile({ url: url.href, + expectedOrigin: new URL(access.apiUrl).origin, headers: { Authorization: `Bearer ${access.token}` }, destinationPath, timeoutMs, diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index f9859e60ee7..ae157d3cc6e 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -67,6 +67,22 @@ test('refuses a provider-supplied URL outside the authenticated instance origin' expect(fs.existsSync(destinationPath)).toBe(false); }); +test('requires an origin fence whenever a download carries authorization', async () => { + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + await expect( + downloadLimrunFile({ + url: 'https://instance.example/recording', + headers: { authorization: 'Bearer instance-token' }, + destinationPath, + timeoutMs: 5_000, + }), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'limrun_download_unsafe_url' }, + }); + expect(fs.existsSync(destinationPath)).toBe(false); +}); + test('refuses a recording larger than the download limit before writing it', async () => { const url = await serve((_request, response) => { response.writeHead(200, { 'content-length': String(512 * 1024 * 1024 + 1) }); diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index 401e985f27f..3ed298789c9 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -96,11 +96,15 @@ function requireLimrunDownloadUrl(options: LimrunFileDownload): URL { reason: LIMRUN_DOWNLOAD_REASONS.unsafeUrl.reason, }); } + const carriesAuthorization = Object.keys(options.headers).some( + (name) => name.toLowerCase() === 'authorization', + ); if ( url.username || url.password || (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHostname(url.hostname))) || + (carriesAuthorization && options.expectedOrigin === undefined) || (options.expectedOrigin !== undefined && url.origin !== options.expectedOrigin) ) { throw new AppError('COMMAND_FAILED', 'Limrun download URL is not admitted', { From f3378aca8868a2e001ab3d9458ffaaf99dfd046b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:13:08 +0100 Subject: [PATCH 03/19] fix(providers): bound Limrun control responses --- .../interactors/limrun-http-response.test.ts | 17 ++++++++++ src/core/interactors/limrun-http-response.ts | 33 +++++++++++++++++++ src/core/interactors/limrun-ios-files.ts | 7 ++-- .../interactors/limrun-ios-runner-products.ts | 3 +- src/core/interactors/limrun-ios-runner.ts | 6 +++- 5 files changed, 62 insertions(+), 4 deletions(-) create mode 100644 src/core/interactors/limrun-http-response.test.ts create mode 100644 src/core/interactors/limrun-http-response.ts 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..38f67c72672 --- /dev/null +++ b/src/core/interactors/limrun-http-response.test.ts @@ -0,0 +1,17 @@ +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( + 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 }, + }); +}); diff --git a/src/core/interactors/limrun-http-response.ts b/src/core/interactors/limrun-http-response.ts new file mode 100644 index 00000000000..1fdf85395b7 --- /dev/null +++ b/src/core/interactors/limrun-http-response.ts @@ -0,0 +1,33 @@ +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; + +const MAX_LIMRUN_CONTROL_RESPONSE_BYTES = 32 * 1024 * 1024; +const LIMRUN_CONTROL_RESPONSE_REASONS = { + tooLarge: { reason: 'provider_response_too_large' }, +} as const satisfies ReasonTable<'limrun'>; + +export async function readLimrunControlText(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 Buffer.concat(chunks, bytes).toString('utf8'); + bytes += value.byteLength; + if (bytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) { + throw new AppError('COMMAND_FAILED', 'Limrun response exceeds the size limit.', { + reason: LIMRUN_CONTROL_RESPONSE_REASONS.tooLarge.reason, + limitBytes: MAX_LIMRUN_CONTROL_RESPONSE_BYTES, + }); + } + chunks.push(value); + } + } finally { + void reader.cancel().catch(() => {}); + } +} + +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 8c7fea78747..07467108688 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']; @@ -96,7 +97,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 { @@ -142,7 +145,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.ts b/src/core/interactors/limrun-ios-runner.ts index d906dc8124f..94540b5d6ca 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, + ).catch(() => undefined), }, ); if (result.status === 409) lastConflict = failure; From 53eaadbf86bdcb567d86ef42306a80aba42c4678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:25:43 +0100 Subject: [PATCH 04/19] fix(providers): satisfy response boundary gates --- .../interactors/limrun-http-response.test.ts | 10 +++------ src/core/interactors/limrun-http-response.ts | 22 ++++++++++++------- src/core/interactors/limrun-ios-runner.ts | 7 +++--- 3 files changed, 20 insertions(+), 19 deletions(-) diff --git a/src/core/interactors/limrun-http-response.test.ts b/src/core/interactors/limrun-http-response.test.ts index 38f67c72672..2f4097d9de3 100644 --- a/src/core/interactors/limrun-http-response.test.ts +++ b/src/core/interactors/limrun-http-response.test.ts @@ -2,13 +2,9 @@ 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( - new ReadableStream({ - start(controller) { - controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)); - }, - }), - ); + const response = new Response('{}', { + headers: { 'content-length': String(32 * 1024 * 1024 + 1) }, + }); await expect(readLimrunControlJson(response)).rejects.toMatchObject({ code: 'COMMAND_FAILED', diff --git a/src/core/interactors/limrun-http-response.ts b/src/core/interactors/limrun-http-response.ts index 1fdf85395b7..915c859c7d3 100644 --- a/src/core/interactors/limrun-http-response.ts +++ b/src/core/interactors/limrun-http-response.ts @@ -1,11 +1,13 @@ -import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { AppError } from '@agent-device/kernel/errors'; const MAX_LIMRUN_CONTROL_RESPONSE_BYTES = 32 * 1024 * 1024; -const LIMRUN_CONTROL_RESPONSE_REASONS = { - tooLarge: { reason: 'provider_response_too_large' }, -} as const satisfies ReasonTable<'limrun'>; +const PROVIDER_RESPONSE_TOO_LARGE = 'provider_response_too_large'; export async function readLimrunControlText(response: Response): Promise { + const declaredBytes = Number(response.headers.get('content-length')); + if (Number.isFinite(declaredBytes) && declaredBytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) { + throw responseTooLarge(); + } if (!response.body) return ''; const reader = response.body.getReader(); const chunks: Uint8Array[] = []; @@ -16,10 +18,7 @@ export async function readLimrunControlText(response: Response): Promise if (done) return Buffer.concat(chunks, bytes).toString('utf8'); bytes += value.byteLength; if (bytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) { - throw new AppError('COMMAND_FAILED', 'Limrun response exceeds the size limit.', { - reason: LIMRUN_CONTROL_RESPONSE_REASONS.tooLarge.reason, - limitBytes: MAX_LIMRUN_CONTROL_RESPONSE_BYTES, - }); + throw responseTooLarge(); } chunks.push(value); } @@ -28,6 +27,13 @@ export async function readLimrunControlText(response: Response): Promise } } +function responseTooLarge(): AppError { + return new AppError('COMMAND_FAILED', 'Limrun response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_TOO_LARGE, + 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-runner.ts b/src/core/interactors/limrun-ios-runner.ts index 94540b5d6ca..f2407fd9081 100644 --- a/src/core/interactors/limrun-ios-runner.ts +++ b/src/core/interactors/limrun-ios-runner.ts @@ -188,10 +188,9 @@ export async function createLimrunIosRunner( `Limrun XCTest launch failed (${result.status})`, { status: result.status, - response: await awaitWithSignal( - readLimrunControlText(result), - launchSignal, - ).catch(() => undefined), + response: await awaitWithSignal(readLimrunControlText(result), launchSignal).catch( + () => undefined, + ), }, ); if (result.status === 409) lastConflict = failure; From e1cfdf3789710ebf8ef147b750607dfcbd60f915 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:32:33 +0100 Subject: [PATCH 05/19] fix(providers): share response failure vocabulary --- packages/contracts/package.json | 4 ++++ packages/contracts/src/provider-response-reasons.ts | 7 +++++++ packages/provider-webdriver/src/webdriver-utils.ts | 5 ++--- src/core/interactors/limrun-http-response.ts | 4 ++-- src/core/interactors/limrun-ios-runner.test.ts | 12 +++++++----- 5 files changed, 22 insertions(+), 10 deletions(-) create mode 100644 packages/contracts/src/provider-response-reasons.ts diff --git a/packages/contracts/package.json b/packages/contracts/package.json index d090b823ad7..a251c8883a4 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -384,6 +384,10 @@ "types": "./src/platform-runtime-unavailable.ts", "default": "./src/platform-runtime-unavailable.ts" }, + "./provider-response-reasons": { + "types": "./src/provider-response-reasons.ts", + "default": "./src/provider-response-reasons.ts" + }, "./runtime-contract": { "types": "./src/runtime-contract.ts", "default": "./src/runtime-contract.ts" diff --git a/packages/contracts/src/provider-response-reasons.ts b/packages/contracts/src/provider-response-reasons.ts new file mode 100644 index 00000000000..d20d7dc1093 --- /dev/null +++ b/packages/contracts/src/provider-response-reasons.ts @@ -0,0 +1,7 @@ +import type { ReasonTable } from '@agent-device/kernel/errors'; + +/** 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'>; diff --git a/packages/provider-webdriver/src/webdriver-utils.ts b/packages/provider-webdriver/src/webdriver-utils.ts index 1cfc623b3e9..a3f33f544d6 100644 --- a/packages/provider-webdriver/src/webdriver-utils.ts +++ b/packages/provider-webdriver/src/webdriver-utils.ts @@ -12,6 +12,7 @@ import { PROVIDER_DEVICE_ORIENTATIONS, type ProviderDeviceOrientation, } from '@agent-device/contracts/remote'; +import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/provider-response-reasons'; import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors'; import { agentDeviceRequestHeaders } from './request-headers.ts'; @@ -46,8 +47,6 @@ export function basicAuthHeader(credentials: { username: string; accessKey: stri const PROVIDER_RESPONSE_ADMISSION_REASONS = { // A credential-bearing provider endpoint is neither HTTPS nor loopback HTTP. credentialEndpointUnsafe: { reason: 'provider_credential_endpoint_unsafe' }, - // A provider answered with more bytes than the response budget allows. - responseTooLarge: { reason: 'provider_response_too_large' }, } as const satisfies ReasonTable<'webdriver provider'>; const LOOPBACK_HOSTS = new net.BlockList(); @@ -130,7 +129,7 @@ export async function readProviderTextBody(response: Response): Promise bytes += value.byteLength; if (bytes > MAX_PROVIDER_RESPONSE_BYTES) { throw new AppError('COMMAND_FAILED', 'Provider response exceeds the size limit.', { - reason: PROVIDER_RESPONSE_ADMISSION_REASONS.responseTooLarge.reason, + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, limitBytes: MAX_PROVIDER_RESPONSE_BYTES, }); } diff --git a/src/core/interactors/limrun-http-response.ts b/src/core/interactors/limrun-http-response.ts index 915c859c7d3..f58968b5949 100644 --- a/src/core/interactors/limrun-http-response.ts +++ b/src/core/interactors/limrun-http-response.ts @@ -1,7 +1,7 @@ import { AppError } from '@agent-device/kernel/errors'; +import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/provider-response-reasons'; const MAX_LIMRUN_CONTROL_RESPONSE_BYTES = 32 * 1024 * 1024; -const PROVIDER_RESPONSE_TOO_LARGE = 'provider_response_too_large'; export async function readLimrunControlText(response: Response): Promise { const declaredBytes = Number(response.headers.get('content-length')); @@ -29,7 +29,7 @@ export async function readLimrunControlText(response: Response): Promise function responseTooLarge(): AppError { return new AppError('COMMAND_FAILED', 'Limrun response exceeds the size limit.', { - reason: PROVIDER_RESPONSE_TOO_LARGE, + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, limitBytes: MAX_LIMRUN_CONTROL_RESPONSE_BYTES, }); } diff --git a/src/core/interactors/limrun-ios-runner.test.ts b/src/core/interactors/limrun-ios-runner.test.ts index d39348077a9..cfbdc3f648e 100644 --- a/src/core/interactors/limrun-ios-runner.test.ts +++ b/src/core/interactors/limrun-ios-runner.test.ts @@ -140,12 +140,13 @@ test('a stalled rejection body respects the launch deadline and does not claim t const readStarted = new Promise((resolve) => { markReadStarted = resolve; }); - const readText = Response.prototype.text; + let launchRequested = () => false; + const read = ReadableStreamDefaultReader.prototype.read; const responseBody = vi - .spyOn(Response.prototype, 'text') - .mockImplementation(function (this: Response) { - if (this.status === 409) markReadStarted(); - return readText.call(this); + .spyOn(ReadableStreamDefaultReader.prototype, 'read') + .mockImplementation(function (this: ReadableStreamDefaultReader) { + if (launchRequested()) markReadStarted(); + return read.call(this); }); const realTimeout = AbortSignal.timeout.bind(AbortSignal); const timer = vi @@ -154,6 +155,7 @@ test('a stalled rejection body respects the launch deadline and does not claim t try { const options = { launchStatus: 409, holdLaunchErrorBody: true }; const f = await fixture(options); + launchRequested = () => f.requests.some((request) => request.endsWith('/xctest/run')); const prepare = () => f.runner.applicationTools.prewarmRunnerSession( f.device, From 2c503f0644f85477ad9419dbcd397d194f142601 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:33:39 +0100 Subject: [PATCH 06/19] fix(providers): cancel stalled Limrun response reads --- src/core/interactors/limrun-http-response.ts | 10 +++++++++- src/core/interactors/limrun-ios-runner.ts | 4 +--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/core/interactors/limrun-http-response.ts b/src/core/interactors/limrun-http-response.ts index f58968b5949..aa06ba21d89 100644 --- a/src/core/interactors/limrun-http-response.ts +++ b/src/core/interactors/limrun-http-response.ts @@ -3,18 +3,25 @@ import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/provider-resp const MAX_LIMRUN_CONTROL_RESPONSE_BYTES = 32 * 1024 * 1024; -export async function readLimrunControlText(response: Response): Promise { +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) { 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 Buffer.concat(chunks, bytes).toString('utf8'); bytes += value.byteLength; if (bytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) { @@ -23,6 +30,7 @@ export async function readLimrunControlText(response: Response): Promise chunks.push(value); } } finally { + signal?.removeEventListener('abort', cancel); void reader.cancel().catch(() => {}); } } diff --git a/src/core/interactors/limrun-ios-runner.ts b/src/core/interactors/limrun-ios-runner.ts index f2407fd9081..90471525423 100644 --- a/src/core/interactors/limrun-ios-runner.ts +++ b/src/core/interactors/limrun-ios-runner.ts @@ -188,9 +188,7 @@ export async function createLimrunIosRunner( `Limrun XCTest launch failed (${result.status})`, { status: result.status, - response: await awaitWithSignal(readLimrunControlText(result), launchSignal).catch( - () => undefined, - ), + response: await readLimrunControlText(result, launchSignal).catch(() => undefined), }, ); if (result.status === 409) lastConflict = failure; From 930a769d155606d9f3978a53abd4a364412dc784 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:36:30 +0100 Subject: [PATCH 07/19] docs: regenerate provider response reasons --- website/docs/docs/error-reasons.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index f38b9ed42dc..07a34e728e3 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -903,6 +903,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 | @@ -1103,4 +1109,3 @@ These reasons can come from more than one command. | `hub_app_upload_transport_failed` | The app upload to the provider's storage never completed its transport. | | `provider_app_cwd_missing` | `--provider-app` is a relative path and the request names no working directory to resolve it in. | | `provider_credential_endpoint_unsafe` | A credential-bearing provider endpoint is neither HTTPS nor loopback HTTP. | -| `provider_response_too_large` | A provider answered with more bytes than the response budget allows. | From edbfdc0fd970d4de995f942878fa9d652cd13012 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:37:32 +0100 Subject: [PATCH 08/19] chore(gates): refresh contracts export snapshot --- scripts/layering/contracts-exports.snapshot.json | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/layering/contracts-exports.snapshot.json b/scripts/layering/contracts-exports.snapshot.json index eaabe50cbf0..fc4e724e742 100644 --- a/scripts/layering/contracts-exports.snapshot.json +++ b/scripts/layering/contracts-exports.snapshot.json @@ -94,6 +94,7 @@ "@agent-device/contracts/plugin-inventory", "@agent-device/contracts/progress", "@agent-device/contracts/provider-profile-fields", + "@agent-device/contracts/provider-response-reasons", "@agent-device/contracts/react-native-overlay", "@agent-device/contracts/record-runtime-execution", "@agent-device/contracts/recording", From 7bd574a12f49711bcb010691a7883ac465912f43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:44:19 +0100 Subject: [PATCH 09/19] test(providers): narrow stalled response observation --- .../interactors/limrun-ios-runner.fixtures.ts | 2 ++ .../interactors/limrun-ios-runner.test.ts | 24 +++++++------------ src/core/limrun-download-file.test.ts | 1 + 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/core/interactors/limrun-ios-runner.fixtures.ts b/src/core/interactors/limrun-ios-runner.fixtures.ts index 63cf72cfdf2..da4b3b615ea 100644 --- a/src/core/interactors/limrun-ios-runner.fixtures.ts +++ b/src/core/interactors/limrun-ios-runner.fixtures.ts @@ -57,6 +57,7 @@ export async function fixture( appleOs?: 'ios' | 'watchos'; launchStatus?: number; holdLaunchErrorBody?: boolean; + onLaunchErrorHeaders?: () => void; syncStatus?: number; holdSync?: boolean; holdReadiness?: boolean; @@ -189,6 +190,7 @@ export async function fixture( if (options.launchStatus) { response.writeHead(options.launchStatus); response.flushHeaders(); + options.onLaunchErrorHeaders?.(); if (!options.holdLaunchErrorBody) response.end('test run unavailable'); return; } diff --git a/src/core/interactors/limrun-ios-runner.test.ts b/src/core/interactors/limrun-ios-runner.test.ts index cfbdc3f648e..5586ccebef1 100644 --- a/src/core/interactors/limrun-ios-runner.test.ts +++ b/src/core/interactors/limrun-ios-runner.test.ts @@ -136,26 +136,21 @@ 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 markHeadersSent!: () => void; + const headersSent = new Promise((resolve) => { + markHeadersSent = resolve; }); - let launchRequested = () => false; - const read = ReadableStreamDefaultReader.prototype.read; - const responseBody = vi - .spyOn(ReadableStreamDefaultReader.prototype, 'read') - .mockImplementation(function (this: ReadableStreamDefaultReader) { - if (launchRequested()) markReadStarted(); - return read.call(this); - }); const realTimeout = AbortSignal.timeout.bind(AbortSignal); const timer = vi .spyOn(AbortSignal, 'timeout') .mockImplementation((ms) => (ms === 90_000 ? timeout.signal : realTimeout(ms))); try { - const options = { launchStatus: 409, holdLaunchErrorBody: true }; + const options = { + launchStatus: 409, + holdLaunchErrorBody: true, + onLaunchErrorHeaders: markHeadersSent, + }; const f = await fixture(options); - launchRequested = () => f.requests.some((request) => request.endsWith('/xctest/run')); const prepare = () => f.runner.applicationTools.prewarmRunnerSession( f.device, @@ -165,7 +160,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 headersSent; timeout.abort(new DOMException('Admission expired', 'TimeoutError')); await failed; timer.mockRestore(); @@ -174,7 +169,6 @@ test('a stalled rejection body respects the launch deadline and does not claim t expect(f.requests.filter((p) => p.endsWith('/xctest/run'))).toHaveLength(2); } finally { timer.mockRestore(); - responseBody.mockRestore(); } }); diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index ae157d3cc6e..0ed88c7d669 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -40,6 +40,7 @@ test('streams the served file to disk with the bearer token the caller supplied' await downloadLimrunFile({ url, + expectedOrigin: new URL(url).origin, headers: { Authorization: 'Bearer instance-token' }, destinationPath, timeoutMs: 5_000, From 1e8387f3793bc914e035d80323540ed89a4dc824 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:48:08 +0100 Subject: [PATCH 10/19] fix(providers): preserve observed Limrun rejection status --- src/core/interactors/limrun-ios-runner.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/core/interactors/limrun-ios-runner.ts b/src/core/interactors/limrun-ios-runner.ts index 90471525423..3094bafeff3 100644 --- a/src/core/interactors/limrun-ios-runner.ts +++ b/src/core/interactors/limrun-ios-runner.ts @@ -188,7 +188,10 @@ export async function createLimrunIosRunner( `Limrun XCTest launch failed (${result.status})`, { status: result.status, - response: await readLimrunControlText(result, launchSignal).catch(() => undefined), + response: await awaitWithSignal( + readLimrunControlText(result, launchSignal), + launchSignal, + ).catch(() => undefined), }, ); if (result.status === 409) lastConflict = failure; From 03aa32549fe047fb80905664a0d51fcd8f46b11c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:52:10 +0100 Subject: [PATCH 11/19] test(providers): await client-observed rejection body --- .../interactors/limrun-ios-runner.fixtures.ts | 2 -- .../interactors/limrun-ios-runner.test.ts | 22 +++++++++++-------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/src/core/interactors/limrun-ios-runner.fixtures.ts b/src/core/interactors/limrun-ios-runner.fixtures.ts index da4b3b615ea..63cf72cfdf2 100644 --- a/src/core/interactors/limrun-ios-runner.fixtures.ts +++ b/src/core/interactors/limrun-ios-runner.fixtures.ts @@ -57,7 +57,6 @@ export async function fixture( appleOs?: 'ios' | 'watchos'; launchStatus?: number; holdLaunchErrorBody?: boolean; - onLaunchErrorHeaders?: () => void; syncStatus?: number; holdSync?: boolean; holdReadiness?: boolean; @@ -190,7 +189,6 @@ export async function fixture( if (options.launchStatus) { response.writeHead(options.launchStatus); response.flushHeaders(); - options.onLaunchErrorHeaders?.(); if (!options.holdLaunchErrorBody) response.end('test run unavailable'); return; } diff --git a/src/core/interactors/limrun-ios-runner.test.ts b/src/core/interactors/limrun-ios-runner.test.ts index 5586ccebef1..59a203ec734 100644 --- a/src/core/interactors/limrun-ios-runner.test.ts +++ b/src/core/interactors/limrun-ios-runner.test.ts @@ -136,20 +136,23 @@ 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 markHeadersSent!: () => void; - const headersSent = new Promise((resolve) => { - markHeadersSent = resolve; + let markBodyRead!: () => void; + const bodyRead = new Promise((resolve) => { + markBodyRead = resolve; }); + const getBody = Object.getOwnPropertyDescriptor(Response.prototype, 'body')!.get!; + const responseBody = vi + .spyOn(Response.prototype, 'body', 'get') + .mockImplementation(function (this: Response) { + if (this.status === 409) markBodyRead(); + return getBody.call(this); + }); const realTimeout = AbortSignal.timeout.bind(AbortSignal); const timer = vi .spyOn(AbortSignal, 'timeout') .mockImplementation((ms) => (ms === 90_000 ? timeout.signal : realTimeout(ms))); try { - const options = { - launchStatus: 409, - holdLaunchErrorBody: true, - onLaunchErrorHeaders: markHeadersSent, - }; + const options = { launchStatus: 409, holdLaunchErrorBody: true }; const f = await fixture(options); const prepare = () => f.runner.applicationTools.prewarmRunnerSession( @@ -160,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 headersSent; + await bodyRead; timeout.abort(new DOMException('Admission expired', 'TimeoutError')); await failed; timer.mockRestore(); @@ -169,6 +172,7 @@ test('a stalled rejection body respects the launch deadline and does not claim t expect(f.requests.filter((p) => p.endsWith('/xctest/run'))).toHaveLength(2); } finally { timer.mockRestore(); + responseBody.mockRestore(); } }); From bd04eb315decabe9eaacefd5393736fd496c7f01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:57:24 +0100 Subject: [PATCH 12/19] test(providers): observe retry conflict body seam --- src/core/interactors/limrun-ios-runner.test.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/core/interactors/limrun-ios-runner.test.ts b/src/core/interactors/limrun-ios-runner.test.ts index 59a203ec734..50c37871fa0 100644 --- a/src/core/interactors/limrun-ios-runner.test.ts +++ b/src/core/interactors/limrun-ios-runner.test.ts @@ -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 { From 8b7110cf837ac3134c8d920a7c4a7c5b4a9edf01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 16:04:56 +0100 Subject: [PATCH 13/19] fix(providers): keep response reason in existing closure --- packages/contracts/package.json | 4 ---- packages/contracts/src/facades/remote.ts | 1 + packages/contracts/src/provider-response-reasons.ts | 7 ------- packages/contracts/src/remote-config-fields.ts | 7 +++++++ packages/provider-webdriver/src/webdriver-utils.ts | 2 +- scripts/layering/contracts-exports.snapshot.json | 1 - src/core/interactors/limrun-http-response.ts | 2 +- 7 files changed, 10 insertions(+), 14 deletions(-) delete mode 100644 packages/contracts/src/provider-response-reasons.ts diff --git a/packages/contracts/package.json b/packages/contracts/package.json index a251c8883a4..d090b823ad7 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -384,10 +384,6 @@ "types": "./src/platform-runtime-unavailable.ts", "default": "./src/platform-runtime-unavailable.ts" }, - "./provider-response-reasons": { - "types": "./src/provider-response-reasons.ts", - "default": "./src/provider-response-reasons.ts" - }, "./runtime-contract": { "types": "./src/runtime-contract.ts", "default": "./src/runtime-contract.ts" diff --git a/packages/contracts/src/facades/remote.ts b/packages/contracts/src/facades/remote.ts index 820d3c79b67..8eb8b474676 100644 --- a/packages/contracts/src/facades/remote.ts +++ b/packages/contracts/src/facades/remote.ts @@ -21,6 +21,7 @@ export { PROVIDER_DEVICE_TYPES, PROVIDER_PROFILE_FIELD_FLAG_ALIASES, PROVIDER_PROFILE_FIELD_FLAGS, + PROVIDER_RESPONSE_REASONS, } from '../remote-config-fields.ts'; export type { CloudProviderProfileFields, diff --git a/packages/contracts/src/provider-response-reasons.ts b/packages/contracts/src/provider-response-reasons.ts deleted file mode 100644 index d20d7dc1093..00000000000 --- a/packages/contracts/src/provider-response-reasons.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { ReasonTable } from '@agent-device/kernel/errors'; - -/** 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'>; diff --git a/packages/contracts/src/remote-config-fields.ts b/packages/contracts/src/remote-config-fields.ts index ba8bc2d19c7..b5cdb28effc 100644 --- a/packages/contracts/src/remote-config-fields.ts +++ b/packages/contracts/src/remote-config-fields.ts @@ -1,4 +1,5 @@ import type { DeviceTarget, PlatformSelector } from '@agent-device/kernel/device'; +import type { ReasonTable } from '@agent-device/kernel/errors'; import type { DaemonServerMode, DaemonTransportPreference, @@ -25,6 +26,12 @@ export type ProviderDeviceOrientation = (typeof PROVIDER_DEVICE_ORIENTATIONS)[nu export const PROVIDER_DEVICE_TYPES = ['real', 'virtual'] as const; export type ProviderDeviceType = (typeof PROVIDER_DEVICE_TYPES)[number]; +/** 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'>; + /** * How a client sends a remote command. `health` reads `/health` before each command RPC. `checked` * sends a standalone command on the checked RPC route, where the server refuses protocol skew diff --git a/packages/provider-webdriver/src/webdriver-utils.ts b/packages/provider-webdriver/src/webdriver-utils.ts index a3f33f544d6..6fe9980b194 100644 --- a/packages/provider-webdriver/src/webdriver-utils.ts +++ b/packages/provider-webdriver/src/webdriver-utils.ts @@ -10,9 +10,9 @@ import type { } from '@agent-device/contracts/device'; import { PROVIDER_DEVICE_ORIENTATIONS, + PROVIDER_RESPONSE_REASONS, type ProviderDeviceOrientation, } from '@agent-device/contracts/remote'; -import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/provider-response-reasons'; import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors'; import { agentDeviceRequestHeaders } from './request-headers.ts'; diff --git a/scripts/layering/contracts-exports.snapshot.json b/scripts/layering/contracts-exports.snapshot.json index fc4e724e742..eaabe50cbf0 100644 --- a/scripts/layering/contracts-exports.snapshot.json +++ b/scripts/layering/contracts-exports.snapshot.json @@ -94,7 +94,6 @@ "@agent-device/contracts/plugin-inventory", "@agent-device/contracts/progress", "@agent-device/contracts/provider-profile-fields", - "@agent-device/contracts/provider-response-reasons", "@agent-device/contracts/react-native-overlay", "@agent-device/contracts/record-runtime-execution", "@agent-device/contracts/recording", diff --git a/src/core/interactors/limrun-http-response.ts b/src/core/interactors/limrun-http-response.ts index aa06ba21d89..cd318af1e12 100644 --- a/src/core/interactors/limrun-http-response.ts +++ b/src/core/interactors/limrun-http-response.ts @@ -1,5 +1,5 @@ import { AppError } from '@agent-device/kernel/errors'; -import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/provider-response-reasons'; +import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/remote'; const MAX_LIMRUN_CONTROL_RESPONSE_BYTES = 32 * 1024 * 1024; From ba2d7f4702bdcc1381231be868c593f7bf96c79d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 17:57:01 +0100 Subject: [PATCH 14/19] fix: preserve anonymous Limrun release redirects and BOM decoding --- .../src/webdriver-utils.test.ts | 5 +++ .../provider-webdriver/src/webdriver-utils.ts | 2 +- .../interactors/limrun-http-response.test.ts | 5 +++ src/core/interactors/limrun-http-response.ts | 2 +- src/core/limrun-download-file.test.ts | 35 +++++++++++++++++++ src/core/limrun-download-file.ts | 11 +++--- 6 files changed, 54 insertions(+), 6 deletions(-) diff --git a/packages/provider-webdriver/src/webdriver-utils.test.ts b/packages/provider-webdriver/src/webdriver-utils.test.ts index 61c4511f84b..550a6086cc0 100644 --- a/packages/provider-webdriver/src/webdriver-utils.test.ts +++ b/packages/provider-webdriver/src/webdriver-utils.test.ts @@ -94,6 +94,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 6fe9980b194..1b7cfaf1b1b 100644 --- a/packages/provider-webdriver/src/webdriver-utils.ts +++ b/packages/provider-webdriver/src/webdriver-utils.ts @@ -125,7 +125,7 @@ export async function readProviderTextBody(response: Response): Promise try { while (true) { const { done, value } = await reader.read(); - if (done) return Buffer.concat(chunks, bytes).toString('utf8'); + 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.', { diff --git a/src/core/interactors/limrun-http-response.test.ts b/src/core/interactors/limrun-http-response.test.ts index 2f4097d9de3..d6609cfd5bc 100644 --- a/src/core/interactors/limrun-http-response.test.ts +++ b/src/core/interactors/limrun-http-response.test.ts @@ -11,3 +11,8 @@ test('stops an oversized Limrun control response before accepting its body', asy 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 index cd318af1e12..63382e6a99a 100644 --- a/src/core/interactors/limrun-http-response.ts +++ b/src/core/interactors/limrun-http-response.ts @@ -22,7 +22,7 @@ export async function readLimrunControlText( while (true) { const { done, value } = await reader.read(); signal?.throwIfAborted(); - if (done) return Buffer.concat(chunks, bytes).toString('utf8'); + if (done) return new TextDecoder().decode(Buffer.concat(chunks, bytes)); bytes += value.byteLength; if (bytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) { throw responseTooLarge(); diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index 0ed88c7d669..52392a5b03b 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -84,6 +84,41 @@ test('requires an origin fence whenever a download carries authorization', async expect(fs.existsSync(destinationPath)).toBe(false); }); +test('anonymous release downloads follow redirects while origin-fenced downloads refuse them', async () => { + const requests: string[] = []; + const url = await serve((request, response) => { + requests.push(request.url ?? ''); + if (request.url?.startsWith('/files')) { + response.writeHead(302, { location: '/release-asset' }); + response.end(); + return; + } + response.writeHead(200); + response.end('runner-archive'); + }); + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'runner.zip'); + + await downloadLimrunFile({ url, headers: {}, destinationPath, timeoutMs: 5_000 }); + expect(fs.readFileSync(destinationPath, 'utf8')).toBe('runner-archive'); + expect(requests).toEqual(['/files?name=recording.mp4', '/release-asset']); + + requests.length = 0; + await expect( + downloadLimrunFile({ + url, + expectedOrigin: new URL(url).origin, + headers: {}, + destinationPath, + timeoutMs: 5_000, + }), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'limrun_download_failed' }, + }); + expect(requests).toEqual(['/files?name=recording.mp4']); + expect(fs.existsSync(destinationPath)).toBe(false); +}); + test('refuses a recording larger than the download limit before writing it', async () => { const url = await serve((_request, response) => { response.writeHead(200, { 'content-length': String(512 * 1024 * 1024 + 1) }); diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index 3ed298789c9..d6085e00491 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -38,12 +38,12 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise { From a2fa5bbe2c5c54e6c1dd8ff1579c69e378513842 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:40:35 +0100 Subject: [PATCH 15/19] fix(providers): close credential and response boundaries --- packages/contracts/src/facades/remote.ts | 2 +- packages/contracts/src/provider-response.ts | 7 ++++ .../contracts/src/remote-config-fields.ts | 7 ---- .../provider-revyl/src/revyl-client.test.ts | 21 ++++++++++ packages/provider-revyl/src/revyl-client.ts | 8 +++- .../src/webdriver-transport.test.ts | 4 +- .../src/webdriver-transport.ts | 9 ++++- .../src/webdriver-utils.test.ts | 1 + .../provider-webdriver/src/webdriver-utils.ts | 13 ++++++- .../interactors/limrun-http-response.test.ts | 15 +++++++ src/core/interactors/limrun-http-response.ts | 1 + src/core/interactors/limrun-ios-files.test.ts | 9 +++++ src/core/interactors/limrun-ios-files.ts | 7 ++-- src/core/limrun-download-file.test.ts | 16 ++++++++ src/core/limrun-download-file.ts | 39 ++++++++++++------- 15 files changed, 128 insertions(+), 31 deletions(-) create mode 100644 packages/contracts/src/provider-response.ts diff --git a/packages/contracts/src/facades/remote.ts b/packages/contracts/src/facades/remote.ts index 8eb8b474676..9e115bfc557 100644 --- a/packages/contracts/src/facades/remote.ts +++ b/packages/contracts/src/facades/remote.ts @@ -21,8 +21,8 @@ export { PROVIDER_DEVICE_TYPES, PROVIDER_PROFILE_FIELD_FLAG_ALIASES, PROVIDER_PROFILE_FIELD_FLAGS, - PROVIDER_RESPONSE_REASONS, } from '../remote-config-fields.ts'; +export { PROVIDER_RESPONSE_REASONS } from '../provider-response.ts'; export type { CloudProviderProfileFields, DaemonRpcMode, diff --git a/packages/contracts/src/provider-response.ts b/packages/contracts/src/provider-response.ts new file mode 100644 index 00000000000..d20d7dc1093 --- /dev/null +++ b/packages/contracts/src/provider-response.ts @@ -0,0 +1,7 @@ +import type { ReasonTable } from '@agent-device/kernel/errors'; + +/** 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'>; diff --git a/packages/contracts/src/remote-config-fields.ts b/packages/contracts/src/remote-config-fields.ts index b5cdb28effc..ba8bc2d19c7 100644 --- a/packages/contracts/src/remote-config-fields.ts +++ b/packages/contracts/src/remote-config-fields.ts @@ -1,5 +1,4 @@ import type { DeviceTarget, PlatformSelector } from '@agent-device/kernel/device'; -import type { ReasonTable } from '@agent-device/kernel/errors'; import type { DaemonServerMode, DaemonTransportPreference, @@ -26,12 +25,6 @@ export type ProviderDeviceOrientation = (typeof PROVIDER_DEVICE_ORIENTATIONS)[nu export const PROVIDER_DEVICE_TYPES = ['real', 'virtual'] as const; export type ProviderDeviceType = (typeof PROVIDER_DEVICE_TYPES)[number]; -/** 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'>; - /** * How a client sends a remote command. `health` reads `/health` before each command RPC. `checked` * sends a standalone command on the checked RPC route, where the server refuses protocol skew diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index a91fd67d68f..7e3780c950b 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -46,6 +46,7 @@ test('rejects unsafe provider-supplied artifact URLs before an app upload', asyn 'http://169.254.169.254/upload', 'http://127.0.0.1:8/upload', 'https://127.0.0.1/upload', + 'https://localhost/upload', 'https://[fd00::1]/upload', 'https://user:pass@storage.example/upload', ]) { @@ -60,6 +61,26 @@ test('rejects unsafe provider-supplied artifact URLs before an app upload', asyn } }); +test('accepts an artifact URL on a configured HTTPS IP backend origin', async () => { + const client = createRevylClient({ + apiKey: 'test-key', + backendUrl: 'https://203.0.113.5:8443', + clientVersion: '0.0.0-test', + fetch: stubFetch(() => + jsonResponse({ + upload_url: 'https://203.0.113.5:8443/upload', + download_url: 'https://203.0.113.5:8443/download', + }), + ), + }); + const artifact = await client.createSessionArtifactUpload( + 'session-1', + 10, + 'application/octet-stream', + ); + assert.equal(artifact.upload_url, 'https://203.0.113.5:8443/upload'); +}); + 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 24b7f58b6c3..382f734d3d9 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -373,9 +373,13 @@ function requireRevylArtifactUrl(value: string, backendUrl: string): string { reason: REVYL_HTTP_REASONS.invalidProviderUrl.reason, }); } - const loopback = isLoopbackHostname(url.hostname) && url.origin === new URL(backendUrl).origin; + const sameBackend = url.origin === new URL(backendUrl).origin; const ipLiteral = isIP(url.hostname.replace(/^\[(.*)\]$/, '$1')) !== 0; - if (url.username || url.password || (!loopback && (url.protocol !== 'https:' || ipLiteral))) { + if ( + url.username || + url.password || + (!sameBackend && (url.protocol !== 'https:' || ipLiteral || isLoopbackHostname(url.hostname))) + ) { throw new AppError('COMMAND_FAILED', 'Revyl artifact URL is not admitted.', { reason: REVYL_HTTP_REASONS.invalidProviderUrl.reason, origin: url.origin, diff --git a/packages/provider-webdriver/src/webdriver-transport.test.ts b/packages/provider-webdriver/src/webdriver-transport.test.ts index 7ee6c8dd9fe..b5775da7ed7 100644 --- a/packages/provider-webdriver/src/webdriver-transport.test.ts +++ b/packages/provider-webdriver/src/webdriver-transport.test.ts @@ -55,7 +55,9 @@ test('WebDriver stops reading a response after its byte limit', async () => { await assert.rejects( transport.requestValue('GET', '/session/x/source'), (error: unknown) => - error instanceof AppError && error.details?.reason === 'provider_response_too_large', + error instanceof AppError && + error.details?.reason === 'provider_response_too_large' && + error.details?.dispatched === 'unknown', ); }); diff --git a/packages/provider-webdriver/src/webdriver-transport.ts b/packages/provider-webdriver/src/webdriver-transport.ts index 437a512975a..085c86947d8 100644 --- a/packages/provider-webdriver/src/webdriver-transport.ts +++ b/packages/provider-webdriver/src/webdriver-transport.ts @@ -278,7 +278,14 @@ export class WebDriverTransport { text: await readProviderTextBody(response), }; } catch (error) { - if (error instanceof AppError) throw 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 550a6086cc0..41f31eafbc8 100644 --- a/packages/provider-webdriver/src/webdriver-utils.test.ts +++ b/packages/provider-webdriver/src/webdriver-utils.test.ts @@ -56,6 +56,7 @@ test('credential-bearing provider endpoints reject cleartext hosts before fetch' 'http://127.0.0.1.evil.test/upload', 'ftp://example.test/upload', 'https://user:pass@example.test/upload', + 'not a url', ]) { assert.throws( () => requireAuthenticatedProviderEndpoint(endpoint), diff --git a/packages/provider-webdriver/src/webdriver-utils.ts b/packages/provider-webdriver/src/webdriver-utils.ts index 1b7cfaf1b1b..b6a1e3d4b3f 100644 --- a/packages/provider-webdriver/src/webdriver-utils.ts +++ b/packages/provider-webdriver/src/webdriver-utils.ts @@ -67,7 +67,14 @@ function isProviderLoopbackHostname(hostname: string): boolean { /** Admit a credential-bearing provider URL before a request can send its first byte. */ export function requireAuthenticatedProviderEndpoint(endpoint: string | URL): URL { - const url = new URL(endpoint); + let url: URL; + try { + url = new URL(endpoint); + } catch { + throw new AppError('INVALID_ARGS', 'Provider endpoint must use HTTPS or loopback HTTP.', { + reason: PROVIDER_RESPONSE_ADMISSION_REASONS.credentialEndpointUnsafe.reason, + }); + } if ( url.username || url.password || @@ -210,6 +217,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', @@ -338,7 +346,7 @@ export async function fetchProviderVerificationJson( ...(options.auth ? { Authorization: basicAuthHeader(options.auth) } : {}), }, signal: AbortSignal.timeout(PROVIDER_API_TIMEOUT_MS), - redirect: 'error', + redirect: options.auth ? 'error' : 'follow', }); if (!response.ok) { const unauthorized = response.status === 401 || response.status === 403; @@ -397,6 +405,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.`, diff --git a/src/core/interactors/limrun-http-response.test.ts b/src/core/interactors/limrun-http-response.test.ts index d6609cfd5bc..403aa59704c 100644 --- a/src/core/interactors/limrun-http-response.test.ts +++ b/src/core/interactors/limrun-http-response.test.ts @@ -12,6 +12,21 @@ test('stops an oversized Limrun control response before accepting its body', asy }); }); +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 index 63382e6a99a..0e2a1940ed3 100644 --- a/src/core/interactors/limrun-http-response.ts +++ b/src/core/interactors/limrun-http-response.ts @@ -10,6 +10,7 @@ export async function readLimrunControlText( 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 ''; diff --git a/src/core/interactors/limrun-ios-files.test.ts b/src/core/interactors/limrun-ios-files.test.ts index e8718dc0887..4704342e2a4 100644 --- a/src/core/interactors/limrun-ios-files.test.ts +++ b/src/core/interactors/limrun-ios-files.test.ts @@ -6,12 +6,21 @@ import { resolveIosSimulatorDeepLinkBundleId } from '@agent-device/platform-appl import { promises as fs } from 'node:fs'; import path from 'node:path'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; +import { AppError } from '@agent-device/kernel/errors'; const plist = (scheme: string) => Buffer.from( `CFBundleExecutableExampleCFBundleURLTypesCFBundleURLSchemes${scheme}`, ); +test('refuses a cleartext remote file API before creating bearer-backed operations', async () => { + const f = await fixture(); + f.session.apiUrl = 'http://remote.example.test/v1/ios_test/api'; + expect(() => createLimrunAppleToolProvider(f.session, new AbortController().signal)).toThrowError( + AppError, + ); +}); + test('remote app metadata resolves Expo and deep-link ownership and rejects duplicate claims', async () => { const f = await fixture({ containers: { diff --git a/src/core/interactors/limrun-ios-files.ts b/src/core/interactors/limrun-ios-files.ts index 07467108688..8e348203093 100644 --- a/src/core/interactors/limrun-ios-files.ts +++ b/src/core/interactors/limrun-ios-files.ts @@ -8,7 +8,7 @@ import { } from '@agent-device/platform-apple/tool-provider'; import type { LimrunRuntimeDependencies } from '@agent-device/provider-limrun'; import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; -import { downloadLimrunFile } from '../limrun-download-file.ts'; +import { downloadLimrunFile, requireLimrunApiUrl } from '../limrun-download-file.ts'; import { readLimrunControlJson } from './limrun-http-response.ts'; type Session = Parameters[0]; @@ -20,6 +20,7 @@ export function createLimrunSimulatorFiles( lifetime: AbortSignal, requestSignal?: AbortSignal, ): { simulatorFiles: Files; readInfoPlist: AppleToolProvider['simulatorApps']['readInfoPlist'] } { + const apiUrl = requireLimrunApiUrl(session.apiUrl); const signalFor = (signal?: AbortSignal) => AbortSignal.any( [lifetime, requestSignal, signal].filter((value): value is AbortSignal => Boolean(value)), @@ -54,7 +55,7 @@ export function createLimrunSimulatorFiles( } }; const urlFor = (route: string, name: string, container?: Container) => { - const url = new URL(`${session.apiUrl.replace(/\/$/, '')}/${route}`); + const url = new URL(`${apiUrl.href.replace(/\/$/, '')}/${route}`); url.searchParams.set(route === 'files/list' ? 'path' : 'name', name); if (container) { url.searchParams.set('bundleId', container.bundleId); @@ -86,7 +87,7 @@ export function createLimrunSimulatorFiles( copyToHost: async (input) => { await downloadLimrunFile({ url: urlFor('files', input.sourcePath, input).href, - expectedOrigin: new URL(session.apiUrl).origin, + expectedOrigin: apiUrl.origin, headers: { Authorization: `Bearer ${session.token}` }, destinationPath: input.destinationPath, timeoutMs: input.timeoutMs, diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index 52392a5b03b..0e917b1571a 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -84,6 +84,22 @@ test('requires an origin fence whenever a download carries authorization', async expect(fs.existsSync(destinationPath)).toBe(false); }); +test('requires an origin fence for any caller-supplied header', async () => { + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + await expect( + downloadLimrunFile({ + url: 'https://instance.example/recording', + headers: { 'X-API-Key': 'secret' }, + destinationPath, + timeoutMs: 5_000, + }), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'limrun_download_unsafe_url' }, + }); + expect(fs.existsSync(destinationPath)).toBe(false); +}); + test('anonymous release downloads follow redirects while origin-fenced downloads refuse them', async () => { const requests: string[] = []; const url = await serve((request, response) => { diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index d6085e00491..6146b0d4bf6 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -38,17 +38,18 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise MAX_LIMRUN_DOWNLOAD_BYTES) { + await response.body?.cancel().catch(() => {}); throw new AppError('COMMAND_FAILED', 'Limrun download exceeds the size limit', { reason: LIMRUN_DOWNLOAD_REASONS.tooLarge.reason, limitBytes: MAX_LIMRUN_DOWNLOAD_BYTES, @@ -89,33 +90,43 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise 0; + if ( + (carriesHeaders && options.expectedOrigin === undefined) || + (options.expectedOrigin !== undefined && url.origin !== options.expectedOrigin) + ) { + throw new AppError('COMMAND_FAILED', 'Limrun download URL is not admitted', { + reason: LIMRUN_DOWNLOAD_REASONS.unsafeUrl.reason, + origin: url.origin, + }); + } + return { url, carriesHeaders }; +} + +/** Admit a Limrun API URL before any request sends a bearer or caller-supplied header. */ +export function requireLimrunApiUrl(value: string): URL { let url: URL; try { - url = new URL(options.url); + url = new URL(value); } catch { - throw new AppError('COMMAND_FAILED', 'Limrun download URL is invalid', { + throw new AppError('COMMAND_FAILED', 'Limrun API URL is invalid', { reason: LIMRUN_DOWNLOAD_REASONS.unsafeUrl.reason, }); } - const carriesAuthorization = Object.keys(options.headers).some( - (name) => name.toLowerCase() === 'authorization', - ); if ( url.username || url.password || - (url.protocol !== 'https:' && - !(url.protocol === 'http:' && isLoopbackHostname(url.hostname))) || - (carriesAuthorization && options.expectedOrigin === undefined) || - (options.expectedOrigin !== undefined && url.origin !== options.expectedOrigin) + (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHostname(url.hostname))) ) { - throw new AppError('COMMAND_FAILED', 'Limrun download URL is not admitted', { + throw new AppError('COMMAND_FAILED', 'Limrun API URL is not admitted', { reason: LIMRUN_DOWNLOAD_REASONS.unsafeUrl.reason, origin: url.origin, }); } - return { url, carriesAuthorization }; + return url; } async function httpFailure(response: Response, options: LimrunFileDownload): Promise { From 80f12798ad622f7470af46d806e733a99704bad0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:55:38 +0100 Subject: [PATCH 16/19] fix(contracts): keep response reasons in remote facade --- packages/contracts/src/facades/remote.ts | 9 ++++++++- packages/contracts/src/provider-response.ts | 7 ------- 2 files changed, 8 insertions(+), 8 deletions(-) delete mode 100644 packages/contracts/src/provider-response.ts diff --git a/packages/contracts/src/facades/remote.ts b/packages/contracts/src/facades/remote.ts index 9e115bfc557..4b21458fed7 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,7 +24,12 @@ export { PROVIDER_PROFILE_FIELD_FLAG_ALIASES, PROVIDER_PROFILE_FIELD_FLAGS, } from '../remote-config-fields.ts'; -export { PROVIDER_RESPONSE_REASONS } from '../provider-response.ts'; + +/** Why a provider response was rejected before its body was accepted. */ +export const PROVIDER_RESPONSE_REASONS = { + tooLarge: { reason: 'provider_response_too_large' }, +} as const satisfies ReasonTable<'provider response'>; + export type { CloudProviderProfileFields, DaemonRpcMode, diff --git a/packages/contracts/src/provider-response.ts b/packages/contracts/src/provider-response.ts deleted file mode 100644 index d20d7dc1093..00000000000 --- a/packages/contracts/src/provider-response.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { ReasonTable } from '@agent-device/kernel/errors'; - -/** 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'>; From 6d637061426116c9dd8a2ed1b0af5cf38016334b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 21:00:26 +0100 Subject: [PATCH 17/19] docs(contracts): summarize provider response reason --- packages/contracts/src/facades/remote.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/contracts/src/facades/remote.ts b/packages/contracts/src/facades/remote.ts index 4b21458fed7..abf4b6a367c 100644 --- a/packages/contracts/src/facades/remote.ts +++ b/packages/contracts/src/facades/remote.ts @@ -27,6 +27,7 @@ export { /** 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'>; From 3ed35d7084ee9f1186f9f9d21f6a24ce6a7ab8a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 08:41:37 +0100 Subject: [PATCH 18/19] fix(providers): narrow response bounds to buffered bodies --- packages/provider-limrun/src/android.ts | 2 - .../src/device-session.test.ts | 4 - .../provider-limrun/src/device-session.ts | 2 - .../src/runtime-dependencies.ts | 2 - .../provider-revyl/src/revyl-client.test.ts | 40 ------- packages/provider-revyl/src/revyl-client.ts | 37 +------ .../src/webdriver-transport.test.ts | 13 --- .../src/webdriver-transport.ts | 8 +- .../src/webdriver-utils.test.ts | 32 ------ .../provider-webdriver/src/webdriver-utils.ts | 58 +--------- src/core/interactors/limrun-ios-files.test.ts | 9 -- src/core/interactors/limrun-ios-files.ts | 7 +- .../limrun-ios-runner-products.test.ts | 10 +- src/core/limrun-download-file.test.ts | 101 ------------------ src/core/limrun-download-file.ts | 78 +------------- .../cloud-webdriver-test-server.ts | 2 +- website/docs/docs/error-reasons.md | 3 - 17 files changed, 17 insertions(+), 391 deletions(-) diff --git a/packages/provider-limrun/src/android.ts b/packages/provider-limrun/src/android.ts index 344a1220de8..a66145d5f5e 100644 --- a/packages/provider-limrun/src/android.ts +++ b/packages/provider-limrun/src/android.ts @@ -41,7 +41,6 @@ type LimrunAndroidAdbSession = { platform: 'android'; lease: DeviceLease; instanceId: string; - readonly apiUrl: string; readonly ownership: LimrunInstanceOwnership; device: DeviceInfo; syncCache?: LimrunSyncCache; @@ -92,7 +91,6 @@ export async function createLimrunAndroidSession( platform: 'android', lease: options.lease, instanceId: options.instanceId, - apiUrl: options.apiUrl, ownership: options.ownership, device: options.device, client, diff --git a/packages/provider-limrun/src/device-session.test.ts b/packages/provider-limrun/src/device-session.test.ts index 6674b58ba5c..d45b03e3abd 100644 --- a/packages/provider-limrun/src/device-session.test.ts +++ b/packages/provider-limrun/src/device-session.test.ts @@ -97,7 +97,6 @@ test('iOS device session exposes reusable capabilities without its raw client', assert.deepEqual(downloadFile.mock.calls.at(-1), [ { url: 'https://ios.example/recording', - expectedOrigin: 'https://ios.example', headers: { Authorization: 'Bearer ios-instance-token' }, destinationPath: '/tmp/ios-recording.mp4', timeoutMs: 60_000, @@ -208,7 +207,6 @@ test('Android device session exposes semantic ADB capabilities without its raw c assert.deepEqual(downloadFile.mock.calls.at(-1), [ { url: 'https://android.example/recording', - expectedOrigin: 'https://android.example', headers: { Authorization: 'Bearer android-instance-token' }, destinationPath: '/tmp/android-recording.mp4', timeoutMs: 60_000, @@ -225,7 +223,6 @@ function iosSession(client: Record): LimrunIosSession { runner: testIosRunner, lease: lease('ios-instance'), instanceId: 'ios-instance', - apiUrl: 'https://ios.example/api', device: device('ios'), client, token: 'ios-instance-token', @@ -241,7 +238,6 @@ function androidSession( platform: 'android', lease: lease('android-instance'), instanceId: 'android-instance', - apiUrl: 'https://android.example/api', device: device('android'), client, adbProvider, diff --git a/packages/provider-limrun/src/device-session.ts b/packages/provider-limrun/src/device-session.ts index 1d027bf876b..3fa3adc750b 100644 --- a/packages/provider-limrun/src/device-session.ts +++ b/packages/provider-limrun/src/device-session.ts @@ -174,7 +174,6 @@ const ATTACHED_RECORDING_PERSIST = Object.freeze({ ttlSeconds: 48 * 60 * 60 }); function createRecordingOperations(session: { readonly client: LimrunRecordingClient; - readonly apiUrl: string; readonly token: string; readonly ownership: LimrunInstanceOwnership; readonly dependencies: { readonly host: Pick }; @@ -194,7 +193,6 @@ function createRecordingOperations(session: { downloadRecording: async (input: { downloadUrl: string; outPath: string }) => { await host.downloadFile({ url: input.downloadUrl, - expectedOrigin: new URL(session.apiUrl).origin, headers: { Authorization: `Bearer ${token}` }, destinationPath: input.outPath, timeoutMs: LIMRUN_RECORDING_DOWNLOAD_TIMEOUT_MS, diff --git a/packages/provider-limrun/src/runtime-dependencies.ts b/packages/provider-limrun/src/runtime-dependencies.ts index 23b47b764d3..fa81df773f5 100644 --- a/packages/provider-limrun/src/runtime-dependencies.ts +++ b/packages/provider-limrun/src/runtime-dependencies.ts @@ -157,8 +157,6 @@ export type LimrunAndroidRuntimeAdapter = { /** One authenticated HTTP download the host performs on the provider's behalf, bounded by `timeoutMs`. */ export type LimrunFileDownload = Readonly<{ url: string; - /** The instance API origin allowed to receive its bearer token. */ - expectedOrigin?: string; headers: Readonly>; destinationPath: string; timeoutMs: number; diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index 7e3780c950b..998a468bc7a 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -41,46 +41,6 @@ test('rejects an oversized provider answer before accepting its body', async () ); }); -test('rejects unsafe provider-supplied artifact URLs before an app upload', async () => { - for (const uploadUrl of [ - 'http://169.254.169.254/upload', - 'http://127.0.0.1:8/upload', - 'https://127.0.0.1/upload', - 'https://localhost/upload', - 'https://[fd00::1]/upload', - 'https://user:pass@storage.example/upload', - ]) { - const client = clientResponding(() => - jsonResponse({ upload_url: uploadUrl, download_url: 'https://storage.example/download' }), - ); - await assert.rejects( - client.createSessionArtifactUpload('session-1', 10, 'application/octet-stream'), - (error: unknown) => - error instanceof AppError && error.details?.reason === 'invalid_provider_url', - ); - } -}); - -test('accepts an artifact URL on a configured HTTPS IP backend origin', async () => { - const client = createRevylClient({ - apiKey: 'test-key', - backendUrl: 'https://203.0.113.5:8443', - clientVersion: '0.0.0-test', - fetch: stubFetch(() => - jsonResponse({ - upload_url: 'https://203.0.113.5:8443/upload', - download_url: 'https://203.0.113.5:8443/download', - }), - ), - }); - const artifact = await client.createSessionArtifactUpload( - 'session-1', - 10, - 'application/octet-stream', - ); - assert.equal(artifact.upload_url, 'https://203.0.113.5:8443/upload'); -}); - 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 382f734d3d9..1747c32b542 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -7,7 +7,6 @@ import { import { isRecord } from '@agent-device/kernel/record'; import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; import fs from 'node:fs'; -import { isIP } from 'node:net'; import { Readable } from 'node:stream'; import { setTimeout as sleep } from 'node:timers/promises'; import type { @@ -32,6 +31,7 @@ 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; @@ -292,21 +292,16 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { assertLifecycleAccepted('stop', response); return response; }, - async createSessionArtifactUpload(sessionId, fileSize, contentType, signal) { - const upload = await json({ + createSessionArtifactUpload(sessionId, fileSize, contentType, signal) { + return json({ method: 'POST', path: `/api/v1/execution/device-sessions/${encodeURIComponent(sessionId)}/artifacts/upload-url`, body: { file_size: fileSize, content_type: contentType }, route: 'session', ...(signal === undefined ? {} : { signal }), }); - return { - upload_url: requireRevylArtifactUrl(upload.upload_url, backendUrl), - download_url: requireRevylArtifactUrl(upload.download_url, backendUrl), - }; }, async uploadSessionArtifact(uploadUrl, file, contentType, signal) { - const admittedUrl = requireRevylArtifactUrl(uploadUrl, backendUrl); // Node streams a request body only in half-duplex mode, which the DOM `RequestInit` type omits. const init: RequestInit & { duplex: 'half' } = { method: 'PUT', @@ -319,7 +314,7 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { }; let response: Response; try { - response = await fetchImpl(admittedUrl, init); + response = await fetchImpl(uploadUrl, init); } catch (error) { throw new AppError( 'COMMAND_FAILED', @@ -364,30 +359,6 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { }); } -function requireRevylArtifactUrl(value: string, backendUrl: string): string { - let url: URL; - try { - url = new URL(value); - } catch { - throw new AppError('COMMAND_FAILED', 'Revyl artifact URL is invalid.', { - reason: REVYL_HTTP_REASONS.invalidProviderUrl.reason, - }); - } - const sameBackend = url.origin === new URL(backendUrl).origin; - const ipLiteral = isIP(url.hostname.replace(/^\[(.*)\]$/, '$1')) !== 0; - if ( - url.username || - url.password || - (!sameBackend && (url.protocol !== 'https:' || ipLiteral || isLoopbackHostname(url.hostname))) - ) { - throw new AppError('COMMAND_FAILED', 'Revyl artifact URL is not admitted.', { - reason: REVYL_HTTP_REASONS.invalidProviderUrl.reason, - origin: url.origin, - }); - } - return url.href; -} - async function sendOnce( backendUrl: string, fetchImpl: typeof fetch, diff --git a/packages/provider-webdriver/src/webdriver-transport.test.ts b/packages/provider-webdriver/src/webdriver-transport.test.ts index b5775da7ed7..8016db15b7b 100644 --- a/packages/provider-webdriver/src/webdriver-transport.test.ts +++ b/packages/provider-webdriver/src/webdriver-transport.test.ts @@ -26,19 +26,6 @@ afterEach(() => { globalThis.fetch = realFetch; }); -test('authenticated WebDriver refuses an insecure remote endpoint before sending credentials', () => { - assert.throws( - () => - new WebDriverTransport({ - clientVersion: '0.0.0-test', - endpoint: 'http://cloud-webdriver.test/wd/hub/', - auth: { username: 'user', accessKey: 'secret' }, - }), - (error: unknown) => - error instanceof AppError && error.details?.reason === 'provider_credential_endpoint_unsafe', - ); -}); - test('WebDriver stops reading a response after its byte limit', async () => { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', diff --git a/packages/provider-webdriver/src/webdriver-transport.ts b/packages/provider-webdriver/src/webdriver-transport.ts index 085c86947d8..6ec7dd25e42 100644 --- a/packages/provider-webdriver/src/webdriver-transport.ts +++ b/packages/provider-webdriver/src/webdriver-transport.ts @@ -4,7 +4,6 @@ import { agentDeviceRequestHeaders } from './request-headers.ts'; import { basicAuthHeader, readProviderTextBody, - requireAuthenticatedProviderEndpoint, trimLeadingSlash, withTrailingSlash, } from './webdriver-utils.ts'; @@ -147,11 +146,7 @@ export class WebDriverTransport { private readonly requestPolicy: ResolvedWebDriverRequestPolicy; constructor(options: WebDriverTransportOptions) { - this.endpoint = withTrailingSlash( - options.auth - ? requireAuthenticatedProviderEndpoint(options.endpoint) - : new URL(options.endpoint), - ); + this.endpoint = withTrailingSlash(new URL(options.endpoint)); this.headers = { ...agentDeviceRequestHeaders(options.clientVersion), ...(options.auth ? { Authorization: basicAuthHeader(options.auth) } : {}), @@ -265,7 +260,6 @@ export class WebDriverTransport { ...this.headers, }, body: payload === undefined ? undefined : JSON.stringify(payload), - redirect: 'error', signal, }); } catch (error) { diff --git a/packages/provider-webdriver/src/webdriver-utils.test.ts b/packages/provider-webdriver/src/webdriver-utils.test.ts index 41f31eafbc8..48358440e78 100644 --- a/packages/provider-webdriver/src/webdriver-utils.test.ts +++ b/packages/provider-webdriver/src/webdriver-utils.test.ts @@ -11,7 +11,6 @@ import { createHubUploadApp, postHubAppUpload, readFlag, - requireAuthenticatedProviderEndpoint, requireConnectFlag, requireConnectPlatform, requireEnv, @@ -50,43 +49,12 @@ const hub = { readAppReference: (body: unknown) => asOptionalRecord(body)?.ref as string | undefined, }; -test('credential-bearing provider endpoints reject cleartext hosts before fetch', async () => { - for (const endpoint of [ - 'http://example.test/upload', - 'http://127.0.0.1.evil.test/upload', - 'ftp://example.test/upload', - 'https://user:pass@example.test/upload', - 'not a url', - ]) { - assert.throws( - () => requireAuthenticatedProviderEndpoint(endpoint), - (error: unknown) => { - assert.ok(error instanceof AppError); - assert.equal(error.details?.reason, 'provider_credential_endpoint_unsafe'); - return true; - }, - ); - } - assert.equal(requireAuthenticatedProviderEndpoint('http://127.0.0.2/upload').protocol, 'http:'); - assert.equal(requireAuthenticatedProviderEndpoint('http://[::1]/upload').protocol, 'http:'); - let calls = 0; - globalThis.fetch = async () => { - calls += 1; - return new Response('{}'); - }; - await assert.rejects( - postHubAppUpload(new FormData(), { ...hub, endpoint: 'http://example.test/upload' }), - ); - assert.equal(calls, 0); -}); - test('the hub upload helper posts with credentials and returns the vendor reference', async () => { const form = new FormData(); globalThis.fetch = async (input, init) => { assert.equal(String(input), hub.endpoint); assert.equal(init?.method, 'POST'); assert.equal(init?.body, form); - assert.equal(init?.redirect, 'error'); const headers = init?.headers as Record; assert.equal(headers.Authorization, `Basic ${Buffer.from('user:key').toString('base64')}`); assert.equal(headers['x-agent-device-version'], '0.0.0-test'); diff --git a/packages/provider-webdriver/src/webdriver-utils.ts b/packages/provider-webdriver/src/webdriver-utils.ts index b6a1e3d4b3f..d584b958b9d 100644 --- a/packages/provider-webdriver/src/webdriver-utils.ts +++ b/packages/provider-webdriver/src/webdriver-utils.ts @@ -1,7 +1,6 @@ import fs from 'node:fs'; import { stat } from 'node:fs/promises'; import path from 'node:path'; -import net from 'node:net'; import type { CliFlags } from '@agent-device/contracts/command'; import type { LeaseLifecycleContext, @@ -44,51 +43,6 @@ export function basicAuthHeader(credentials: { username: string; accessKey: stri return `Basic ${Buffer.from(`${credentials.username}:${credentials.accessKey}`).toString('base64')}`; } -const PROVIDER_RESPONSE_ADMISSION_REASONS = { - // A credential-bearing provider endpoint is neither HTTPS nor loopback HTTP. - credentialEndpointUnsafe: { reason: 'provider_credential_endpoint_unsafe' }, -} as const satisfies ReasonTable<'webdriver provider'>; - -const LOOPBACK_HOSTS = new net.BlockList(); -LOOPBACK_HOSTS.addSubnet('127.0.0.0', 8, 'ipv4'); -LOOPBACK_HOSTS.addAddress('::1', 'ipv6'); -LOOPBACK_HOSTS.addSubnet('::ffff:127.0.0.0', 104, 'ipv6'); - -function isProviderLoopbackHostname(hostname: string): boolean { - const normalized = hostname - .trim() - .toLowerCase() - .replace(/^\[(.*)\]$/, '$1'); - if (normalized === 'localhost') return true; - if (net.isIPv4(normalized)) return LOOPBACK_HOSTS.check(normalized, 'ipv4'); - if (net.isIPv6(normalized)) return LOOPBACK_HOSTS.check(normalized, 'ipv6'); - return false; -} - -/** Admit a credential-bearing provider URL before a request can send its first byte. */ -export function requireAuthenticatedProviderEndpoint(endpoint: string | URL): URL { - let url: URL; - try { - url = new URL(endpoint); - } catch { - throw new AppError('INVALID_ARGS', 'Provider endpoint must use HTTPS or loopback HTTP.', { - reason: PROVIDER_RESPONSE_ADMISSION_REASONS.credentialEndpointUnsafe.reason, - }); - } - if ( - url.username || - url.password || - (url.protocol !== 'https:' && - !(url.protocol === 'http:' && isProviderLoopbackHostname(url.hostname))) - ) { - throw new AppError('INVALID_ARGS', 'Provider endpoint must use HTTPS or loopback HTTP.', { - reason: PROVIDER_RESPONSE_ADMISSION_REASONS.credentialEndpointUnsafe.reason, - endpoint: url.origin, - }); - } - return url; -} - export function trimLeadingSlash(value: string): string { let firstNonSlash = 0; while (firstNonSlash < value.length && value.charCodeAt(firstNonSlash) === 47) { @@ -199,19 +153,17 @@ export async function postHubAppUpload( }, signal?: AbortSignal, ): Promise { - const endpoint = requireAuthenticatedProviderEndpoint(options.endpoint); const timeoutSignal = AbortSignal.timeout(HUB_APP_UPLOAD_TIMEOUT_MS); let response: Response; let json: unknown; try { - response = await fetch(endpoint, { + response = await fetch(options.endpoint, { method: 'POST', headers: { ...agentDeviceRequestHeaders(options.clientVersion), Authorization: basicAuthHeader(options.auth), }, body: form, - redirect: 'error', signal: signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal, }); json = await readProviderJsonBody(response); @@ -336,17 +288,15 @@ export async function fetchProviderVerificationJson( hints: ProviderJsonFailureHints; }, ): Promise { - const admittedEndpoint = options.auth ? requireAuthenticatedProviderEndpoint(endpoint) : endpoint; const { service, unauthorizedHint, networkHint } = options.hints; const serviceHint = `Retry connect or check the ${service} service status.`; try { - const response = await fetch(admittedEndpoint, { + const response = await fetch(endpoint, { headers: { ...agentDeviceRequestHeaders(options.clientVersion), ...(options.auth ? { Authorization: basicAuthHeader(options.auth) } : {}), }, signal: AbortSignal.timeout(PROVIDER_API_TIMEOUT_MS), - redirect: options.auth ? 'error' : 'follow', }); if (!response.ok) { const unauthorized = response.status === 401 || response.status === 403; @@ -391,17 +341,15 @@ export async function fetchProviderSessionDetails( service: string; }, ): Promise> { - const admittedEndpoint = requireAuthenticatedProviderEndpoint(endpoint); let response: Response; let json: unknown; try { - response = await fetch(admittedEndpoint, { + response = await fetch(endpoint, { headers: { ...agentDeviceRequestHeaders(options.clientVersion), Authorization: basicAuthHeader(options.auth), }, signal: AbortSignal.timeout(PROVIDER_API_TIMEOUT_MS), - redirect: 'error', }); json = await readProviderJsonBody(response); } catch (error) { diff --git a/src/core/interactors/limrun-ios-files.test.ts b/src/core/interactors/limrun-ios-files.test.ts index 4704342e2a4..e8718dc0887 100644 --- a/src/core/interactors/limrun-ios-files.test.ts +++ b/src/core/interactors/limrun-ios-files.test.ts @@ -6,21 +6,12 @@ import { resolveIosSimulatorDeepLinkBundleId } from '@agent-device/platform-appl import { promises as fs } from 'node:fs'; import path from 'node:path'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; -import { AppError } from '@agent-device/kernel/errors'; const plist = (scheme: string) => Buffer.from( `CFBundleExecutableExampleCFBundleURLTypesCFBundleURLSchemes${scheme}`, ); -test('refuses a cleartext remote file API before creating bearer-backed operations', async () => { - const f = await fixture(); - f.session.apiUrl = 'http://remote.example.test/v1/ios_test/api'; - expect(() => createLimrunAppleToolProvider(f.session, new AbortController().signal)).toThrowError( - AppError, - ); -}); - test('remote app metadata resolves Expo and deep-link ownership and rejects duplicate claims', async () => { const f = await fixture({ containers: { diff --git a/src/core/interactors/limrun-ios-files.ts b/src/core/interactors/limrun-ios-files.ts index 8e348203093..7d96f7184d0 100644 --- a/src/core/interactors/limrun-ios-files.ts +++ b/src/core/interactors/limrun-ios-files.ts @@ -8,7 +8,7 @@ import { } from '@agent-device/platform-apple/tool-provider'; import type { LimrunRuntimeDependencies } from '@agent-device/provider-limrun'; import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; -import { downloadLimrunFile, requireLimrunApiUrl } from '../limrun-download-file.ts'; +import { downloadLimrunFile } from '../limrun-download-file.ts'; import { readLimrunControlJson } from './limrun-http-response.ts'; type Session = Parameters[0]; @@ -20,7 +20,6 @@ export function createLimrunSimulatorFiles( lifetime: AbortSignal, requestSignal?: AbortSignal, ): { simulatorFiles: Files; readInfoPlist: AppleToolProvider['simulatorApps']['readInfoPlist'] } { - const apiUrl = requireLimrunApiUrl(session.apiUrl); const signalFor = (signal?: AbortSignal) => AbortSignal.any( [lifetime, requestSignal, signal].filter((value): value is AbortSignal => Boolean(value)), @@ -55,7 +54,7 @@ export function createLimrunSimulatorFiles( } }; const urlFor = (route: string, name: string, container?: Container) => { - const url = new URL(`${apiUrl.href.replace(/\/$/, '')}/${route}`); + const url = new URL(`${session.apiUrl.replace(/\/$/, '')}/${route}`); url.searchParams.set(route === 'files/list' ? 'path' : 'name', name); if (container) { url.searchParams.set('bundleId', container.bundleId); @@ -87,7 +86,6 @@ export function createLimrunSimulatorFiles( copyToHost: async (input) => { await downloadLimrunFile({ url: urlFor('files', input.sourcePath, input).href, - expectedOrigin: apiUrl.origin, headers: { Authorization: `Bearer ${session.token}` }, destinationPath: input.destinationPath, timeoutMs: input.timeoutMs, @@ -193,7 +191,6 @@ export async function readLimrunAppInfo( }).toString(); await downloadLimrunFile({ url: url.href, - expectedOrigin: new URL(access.apiUrl).origin, headers: { Authorization: `Bearer ${access.token}` }, destinationPath, timeoutMs, diff --git a/src/core/interactors/limrun-ios-runner-products.test.ts b/src/core/interactors/limrun-ios-runner-products.test.ts index 3feeddcd0ef..3e5e1df1dee 100644 --- a/src/core/interactors/limrun-ios-runner-products.test.ts +++ b/src/core/interactors/limrun-ios-runner-products.test.ts @@ -240,10 +240,10 @@ for (const bindAddress of ['0.0.0.0', 'localhost', '', '::1']) { test('refuses release bytes with a mismatched checksum before extracting or deploying them', async () => { const urls: string[] = []; - vi.stubGlobal('fetch', async (url: URL) => { - urls.push(url.href); + vi.stubGlobal('fetch', async (url: string) => { + urls.push(url); return new Response( - url.href.endsWith('.json') + url.endsWith('.json') ? JSON.stringify({ version: '0.1.0', platform_target: 'iphonesimulator', @@ -293,9 +293,7 @@ test('a Watch lease rejects an iPhone manifest before downloading its runner', a ).rejects.toThrow('Invalid watchsimulator runner release manifest'); expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenCalledWith( - expect.objectContaining({ - href: expect.stringContaining('/agent-device-watchos-runner-0.1.0.manifest.json'), - }), + expect.stringContaining('/agent-device-watchos-runner-0.1.0.manifest.json'), expect.anything(), ); }); diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index 0e917b1571a..324128028c2 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -40,7 +40,6 @@ test('streams the served file to disk with the bearer token the caller supplied' await downloadLimrunFile({ url, - expectedOrigin: new URL(url).origin, headers: { Authorization: 'Bearer instance-token' }, destinationPath, timeoutMs: 5_000, @@ -50,106 +49,6 @@ test('streams the served file to disk with the bearer token the caller supplied' expect(fs.readFileSync(destinationPath, 'utf8')).toBe('ftypisom-payload'); }); -test('refuses a provider-supplied URL outside the authenticated instance origin', async () => { - const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); - fs.writeFileSync(destinationPath, 'stale recording'); - await expect( - downloadLimrunFile({ - url: 'https://other.example/recording', - expectedOrigin: 'https://instance.example', - headers: { Authorization: 'Bearer instance-token' }, - destinationPath, - timeoutMs: 5_000, - }), - ).rejects.toMatchObject({ - code: 'COMMAND_FAILED', - details: { reason: 'limrun_download_unsafe_url' }, - }); - expect(fs.existsSync(destinationPath)).toBe(false); -}); - -test('requires an origin fence whenever a download carries authorization', async () => { - const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); - await expect( - downloadLimrunFile({ - url: 'https://instance.example/recording', - headers: { authorization: 'Bearer instance-token' }, - destinationPath, - timeoutMs: 5_000, - }), - ).rejects.toMatchObject({ - code: 'COMMAND_FAILED', - details: { reason: 'limrun_download_unsafe_url' }, - }); - expect(fs.existsSync(destinationPath)).toBe(false); -}); - -test('requires an origin fence for any caller-supplied header', async () => { - const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); - await expect( - downloadLimrunFile({ - url: 'https://instance.example/recording', - headers: { 'X-API-Key': 'secret' }, - destinationPath, - timeoutMs: 5_000, - }), - ).rejects.toMatchObject({ - code: 'COMMAND_FAILED', - details: { reason: 'limrun_download_unsafe_url' }, - }); - expect(fs.existsSync(destinationPath)).toBe(false); -}); - -test('anonymous release downloads follow redirects while origin-fenced downloads refuse them', async () => { - const requests: string[] = []; - const url = await serve((request, response) => { - requests.push(request.url ?? ''); - if (request.url?.startsWith('/files')) { - response.writeHead(302, { location: '/release-asset' }); - response.end(); - return; - } - response.writeHead(200); - response.end('runner-archive'); - }); - const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'runner.zip'); - - await downloadLimrunFile({ url, headers: {}, destinationPath, timeoutMs: 5_000 }); - expect(fs.readFileSync(destinationPath, 'utf8')).toBe('runner-archive'); - expect(requests).toEqual(['/files?name=recording.mp4', '/release-asset']); - - requests.length = 0; - await expect( - downloadLimrunFile({ - url, - expectedOrigin: new URL(url).origin, - headers: {}, - destinationPath, - timeoutMs: 5_000, - }), - ).rejects.toMatchObject({ - code: 'COMMAND_FAILED', - details: { reason: 'limrun_download_failed' }, - }); - expect(requests).toEqual(['/files?name=recording.mp4']); - expect(fs.existsSync(destinationPath)).toBe(false); -}); - -test('refuses a recording larger than the download limit before writing it', async () => { - const url = await serve((_request, response) => { - response.writeHead(200, { 'content-length': String(512 * 1024 * 1024 + 1) }); - response.end('not sent'); - }); - const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); - await expect( - downloadLimrunFile({ url, headers: {}, destinationPath, timeoutMs: 5_000 }), - ).rejects.toMatchObject({ - code: 'COMMAND_FAILED', - details: { reason: 'limrun_download_too_large' }, - }); - expect(fs.existsSync(destinationPath)).toBe(false); -}); - test('a non-2xx answer is a typed failure carrying the status and no file is left behind', async () => { const url = await serve((_request, response) => { response.writeHead(404); diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index 6146b0d4bf6..de486705076 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; -import { Readable, Transform } from 'node:stream'; +import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import type { ReadableStream as WebReadableStream } from 'node:stream/web'; import { @@ -9,10 +9,8 @@ import { type ReasonTable, } from '@agent-device/kernel/errors'; import type { LimrunFileDownload } from '@agent-device/provider-limrun'; -import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; const RESPONSE_BODY_PREVIEW_BYTES = 500; -const MAX_LIMRUN_DOWNLOAD_BYTES = 512 * 1024 * 1024; // Why a Limrun file download did not land. The destination is removed on every failure, so each row // means "retry from the same URL", and `limrun_download_failed` adds that the transport itself broke. @@ -23,10 +21,6 @@ const LIMRUN_DOWNLOAD_REASONS = { timeout: { reason: 'limrun_download_timeout' }, // The transfer broke for a reason the service never answered with, kept in `details.cause`. failed: { reason: 'limrun_download_failed' }, - // The provider supplied an invalid, insecure, or cross-origin download URL. - unsafeUrl: { reason: 'limrun_download_unsafe_url' }, - // The downloaded response exceeds the file-size budget. - tooLarge: { reason: 'limrun_download_too_large' }, } as const satisfies ReasonTable<'limrun'>; /** @@ -38,47 +32,20 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise MAX_LIMRUN_DOWNLOAD_BYTES) { - await response.body?.cancel().catch(() => {}); - throw new AppError('COMMAND_FAILED', 'Limrun download exceeds the size limit', { - reason: LIMRUN_DOWNLOAD_REASONS.tooLarge.reason, - limitBytes: MAX_LIMRUN_DOWNLOAD_BYTES, - }); - } if (!response.body) { throw new AppError('COMMAND_FAILED', 'Limrun download returned no body', { url: options.url, }); } - let bytes = 0; - const limit = new Transform({ - transform(chunk: Buffer, _encoding, callback) { - bytes += chunk.byteLength; - if (bytes > MAX_LIMRUN_DOWNLOAD_BYTES) { - callback( - new AppError('COMMAND_FAILED', 'Limrun download exceeds the size limit', { - reason: LIMRUN_DOWNLOAD_REASONS.tooLarge.reason, - limitBytes: MAX_LIMRUN_DOWNLOAD_BYTES, - }), - ); - return; - } - callback(null, chunk); - }, - }); await pipeline( Readable.fromWeb(response.body as WebReadableStream), - limit, fs.createWriteStream(options.destinationPath), { signal }, ); @@ -88,47 +55,6 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise 0; - if ( - (carriesHeaders && options.expectedOrigin === undefined) || - (options.expectedOrigin !== undefined && url.origin !== options.expectedOrigin) - ) { - throw new AppError('COMMAND_FAILED', 'Limrun download URL is not admitted', { - reason: LIMRUN_DOWNLOAD_REASONS.unsafeUrl.reason, - origin: url.origin, - }); - } - return { url, carriesHeaders }; -} - -/** Admit a Limrun API URL before any request sends a bearer or caller-supplied header. */ -export function requireLimrunApiUrl(value: string): URL { - let url: URL; - try { - url = new URL(value); - } catch { - throw new AppError('COMMAND_FAILED', 'Limrun API URL is invalid', { - reason: LIMRUN_DOWNLOAD_REASONS.unsafeUrl.reason, - }); - } - if ( - url.username || - url.password || - (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHostname(url.hostname))) - ) { - throw new AppError('COMMAND_FAILED', 'Limrun API URL is not admitted', { - reason: LIMRUN_DOWNLOAD_REASONS.unsafeUrl.reason, - origin: url.origin, - }); - } - return url; -} - async function httpFailure(response: Response, options: LimrunFileDownload): Promise { return new AppError('COMMAND_FAILED', `Limrun download failed with HTTP ${response.status}`, { url: options.url, diff --git a/test/integration/provider-scenarios/cloud-webdriver-test-server.ts b/test/integration/provider-scenarios/cloud-webdriver-test-server.ts index f3b1d90628a..a1265a6c75b 100644 --- a/test/integration/provider-scenarios/cloud-webdriver-test-server.ts +++ b/test/integration/provider-scenarios/cloud-webdriver-test-server.ts @@ -32,7 +32,7 @@ export type CloudWebDriverTestResponse = { export abstract class CloudWebDriverTestServer { readonly calls: CloudWebDriverHttpCall[] = []; // fallow-ignore-next-line unused-class-member - readonly url = 'https://cloud-webdriver.test'; + readonly url = 'http://cloud-webdriver.test'; protected abstract respond(call: CloudWebDriverHttpCall): CloudWebDriverTestResponse; diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 07a34e728e3..44078aa0b94 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -833,8 +833,6 @@ These reasons can come from more than one command. | `limrun_download_http_error` | The service answered the download with an error status; `details.statusCode` and `details.body` carry its reply. | | `limrun_download_timeout` | The download passed its deadline; `details.timeoutMs` is that deadline. | | `limrun_download_failed` | The transfer broke for a reason the service never answered with, kept in `details.cause`. | -| `limrun_download_unsafe_url` | The provider supplied an invalid, insecure, or cross-origin download URL. | -| `limrun_download_too_large` | The downloaded response exceeds the file-size budget. | ### Limrun provider @@ -1108,4 +1106,3 @@ These reasons can come from more than one command. | `hub_app_upload_timeout` | The app upload to the provider's storage did not answer within its own deadline. | | `hub_app_upload_transport_failed` | The app upload to the provider's storage never completed its transport. | | `provider_app_cwd_missing` | `--provider-app` is a relative path and the request names no working directory to resolve it in. | -| `provider_credential_endpoint_unsafe` | A credential-bearing provider endpoint is neither HTTPS nor loopback HTTP. | From 2955f2b942d6dfcd427ac2768f2ba3dd0932a431 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 09:27:03 +0100 Subject: [PATCH 19/19] fix(revyl): report oversized responses with shared reason --- packages/provider-revyl/src/revyl-client.test.ts | 4 +++- packages/provider-revyl/src/revyl-client.ts | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index 998a468bc7a..ef3d0698b9d 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -37,7 +37,9 @@ test('rejects an oversized provider answer before accepting its body', async () await assert.rejects( client.verifyCredentials(), (error: unknown) => - error instanceof AppError && error.details?.reason === 'provider-response-invalid', + error instanceof AppError && + error.details?.reason === 'provider_response_too_large' && + error.details?.limitBytes === 32 * 1024 * 1024, ); }); diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index 1747c32b542..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'; @@ -408,7 +409,7 @@ async function readRevylResponseBody(response: Response): Promise { bytes += value.byteLength; if (bytes > MAX_REVYL_RESPONSE_BYTES) { throw new AppError('COMMAND_FAILED', 'Revyl response exceeds the size limit.', { - reason: REVYL_OUTCOME_REASONS.responseInvalid.reason, + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, limitBytes: MAX_REVYL_RESPONSE_BYTES, }); }