diff --git a/packages/host-kit/package.json b/packages/host-kit/package.json index 405727d1499..1a1e1877902 100644 --- a/packages/host-kit/package.json +++ b/packages/host-kit/package.json @@ -100,6 +100,10 @@ "types": "./src/retry.ts", "default": "./src/retry.ts" }, + "./response-body": { + "types": "./src/response-body.ts", + "default": "./src/response-body.ts" + }, "./runtime-transport-hints": { "types": "./src/runtime-transport-hints.ts", "default": "./src/runtime-transport-hints.ts" diff --git a/packages/host-kit/src/response-body.test.ts b/packages/host-kit/src/response-body.test.ts new file mode 100644 index 00000000000..8a412c2c2e6 --- /dev/null +++ b/packages/host-kit/src/response-body.test.ts @@ -0,0 +1,49 @@ +import { expect, test, vi } from 'vitest'; +import { readBoundedResponse, readBoundedResponseText, refuseRedirect } from './response-body.ts'; + +function streamed(chunks: Uint8Array[], cancel = vi.fn(), close = true): Response { + return new Response( + new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(chunk); + if (close) controller.close(); + }, + cancel, + }), + { status: 502 }, + ); +} + +test('a response without a body reads as empty bytes', async () => { + expect(await readBoundedResponse(new Response(null, { status: 204 }), 8)).toEqual( + new Uint8Array(), + ); +}); + +test('a body at the limit is accepted and one byte more fails typed with the status', async () => { + expect((await readBoundedResponse(streamed([new Uint8Array(8)]), 8)).byteLength).toBe(8); + const cancel = vi.fn(); + await expect( + readBoundedResponse(streamed([new Uint8Array(9)], cancel, false), 8), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'provider_response_too_large', limitBytes: 8, status: 502 }, + }); + expect(cancel).toHaveBeenCalledTimes(1); +}); + +test('text decoding joins a character split across chunks', async () => { + const bytes = new TextEncoder().encode('é'); + const text = await readBoundedResponseText(streamed([bytes.slice(0, 1), bytes.slice(1)]), 8); + expect(text).toBe('é'); +}); + +test.each([300, 301, 307, 399])('refuseRedirect refuses status %i', async (status) => { + await expect(refuseRedirect(new Response(null, { status }))).rejects.toMatchObject({ + details: { reason: 'provider_redirect_refused', status }, + }); +}); + +test.each([204, 400])('refuseRedirect passes status %i', async (status) => { + await expect(refuseRedirect(new Response(null, { status }))).resolves.toBeUndefined(); +}); diff --git a/packages/host-kit/src/response-body.ts b/packages/host-kit/src/response-body.ts new file mode 100644 index 00000000000..ebac607753f --- /dev/null +++ b/packages/host-kit/src/response-body.ts @@ -0,0 +1,61 @@ +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; + +const PROVIDER_RESPONSE_REASONS = { + // A provider response body is larger than the byte budget its caller allows. + tooLarge: { reason: 'provider_response_too_large' }, + // A provider answered a credentialed request with a redirect, which the sender never follows. + redirectRefused: { reason: 'provider_redirect_refused' }, +} as const satisfies ReasonTable<'provider response'>; + +const PROVIDER_TEXT_BODY_LIMIT_BYTES = 1024 * 1024; +export const PROVIDER_LARGE_BODY_LIMIT_BYTES = 32 * 1024 * 1024; +export const PROVIDER_METADATA_BODY_LIMIT_BYTES = 256 * 1024; + +/** Reads a response body and cancels the stream once it passes `maxBytes`. */ +export async function readBoundedResponse( + response: Response, + maxBytes: number = PROVIDER_TEXT_BODY_LIMIT_BYTES, +): Promise { + const reader = response.body?.getReader(); + if (!reader) return new Uint8Array(); + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) return Buffer.concat(chunks, bytes); + bytes += value.byteLength; + if (bytes > maxBytes) { + throw new AppError('COMMAND_FAILED', 'Provider response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, + limitBytes: maxBytes, + status: response.status, + }); + } + chunks.push(value); + } + } finally { + await reader.cancel().catch(() => {}); + } +} + +export async function readBoundedResponseText( + response: Response, + maxBytes?: number, +): Promise { + return new TextDecoder().decode(await readBoundedResponse(response, maxBytes)); +} + +/** A credentialed request sets `redirect: 'manual'`; any 3xx answer is refused instead of followed. */ +export async function refuseRedirect(response: Response): Promise { + if (response.status < 300 || response.status > 399) return; + await response.body?.cancel().catch(() => {}); + throw new AppError( + 'COMMAND_FAILED', + 'Provider answered a credentialed request with a redirect.', + { + reason: PROVIDER_RESPONSE_REASONS.redirectRefused.reason, + status: response.status, + }, + ); +} diff --git a/packages/provider-aws-device-farm/src/aws-device-farm-webdriver.ts b/packages/provider-aws-device-farm/src/aws-device-farm-webdriver.ts index 712887d66c0..835bb11765b 100644 --- a/packages/provider-aws-device-farm/src/aws-device-farm-webdriver.ts +++ b/packages/provider-aws-device-farm/src/aws-device-farm-webdriver.ts @@ -36,6 +36,7 @@ export function createAwsDeviceFarmWebDriver( createAwsCliDeviceFarmClient({ runHostCommand, region }); return { clientVersion: host.clientVersion, + env, diagnostics: host.diagnostics, provider: AWS_DEVICE_FARM_PROVIDER, profileFields: AWS_DEVICE_FARM_PROFILE_FIELDS, diff --git a/packages/provider-browserstack/src/browserstack-connection-verification.test.ts b/packages/provider-browserstack/src/browserstack-connection-verification.test.ts index cf55bd14b23..aac8e5d98fa 100644 --- a/packages/provider-browserstack/src/browserstack-connection-verification.test.ts +++ b/packages/provider-browserstack/src/browserstack-connection-verification.test.ts @@ -3,7 +3,7 @@ import { afterEach, test, vi } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; import { verifyBrowserStackConnection } from './browserstack-connection-verification.ts'; -const CLIENT_VERSION = '1.2.3'; +const CLIENT_VERSION = { clientVersion: '1.2.3', env: {} }; const browserStackOptions = { username: 'browser-user', diff --git a/packages/provider-browserstack/src/browserstack-connection-verification.ts b/packages/provider-browserstack/src/browserstack-connection-verification.ts index 6578ef65ced..1f6194a720a 100644 --- a/packages/provider-browserstack/src/browserstack-connection-verification.ts +++ b/packages/provider-browserstack/src/browserstack-connection-verification.ts @@ -1,3 +1,4 @@ +import type { EnvMap } from '@agent-device/kernel/source-value'; import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; import type { @@ -28,9 +29,12 @@ export type BrowserStackConnectionVerification = ProviderConnectionVerification project?: never; }; +/** The host facts a connection check sends with every credentialed request. */ +type ProviderRequestClient = { clientVersion: string; env: Readonly }; + export async function verifyBrowserStackConnection( options: BrowserStackConnectionVerificationOptions, - clientVersion: string, + client: ProviderRequestClient, ): Promise { const { parseBrowserStackAppReference } = await import('./browserstack.ts'); const { sameOsVersion } = await import('@agent-device/provider-webdriver/plugin'); @@ -39,7 +43,7 @@ export async function verifyBrowserStackConnection( const devices = await fetchBrowserStackJson( options.devicesEndpoint ?? BROWSERSTACK_DEVICES_ENDPOINT, auth, - clientVersion, + client, ); const matchedDevice = readBrowserStackDevices(devices).find( (device) => @@ -57,7 +61,7 @@ export async function verifyBrowserStackConnection( ); } - const app = await verifyBrowserStackApp(providerApp, options, auth, clientVersion); + const app = await verifyBrowserStackApp(providerApp, options, auth, client); return { provider: 'browserstack', service: 'BrowserStack', @@ -79,14 +83,14 @@ async function verifyBrowserStackApp( app: string, options: BrowserStackConnectionVerificationOptions, auth: { username: string; accessKey: string }, - clientVersion: string, + client: ProviderRequestClient, ): Promise { const { isBrowserStackAppReference } = await import('./providers.ts'); if (isBrowserStackAppReference(app)) { const apps = await fetchBrowserStackJson( options.appsEndpoint ?? BROWSERSTACK_APPS_ENDPOINT, auth, - clientVersion, + client, ); const matched = readBrowserStackApps(apps).find((entry) => entry.reference === app); if (!matched) { @@ -117,11 +121,11 @@ async function verifyBrowserStackApp( async function fetchBrowserStackJson( endpoint: string | URL, auth: { username: string; accessKey: string }, - clientVersion: string, + client: ProviderRequestClient, ): Promise { const { fetchProviderVerificationJson } = await import('@agent-device/provider-webdriver/plugin'); return await fetchProviderVerificationJson(endpoint, { - clientVersion, + ...client, auth, hints: { service: 'BrowserStack', diff --git a/packages/provider-browserstack/src/browserstack-connection.test.ts b/packages/provider-browserstack/src/browserstack-connection.test.ts index 5bc94f27c92..7e4cd141937 100644 --- a/packages/provider-browserstack/src/browserstack-connection.test.ts +++ b/packages/provider-browserstack/src/browserstack-connection.test.ts @@ -155,7 +155,7 @@ test('verify hands the saved profile and the client version to the verifier', as osVersion: '14.0', app: 'bs://app-id', }, - '1.2.3', + { clientVersion: '1.2.3', env: CREDENTIALS }, ]); await assert.rejects( connection.verify({ flags: { ...FLAGS, device: undefined }, env: CREDENTIALS, host: host() }), diff --git a/packages/provider-browserstack/src/browserstack-webdriver.ts b/packages/provider-browserstack/src/browserstack-webdriver.ts index d5477649dbd..58c27cfe0b5 100644 --- a/packages/provider-browserstack/src/browserstack-webdriver.ts +++ b/packages/provider-browserstack/src/browserstack-webdriver.ts @@ -35,6 +35,7 @@ function createBrowserStackWebDriver(host: ProviderPluginHost): CloudWebDriverRu const { env, clientVersion } = host; return { clientVersion: host.clientVersion, + env, diagnostics: host.diagnostics, provider: PROVIDER, profileFields: BROWSERSTACK_PROFILE_FIELDS, @@ -45,6 +46,7 @@ function createBrowserStackWebDriver(host: ProviderPluginHost): CloudWebDriverRu listArtifacts: async ({ provider, providerSessionId }) => await listBrowserStackCloudArtifacts(provider, providerSessionId, { clientVersion, + env, ...requireBrowserStackCredentials(env, 'BrowserStack artifact lookup'), endpoint: env.BROWSERSTACK_SESSION_DETAILS_ENDPOINT, }), @@ -60,6 +62,7 @@ function createBrowserStackWebDriver(host: ProviderPluginHost): CloudWebDriverRu ); const upload = { clientVersion, + env, ...credentials, endpoint: env.BROWSERSTACK_APP_UPLOAD_ENDPOINT ?? BROWSERSTACK_APP_UPLOAD_ENDPOINT, }; diff --git a/packages/provider-browserstack/src/browserstack.test.ts b/packages/provider-browserstack/src/browserstack.test.ts index cc365416568..9092d3928f0 100644 --- a/packages/provider-browserstack/src/browserstack.test.ts +++ b/packages/provider-browserstack/src/browserstack.test.ts @@ -37,6 +37,7 @@ test('BrowserStack upload aborts while the provider request is in flight', async appPath, { clientVersion: '0.0.0-test', + env: {}, username: 'user', accessKey: 'key', }, @@ -51,7 +52,7 @@ test('BrowserStack upload aborts while the provider request is in flight', async } }); -const upload = { clientVersion: '0.0.0-test', username: 'user', accessKey: 'key' }; +const upload = { clientVersion: '0.0.0-test', env: {}, username: 'user', accessKey: 'key' }; test('BrowserStack upload sends the file field and fails typed on a gateway error page', async () => { const tempDir = await mkdtempForTest('agent-device-browserstack-upload-error-'); diff --git a/packages/provider-browserstack/src/browserstack.ts b/packages/provider-browserstack/src/browserstack.ts index 9bb5f208f1a..4847702a0fe 100644 --- a/packages/provider-browserstack/src/browserstack.ts +++ b/packages/provider-browserstack/src/browserstack.ts @@ -1,6 +1,8 @@ +import type { EnvMap } from '@agent-device/kernel/source-value'; import type { CloudArtifact, CloudArtifactsResult } from '@agent-device/contracts/observability'; import { AppError } from '@agent-device/kernel/errors'; import { + admitCredentialedEndpoint, appendUrlPath, appFileUploadForm, cloudArtifactsReadyOrPending, @@ -54,6 +56,7 @@ export type BrowserStackCapabilitiesOptions = { export type BrowserStackSessionDetailsOptions = { clientVersion: string; + env: Readonly; username: string; accessKey: string; endpoint?: string | URL; @@ -77,6 +80,7 @@ export async function listBrowserStackCloudArtifacts( export type BrowserStackUploadOptions = { clientVersion: string; + env: Readonly; username: string; accessKey: string; endpoint?: string | URL; @@ -97,6 +101,7 @@ export async function uploadBrowserStackApp( service: 'BrowserStack', endpoint: options.endpoint ?? BROWSERSTACK_APP_UPLOAD_ENDPOINT, clientVersion: options.clientVersion, + env: options.env, auth: options, readAppReference: readBrowserStackAppUrl, }, @@ -182,11 +187,15 @@ async function fetchBrowserStackSessionDetails( options: BrowserStackSessionDetailsOptions, ): Promise> { const endpoint = appendUrlPath( - options.endpoint ?? BROWSERSTACK_SESSION_DETAILS_ENDPOINT, + await admitCredentialedEndpoint( + options.endpoint ?? BROWSERSTACK_SESSION_DETAILS_ENDPOINT, + options.env, + ), `${sessionId}.json`, ); const json = await fetchProviderSessionDetails(endpoint, { clientVersion: options.clientVersion, + env: options.env, auth: options, service: 'BrowserStack', }); diff --git a/packages/provider-browserstack/src/connection.ts b/packages/provider-browserstack/src/connection.ts index 2f1250b21ef..e6f34f48ba4 100644 --- a/packages/provider-browserstack/src/connection.ts +++ b/packages/provider-browserstack/src/connection.ts @@ -72,7 +72,7 @@ export function createBrowserStackConnection( ), app: requireResolvedProfileValue(flags.providerApp, 'BrowserStack profile missed app.'), }, - host.clientVersion, + { clientVersion: host.clientVersion, env: host.env }, ), }; } diff --git a/packages/provider-limrun/src/download-file.test.ts b/packages/provider-limrun/src/download-file.test.ts index 56576fa64e2..95ff09d5123 100644 --- a/packages/provider-limrun/src/download-file.test.ts +++ b/packages/provider-limrun/src/download-file.test.ts @@ -369,3 +369,18 @@ test.each(['http://127.0.0.1', 'http://localhost.', 'http://instance.example'])( } }, ); + +test('a download past its byte budget fails typed and leaves no file', async () => { + const url = await serve((_request, response) => { + response.end('ftypisom-payload'); + }); + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + + await expect( + downloadLimrunFile({ url, destinationPath, timeoutMs: 5_000, maxBytes: 4 }), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'limrun_download_too_large', limitBytes: 4 }, + }); + expect(fs.existsSync(destinationPath)).toBe(false); +}); diff --git a/packages/provider-limrun/src/download-file.ts b/packages/provider-limrun/src/download-file.ts index 2ea1d63307b..6efdce01da3 100644 --- a/packages/provider-limrun/src/download-file.ts +++ b/packages/provider-limrun/src/download-file.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; -import { Readable } from 'node:stream'; +import { Readable, type Transform } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import type { ReadableStream as WebReadableStream } from 'node:stream/web'; import { @@ -20,6 +20,8 @@ const LIMRUN_DOWNLOAD_REASONS = { timeout: { reason: 'limrun_download_timeout' }, // The request or transfer failed, including when an authenticated endpoint redirects. failed: { reason: 'limrun_download_failed' }, + // The download body is larger than the byte budget, so the transfer stopped. + tooLarge: { reason: 'limrun_download_too_large' }, // An authenticated download requires HTTPS on the instance origin. endpointBlocked: { reason: 'limrun_download_endpoint_blocked' }, } as const satisfies ReasonTable<'limrun'>; @@ -39,7 +41,25 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise + new AppError('COMMAND_FAILED', 'Limrun download exceeds the size limit', { + reason: LIMRUN_DOWNLOAD_REASONS.tooLarge.reason, + limitBytes: maxBytes, + }), + }), + ); } catch (error) { await fs.promises.rm(options.destinationPath, { force: true }).catch(() => {}); throw downloadFailure(error, options, timeout, signal); @@ -69,6 +89,7 @@ async function writeDownloadBody( body: WebReadableStream | null, destinationPath: string, signal: AbortSignal, + limit: Transform, ): Promise { if (!body) { throw new AppError('COMMAND_FAILED', 'Limrun download returned no body', { @@ -76,7 +97,7 @@ async function writeDownloadBody( destination: path.basename(destinationPath), }); } - await pipeline(Readable.fromWeb(body), fs.createWriteStream(destinationPath), { signal }); + await pipeline(Readable.fromWeb(body), limit, fs.createWriteStream(destinationPath), { signal }); } function instanceDownloadUrl(apiUrl: string, value: string): URL { diff --git a/packages/provider-limrun/src/ios-files.ts b/packages/provider-limrun/src/ios-files.ts index beb98284673..914a8521a53 100644 --- a/packages/provider-limrun/src/ios-files.ts +++ b/packages/provider-limrun/src/ios-files.ts @@ -26,8 +26,10 @@ const LIMRUN_FILE_REASONS = { } as const satisfies ReasonTable<'limrun'>; async function readFileReply(response: Response, signal: AbortSignal): Promise { + const { readBoundedResponseText } = await import('@agent-device/host-kit/response-body'); + const text = await readBoundedResponseText(response); try { - return (await response.json()) as T; + return JSON.parse(text) as T; } catch { signal.throwIfAborted(); throw new AppError('COMMAND_FAILED', 'Limrun file operation returned invalid JSON', { @@ -215,11 +217,14 @@ export async function readLimrunAppInfo( bundleId, containerType: 'app', }).toString(); + const { PROVIDER_METADATA_BODY_LIMIT_BYTES } = + await import('@agent-device/host-kit/response-body'); await downloadLimrunFile({ url: url.href, instance: access, destinationPath, timeoutMs, + maxBytes: PROVIDER_METADATA_BODY_LIMIT_BYTES, signal, }); return parsePlist(await fs.readFile(destinationPath, { signal })); diff --git a/packages/provider-limrun/src/ios-runner-products.ts b/packages/provider-limrun/src/ios-runner-products.ts index 8c1f3d09823..c2728f60936 100644 --- a/packages/provider-limrun/src/ios-runner-products.ts +++ b/packages/provider-limrun/src/ios-runner-products.ts @@ -154,10 +154,13 @@ async function downloadReleaseRunner( const name = `agent-device-${platform}-runner-${input.version}`; const release = `https://github.com/callstack/agent-device/releases/download/v${input.version}`; const manifestPath = path.join(input.directory, 'manifest.json'); + const { PROVIDER_METADATA_BODY_LIMIT_BYTES } = + await import('@agent-device/host-kit/response-body'); await downloadLimrunFile({ url: `${release}/${name}.manifest.json`, destinationPath: manifestPath, timeoutMs: 120_000, + maxBytes: PROVIDER_METADATA_BODY_LIMIT_BYTES, signal: input.signal, }); const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8')) as Record; @@ -309,8 +312,10 @@ export async function uploadLimrunRunnerProducts( }, ); } + const { readBoundedResponseText } = await import('@agent-device/host-kit/response-body'); + const text = await readBoundedResponseText(response); try { - return (await response.json()) as { ok?: boolean; needFull?: string[] }; + return JSON.parse(text) as { ok?: boolean; needFull?: string[] }; } catch { signal.throwIfAborted(); throw limrunRunnerError('uploadFailed', 'Limrun runner upload returned invalid JSON', { diff --git a/packages/provider-limrun/src/ios-runner.ts b/packages/provider-limrun/src/ios-runner.ts index 6b73e3b102e..d4221362132 100644 --- a/packages/provider-limrun/src/ios-runner.ts +++ b/packages/provider-limrun/src/ios-runner.ts @@ -185,9 +185,12 @@ export async function createLimrunIosRunner( launchSignal, ); if (!result.ok) { - const responseText = await awaitWithSignal(result.text(), launchSignal).catch( - () => undefined, - ); + const { readBoundedResponseText } = + await import('@agent-device/host-kit/response-body'); + const responseText = await awaitWithSignal( + readBoundedResponseText(result), + launchSignal, + ).catch(() => undefined); const failure = limrunRunnerError( result.status === 409 ? 'xctestSlotOccupied' : 'launchFailed', `Limrun XCTest launch failed (${result.status})`, diff --git a/packages/provider-limrun/src/runtime-dependencies.ts b/packages/provider-limrun/src/runtime-dependencies.ts index 40b2769ad3d..0f9afddeec8 100644 --- a/packages/provider-limrun/src/runtime-dependencies.ts +++ b/packages/provider-limrun/src/runtime-dependencies.ts @@ -162,6 +162,8 @@ export type LimrunFileDownload = Readonly<{ instance?: { apiUrl: string; token: string }; destinationPath: string; timeoutMs: number; + /** Defaults to the artifact size limit; a small metadata read passes its own budget. */ + maxBytes?: number; signal?: AbortSignal; }>; diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index 098e6076e4c..54fb1b8fe34 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -456,3 +456,46 @@ function jsonError(status: number, detail: string): Response { headers: { 'content-type': 'application/json' }, }); } + +function oversizedResponse(bytes: number, status = 200, onCancel?: () => void): Response { + return new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(bytes)); + if (!onCancel) controller.close(); + }, + cancel: onCancel, + }), + { status }, + ); +} + +test('an oversized JSON reply is canceled at the text budget', async () => { + let canceled = 0; + const client = clientResponding(() => + oversizedResponse(1024 * 1024 + 1, 200, () => { + canceled += 1; + }), + ); + await assert.rejects( + client.verifyCredentials(), + (error) => + error instanceof AppError && + error.details?.reason === 'provider_response_too_large' && + error.details?.limitBytes === 1024 * 1024, + ); + assert.equal(canceled, 1); +}); + +test('a successful hierarchy gets the large budget and an error reply keeps the text budget', async () => { + const hierarchy = clientResponding(() => oversizedResponse(2 * 1024 * 1024)); + assert.equal((await hierarchy.getWorkerHierarchy('run-1')).length, 2 * 1024 * 1024); + const failing = clientResponding(() => oversizedResponse(1024 * 1024 + 1, 400)); + await assert.rejects( + failing.getWorkerHierarchy('run-1'), + (error) => + error instanceof AppError && + error.details?.reason !== 'provider_response_too_large' && + error.details?.providerStatus === 400, + ); +}); diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index 840e72653ff..dc193a820c5 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -7,6 +7,10 @@ import { } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; +import { + PROVIDER_LARGE_BODY_LIMIT_BYTES, + readBoundedResponse, +} from '@agent-device/host-kit/response-body'; import fs from 'node:fs'; import { Readable } from 'node:stream'; import { setTimeout as sleep } from 'node:timers/promises'; @@ -121,6 +125,8 @@ type RevylRequest = Readonly<{ path: string; body?: unknown; timeoutMs?: number; + /** A successful answer may carry up to the large byte budget; any other answer gets the text budget. */ + largeResponse?: boolean; /** * Defaults to true for GET and false for POST. A POST opts in only when Revyl documents it as * idempotent, which `/stop` is; a device action is never replayed. @@ -262,7 +268,7 @@ function createRoutedClient(options: RevylRouteOptions): RevylClient { /** A successful call whose body is raw text or bytes; a binary action still reports errors as JSON. */ async function body(request: RevylRequest): Promise { - const response = await send(request); + const response = await send({ ...request, largeResponse: true }); assertSuccess(request, response, proxy !== undefined); return response.body; } @@ -414,6 +420,19 @@ function createRoutedClient(options: RevylRouteOptions): RevylClient { }); } +async function readResponseBody(response: Response, request: RevylRequest): Promise { + try { + return await readBoundedResponse( + response, + response.ok && request.largeResponse ? PROVIDER_LARGE_BODY_LIMIT_BYTES : undefined, + ); + } catch (error) { + // An oversized error page keeps its status, so the status classifier still runs. + if (response.ok || !(error instanceof AppError)) throw error; + return new Uint8Array(); + } +} + async function sendOnce( backendUrl: string, fetchImpl: typeof fetch, @@ -433,12 +452,14 @@ async function sendOnce( redirect: 'error', signal, }); + const body = await readResponseBody(response, request); return Object.freeze({ status: response.status, contentType: response.headers.get('content-type') ?? undefined, - body: new Uint8Array(await response.arrayBuffer()), + body, }); } 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( diff --git a/packages/provider-testmu/src/connection.ts b/packages/provider-testmu/src/connection.ts index a10a0cb17e3..a3cd5c8b790 100644 --- a/packages/provider-testmu/src/connection.ts +++ b/packages/provider-testmu/src/connection.ts @@ -74,7 +74,7 @@ export function createTestMuConnection(host: ProviderPluginHost) { deviceType: readTestMuDeviceType(flags), apiEndpoint: host.env.TESTMU_API_ENDPOINT, }, - host.clientVersion, + { clientVersion: host.clientVersion, env: host.env }, ), }; } diff --git a/packages/provider-testmu/src/testmu-connection-verification.test.ts b/packages/provider-testmu/src/testmu-connection-verification.test.ts index e82ac69cbdd..b57d2dbf6d4 100644 --- a/packages/provider-testmu/src/testmu-connection-verification.test.ts +++ b/packages/provider-testmu/src/testmu-connection-verification.test.ts @@ -6,7 +6,7 @@ afterEach(() => vi.unstubAllGlobals()); function createProvider() { return { verifyConnection: async (options: TestMuOptions) => - await verifyTestMuConnection(options, '1.2.3'), + await verifyTestMuConnection(options, { clientVersion: '1.2.3', env: {} }), }; } function jsonResponse(value: unknown, status = 200) { @@ -406,3 +406,29 @@ test('TestMu defers a real-device lt:// id missing from the real-device app list 'Credentials and real device verified; app availability is checked when the session is created.', ); }); + +test('TestMu verifies an app that sits in an app list larger than the text budget', async () => { + const filler = Array.from({ length: 12_000 }, (_, index) => ({ + app_id: `FILL${index}`, + name: 'x'.repeat(100), + version: '1', + type: 'android', + })); + vi.stubGlobal( + 'fetch', + vi.fn(async (input) => + String(input).includes('capability/generator') + ? jsonResponse(testMuCatalog) + : jsonResponse({ + data: [ + ...filler, + { app_id: 'APP1', name: 'sample.apk', version: '1', type: 'android' }, + ], + }), + ), + ); + + const result = await createProvider().verifyConnection(testMuOptions); + + assert.equal(result.app?.status, 'verified'); +}); diff --git a/packages/provider-testmu/src/testmu-connection-verification.ts b/packages/provider-testmu/src/testmu-connection-verification.ts index 5f7bf3fe941..7d83b6611e5 100644 --- a/packages/provider-testmu/src/testmu-connection-verification.ts +++ b/packages/provider-testmu/src/testmu-connection-verification.ts @@ -1,7 +1,9 @@ +import type { EnvMap } from '@agent-device/kernel/source-value'; import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; import { asOptionalRecord } from '@agent-device/kernel/record'; import { + admitCredentialedEndpoint, appendUrlPath, fetchProviderVerificationJson, } from '@agent-device/provider-webdriver/plugin'; @@ -39,6 +41,9 @@ const TESTMU_APP_LIST_TYPES: Record }; + /** * Verifies a TestMu device selection without creating a session: the public capability catalog * of the selected pool (real or virtual) confirms the device/OS pair exists, and the @@ -46,7 +51,7 @@ const TESTMU_APP_LIST_TYPES: Record { const auth = { username: options.username, accessKey: options.accessKey }; const deviceType = options.deviceType ?? 'virtual'; @@ -54,7 +59,7 @@ export async function verifyTestMuConnection( ? new URL(options.devicesEndpoint) : appendUrlPath(options.apiEndpoint ?? TESTMU_API_ENDPOINT, 'capability/generator'); catalogUrl.searchParams.set('isVirtualDevice', String(deviceType === 'virtual')); - const catalog = await fetchTestMuJson(catalogUrl, undefined, clientVersion); + const catalog = await fetchTestMuJson(catalogUrl, undefined, client); const namedDevices = readTestMuCatalogDevices(catalog, options.platform, deviceType).filter( (device) => device.name === options.deviceName, ); @@ -80,7 +85,7 @@ export async function verifyTestMuConnection( ); } - const app = await verifyTestMuApp(options, deviceType, auth, clientVersion); + const app = await verifyTestMuApp(options, deviceType, auth, client); return { provider: 'testmu', service: 'TestMu AI', @@ -102,14 +107,17 @@ async function verifyTestMuApp( options: TestMuOptions, deviceType: ProviderDeviceType, auth: TestMuAuth, - clientVersion: string, + client: ProviderRequestClient, ): Promise { const { app } = options; // The listing is authenticated, so it doubles as the credential check for every app kind. - const appsUrl = new URL(options.appsEndpoint ?? TESTMU_APPS_ENDPOINT); + const appsUrl = await admitCredentialedEndpoint( + options.appsEndpoint ?? TESTMU_APPS_ENDPOINT, + client.env, + ); appsUrl.searchParams.set('type', TESTMU_APP_LIST_TYPES[deviceType][options.platform]); appsUrl.searchParams.set('level', 'user'); - const apps = await fetchTestMuJson(appsUrl, auth, clientVersion); + const apps = await fetchTestMuJson(appsUrl, auth, client); if (isTestMuAppReference(app)) { const matched = readTestMuApps(apps).find((entry) => entry.reference === app); if (!matched) { @@ -139,10 +147,10 @@ async function verifyTestMuApp( async function fetchTestMuJson( endpoint: string | URL, auth: TestMuAuth | undefined, - clientVersion: string, + client: ProviderRequestClient, ): Promise { return await fetchProviderVerificationJson(endpoint, { - clientVersion, + ...client, auth, hints: { service: 'TestMu AI', diff --git a/packages/provider-testmu/src/testmu-webdriver.ts b/packages/provider-testmu/src/testmu-webdriver.ts index c199b90dc79..4b362004223 100644 --- a/packages/provider-testmu/src/testmu-webdriver.ts +++ b/packages/provider-testmu/src/testmu-webdriver.ts @@ -53,12 +53,14 @@ function createTestMuWebDriver(host: ProviderPluginHost): CloudWebDriverRuntimeO ) { return await listTestMuCloudArtifacts(provider, providerSessionId, { clientVersion: host.clientVersion, + env, ...requireTestMuCredentials(env, 'TestMu AI artifact lookup'), endpoint: env.TESTMU_API_ENDPOINT, }); } return { clientVersion: host.clientVersion, + env, diagnostics: host.diagnostics, provider: 'testmu', profileFields: TESTMU_PROFILE_FIELDS, @@ -82,7 +84,7 @@ function createTestMuWebDriver(host: ProviderPluginHost): CloudWebDriverRuntimeO ); const upload = { clientVersion: host.clientVersion, - + env, ...credentials, deviceType, endpoint: uploadEndpoint, diff --git a/packages/provider-testmu/src/testmu.test.ts b/packages/provider-testmu/src/testmu.test.ts index af2fb63c9ae..b6b3910c0cb 100644 --- a/packages/provider-testmu/src/testmu.test.ts +++ b/packages/provider-testmu/src/testmu.test.ts @@ -15,7 +15,7 @@ import { buildCloudWebDriverBaseCapabilities } from '@agent-device/provider-webd import { mkdtempForTest } from './tmp-dir.fixtures.ts'; const realFetch = globalThis.fetch; -const auth = { clientVersion: '0.0.0-test', username: 'user', accessKey: 'key' }; +const auth = { clientVersion: '0.0.0-test', env: {}, username: 'user', accessKey: 'key' }; afterEach(() => { globalThis.fetch = realFetch; diff --git a/packages/provider-testmu/src/testmu.ts b/packages/provider-testmu/src/testmu.ts index 8ea6b12e87a..d7d32a2710f 100644 --- a/packages/provider-testmu/src/testmu.ts +++ b/packages/provider-testmu/src/testmu.ts @@ -1,8 +1,10 @@ +import type { EnvMap } from '@agent-device/kernel/source-value'; import { type CloudWebDriverPlatform, type CloudWebDriverUploadApp, cloudArtifactsReadyOrPending, urlArtifactFromDetails, + admitCredentialedEndpoint, appendUrlPath, appFileUploadForm, createHubUploadApp, @@ -55,6 +57,7 @@ export type TestMuAuth = { export type TestMuSessionDetailsOptions = TestMuAuth & { clientVersion: string; + env: Readonly; endpoint?: string | URL; }; @@ -76,6 +79,7 @@ export async function listTestMuCloudArtifacts( export type TestMuUploadOptions = TestMuAuth & { clientVersion: string; + env: Readonly; /** Selects the pool's upload API when no endpoint override is given; defaults to `virtual`. */ deviceType?: ProviderDeviceType; endpoint?: string | URL; @@ -132,6 +136,7 @@ async function postTestMuUpload( service: 'TestMu AI', endpoint: options.endpoint ?? TESTMU_APP_UPLOAD_ENDPOINTS[options.deviceType ?? 'virtual'], clientVersion: options.clientVersion, + env: options.env, auth: options, readAppReference: readTestMuAppReference, }, @@ -227,13 +232,14 @@ async function fetchTestMuSessionDetails( options: TestMuSessionDetailsOptions, ): Promise> { const endpoint = appendUrlPath( - options.endpoint ?? TESTMU_API_ENDPOINT, + await admitCredentialedEndpoint(options.endpoint ?? TESTMU_API_ENDPOINT, options.env), `sessions/${encodeURIComponent(sessionId)}`, ); let json: Record; try { json = await fetchProviderSessionDetails(endpoint, { clientVersion: options.clientVersion, + env: options.env, auth: options, service: 'TestMu AI', }); diff --git a/packages/provider-webdriver/package.json b/packages/provider-webdriver/package.json index 58b8214d29c..1a58b9ed3cd 100644 --- a/packages/provider-webdriver/package.json +++ b/packages/provider-webdriver/package.json @@ -7,6 +7,7 @@ "dependencies": { "@agent-device/capture-kit": "workspace:*", "@agent-device/contracts": "workspace:*", + "@agent-device/host-kit": "workspace:*", "@agent-device/kernel": "workspace:*", "@agent-device/xml": "workspace:*" }, @@ -26,7 +27,6 @@ }, "devDependencies": { "@agent-device/gestures": "workspace:*", - "@agent-device/host-kit": "workspace:*", "@agent-device/test-kit": "workspace:*" } } diff --git a/packages/provider-webdriver/src/plugin.ts b/packages/provider-webdriver/src/plugin.ts index 8e3cac38bbe..bdfd48c6d0d 100644 --- a/packages/provider-webdriver/src/plugin.ts +++ b/packages/provider-webdriver/src/plugin.ts @@ -15,6 +15,7 @@ export type { export type { CloudWebDriverCapabilityOverrides } from './capabilities.ts'; export { + admitCredentialedEndpoint, appFileUploadForm, appendUrlPath, createHubUploadApp, diff --git a/packages/provider-webdriver/src/runtime-session-allocation.test.ts b/packages/provider-webdriver/src/runtime-session-allocation.test.ts index dd8e3b71f90..4796080a384 100644 --- a/packages/provider-webdriver/src/runtime-session-allocation.test.ts +++ b/packages/provider-webdriver/src/runtime-session-allocation.test.ts @@ -934,6 +934,7 @@ function describe(outcome: Settled): string { function makeRuntime(overrides: Partial = {}) { return createCloudWebDriverRuntime({ clientVersion: 'test', + env: {}, provider: 'webdriver-test', endpoint: 'https://webdriver.test/wd/hub/', platform: 'android', diff --git a/packages/provider-webdriver/src/runtime-session.test.ts b/packages/provider-webdriver/src/runtime-session.test.ts index 5b9c50412a8..4e51a2d5ea8 100644 --- a/packages/provider-webdriver/src/runtime-session.test.ts +++ b/packages/provider-webdriver/src/runtime-session.test.ts @@ -163,6 +163,7 @@ test('cloud artifact lookup does not accept a provider session id without its le function makeRuntime(overrides: Partial = {}) { return createCloudWebDriverRuntime({ clientVersion: 'test', + env: {}, provider: 'webdriver-test', endpoint: 'https://webdriver.test/wd/hub/', platform: 'android', diff --git a/packages/provider-webdriver/src/runtime-session.ts b/packages/provider-webdriver/src/runtime-session.ts index 9bcd06c1c74..ff6ef0cf786 100644 --- a/packages/provider-webdriver/src/runtime-session.ts +++ b/packages/provider-webdriver/src/runtime-session.ts @@ -321,6 +321,7 @@ export class WebDriverSessionManager { const prepared = await this.prepareSession(lease, req); const client = new WebDriverClient({ clientVersion: this.options.clientVersion, + env: this.options.env, diagnostics: this.options.diagnostics, endpoint: prepared.endpoint, auth: prepared.auth, diff --git a/packages/provider-webdriver/src/runtime.test.ts b/packages/provider-webdriver/src/runtime.test.ts index e94d1faece4..2d256fc325a 100644 --- a/packages/provider-webdriver/src/runtime.test.ts +++ b/packages/provider-webdriver/src/runtime.test.ts @@ -5,6 +5,7 @@ import { consumeAllProfileFields } from './profile-fields.fixtures.ts'; test('publishes eager provider metadata without loading a WebDriver session', async () => { const runtime = createCloudWebDriverRuntime({ clientVersion: 'test', + env: {}, provider: 'webdriver-test', endpoint: 'https://webdriver.test/wd/hub/', platform: 'android', diff --git a/packages/provider-webdriver/src/runtime.ts b/packages/provider-webdriver/src/runtime.ts index d9bc5fc8042..9026759e43b 100644 --- a/packages/provider-webdriver/src/runtime.ts +++ b/packages/provider-webdriver/src/runtime.ts @@ -1,3 +1,4 @@ +import type { EnvMap } from '@agent-device/kernel/source-value'; import type { CloudArtifactProvider, CloudArtifactsResult, @@ -90,6 +91,7 @@ export type CloudWebDriverPrepareSession = (params: { export type CloudWebDriverRuntimeOptions = { clientVersion: string; + env: Readonly; diagnostics?: WebDriverClientOptions['diagnostics']; provider: string; endpoint: string | URL; diff --git a/packages/provider-webdriver/src/webdriver-client.test.ts b/packages/provider-webdriver/src/webdriver-client.test.ts index e71da72c354..0a3287a00a5 100644 --- a/packages/provider-webdriver/src/webdriver-client.test.ts +++ b/packages/provider-webdriver/src/webdriver-client.test.ts @@ -169,6 +169,7 @@ test('createSession does not retry a transient create failure', async () => { }; const client = new WebDriverClient({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', // A retry-enabled policy would double a normal request; createSession must // still refuse to retry regardless of the client's retry budget. @@ -201,6 +202,7 @@ test('createSession waits on its own budget, not the per-request default', async }; const client = new WebDriverClient({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', // A create bound by this 20ms default would abort before the 60ms answer; // the dedicated session-create budget is what keeps it alive. @@ -228,6 +230,7 @@ test('createSession is bounded by the operation deadline when it is shorter', as }; const client = new WebDriverClient({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', requestPolicy: { timeoutMs: 30_000, retryAttempts: 0, sessionCreateTimeoutMs: 180_000 }, }); @@ -430,6 +433,7 @@ for (const operation of ['clear', 'replace'] as const) { globalThis.fetch = webDriverResponse(200, { value: { sessionId: 'wd-1', capabilities: {} } }); const client = new WebDriverClient({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', requestPolicy: { retryAttempts: 3 }, }); @@ -478,6 +482,7 @@ async function connectedClient(respond: typeof globalThis.fetch): Promise { - const value = await this.sessionRequest('GET', '/source', undefined, overrides); + const value = await this.sessionRequest('GET', '/source', undefined, { + ...overrides, + responseLimitBytes: overrides?.responseLimitBytes ?? PROVIDER_LARGE_BODY_LIMIT_BYTES, + }); if (typeof value !== 'string') { throw new AppError('COMMAND_FAILED', 'WebDriver source response was not a string', { valueType: typeof value, @@ -306,7 +310,9 @@ export class WebDriverClient { } async screenshot(outPath: string): Promise { - const value = await this.sessionRequest('GET', '/screenshot'); + const value = await this.sessionRequest('GET', '/screenshot', undefined, { + responseLimitBytes: PROVIDER_LARGE_BODY_LIMIT_BYTES, + }); if (typeof value !== 'string') { throw new AppError('COMMAND_FAILED', 'WebDriver screenshot response was not base64 text', { valueType: typeof value, diff --git a/packages/provider-webdriver/src/webdriver-interactor-mutation-resend.test.ts b/packages/provider-webdriver/src/webdriver-interactor-mutation-resend.test.ts index 53be184e440..d75643cb42c 100644 --- a/packages/provider-webdriver/src/webdriver-interactor-mutation-resend.test.ts +++ b/packages/provider-webdriver/src/webdriver-interactor-mutation-resend.test.ts @@ -84,6 +84,7 @@ async function connectedWebDriverInteractor(options: { globalThis.fetch = fetch; const client = new WebDriverClient({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', requestPolicy: { timeoutMs: 20, retryDelayMs: 5, sessionCreateTimeoutMs: 20 }, diagnostics: { emit: emitDiagnostic }, diff --git a/packages/provider-webdriver/src/webdriver-orientation.test.ts b/packages/provider-webdriver/src/webdriver-orientation.test.ts index c12cf988e27..93b68ecfda3 100644 --- a/packages/provider-webdriver/src/webdriver-orientation.test.ts +++ b/packages/provider-webdriver/src/webdriver-orientation.test.ts @@ -24,6 +24,7 @@ afterEach(() => { async function driverAnswerError(driver: typeof globalThis.fetch): Promise { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', requestPolicy: { timeoutMs: 20 }, }); diff --git a/packages/provider-webdriver/src/webdriver-transport.test.ts b/packages/provider-webdriver/src/webdriver-transport.test.ts index 8cae57f3989..0266b602002 100644 --- a/packages/provider-webdriver/src/webdriver-transport.test.ts +++ b/packages/provider-webdriver/src/webdriver-transport.test.ts @@ -35,6 +35,7 @@ afterEach(() => { test('a transport-deadline abort surfaces as a typed timeout, not a DOMException name', async () => { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', requestPolicy: { timeoutMs: 30, retryAttempts: 0 }, }); @@ -61,6 +62,7 @@ test('a caller-driven abort is NOT reclassified as a transport timeout', async ( const controller = new AbortController(); const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', requestPolicy: { timeoutMs: 30_000, retryAttempts: 0 }, }); @@ -83,6 +85,7 @@ test('cancels a retry delay when the request binding aborts', async () => { const controller = new AbortController(); const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', requestPolicy: { timeoutMs: 30_000, retryAttempts: 1, retryDelayMs: 10_000 }, }); @@ -132,6 +135,7 @@ test('a POST without parameters carries an empty JSON object body', async () => try { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: driver.endpoint, requestPolicy: { timeoutMs: 5_000, retryAttempts: 0 }, }); @@ -195,6 +199,7 @@ function countFetchCalls(): () => number { test('a refused connection discloses the request never reached the driver', async () => { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: `http://127.0.0.1:${await refusedPort()}/wd/hub/`, requestPolicy: { timeoutMs: 5_000, retryDelayMs: 1 }, }); @@ -212,6 +217,7 @@ test('a refused connection discloses the request never reached the driver', asyn test('a refused POST is not resent', async () => { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: `http://127.0.0.1:${await refusedPort()}/wd/hub/`, requestPolicy: { timeoutMs: 5_000, retryDelayMs: 1 }, }); @@ -229,6 +235,7 @@ test('a socket reset after the driver read the body discloses an unresolved outc }); const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: driver.endpoint, requestPolicy: { timeoutMs: 5_000, retryDelayMs: 1 }, }); @@ -258,6 +265,7 @@ test('a response body cut off after the headers discloses an unresolved outcome' }); const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: driver.endpoint, requestPolicy: { timeoutMs: 5_000, retryDelayMs: 1 }, }); @@ -283,6 +291,7 @@ test('a response body cut off after the headers discloses an unresolved outcome' test('a 5xx response to a POST discloses an unresolved outcome and is not resent', async () => { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', requestPolicy: { timeoutMs: 30_000, retryAttempts: 1, retryDelayMs: 1 }, }); @@ -309,6 +318,7 @@ test('a 5xx response to a POST discloses an unresolved outcome and is not resent test('a 5xx with a non-JSON body keeps its status, dispatch disclosure, and idempotent retry', async () => { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', requestPolicy: { timeoutMs: 30_000, retryAttempts: 1, retryDelayMs: 1 }, }); @@ -337,6 +347,7 @@ for (const status of [404, 405, 501]) { test(`a non-JSON HTTP ${status} page is not an unsupported route`, async () => { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', requestPolicy: { timeoutMs: 30_000, retryAttempts: 0 }, }); @@ -359,6 +370,7 @@ for (const status of [404, 405, 501]) { test('a 2xx with a non-JSON body names its status', async () => { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', requestPolicy: { timeoutMs: 30_000, retryAttempts: 0 }, }); @@ -396,6 +408,7 @@ for (const { status, body, unsupported } of ROUTE_ANSWERS) { test(`HTTP ${status} ${JSON.stringify(body)} is ${unsupported ? '' : 'not '}an unsupported route`, async () => { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', diagnostics: { emit: emitDiagnostic }, }); @@ -439,6 +452,7 @@ function nestedCause(code: string, layers: number): Error { async function dispatchedAfter(failure: TypeError): Promise { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint: 'http://cloud-webdriver.test/wd/hub/', }); globalThis.fetch = async () => { @@ -475,6 +489,7 @@ test('a pre-connect code is read to the depth cap and not beyond', async () => { async function postActions(endpoint: string, timeoutMs = 5_000): Promise { const transport = new WebDriverTransport({ clientVersion: '0.0.0-test', + env: {}, endpoint, requestPolicy: { timeoutMs, retryDelayMs: 1 }, }); @@ -537,3 +552,77 @@ for (const row of ROWS) { }); }); } + +function hasReason(reason: string, limitBytes?: number) { + return (error: unknown) => + error instanceof AppError && + error.details?.reason === reason && + (limitBytes === undefined || error.details?.limitBytes === limitBytes); +} + +const credentialed = { + clientVersion: 'test', + env: {}, + endpoint: 'https://provider.example/wd/hub', + auth: { username: 'name', accessKey: 'key' }, + requestPolicy: { retryAttempts: 0 }, +}; + +function oversizedBody(bytes: number, cancel: () => void): Response { + return new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(bytes)); + }, + cancel, + }), + ); +} + +test('a credentialed transport refuses a public http endpoint unless the override is set', () => { + const options = { ...credentialed, endpoint: 'http://provider.example/wd/hub' }; + assert.throws(() => new WebDriverTransport(options), hasReason('insecure_credential_transport')); + assert.doesNotThrow( + () => + new WebDriverTransport({ ...options, env: { AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1' } }), + ); +}); + +test('a credentialed redirect is refused with a typed reason', async () => { + globalThis.fetch = async (_url, init) => { + assert.equal(init?.redirect, 'manual'); + return new Response(null, { status: 307, headers: { location: 'https://elsewhere.test/' } }); + }; + await assert.rejects( + new WebDriverTransport(credentialed).requestValue('GET', 'status'), + hasReason('provider_redirect_refused'), + ); +}); + +test('an uncredentialed transport follows a redirect', async () => { + globalThis.fetch = async (_url, init) => { + assert.equal(init?.redirect, 'follow'); + return new Response(JSON.stringify({ value: { ready: true } })); + }; + const transport = new WebDriverTransport({ ...credentialed, auth: undefined }); + assert.deepEqual(await transport.requestValue('GET', 'status'), { ready: true }); +}); + +test('an oversized answer is canceled at the text budget, and a screenshot gets the large budget', async () => { + const cancel = vi.fn(); + globalThis.fetch = async () => oversizedBody(1024 * 1024 + 1, cancel); + const transport = new WebDriverTransport(credentialed); + await assert.rejects( + transport.requestValue('GET', 'status'), + hasReason('provider_response_too_large', 1024 * 1024), + ); + assert.equal(cancel.mock.calls.length, 1); + globalThis.fetch = async () => oversizedBody(32 * 1024 * 1024 + 1, cancel); + await assert.rejects( + transport.requestValue('GET', 'screenshot', undefined, { + responseLimitBytes: 32 * 1024 * 1024, + }), + hasReason('provider_response_too_large', 32 * 1024 * 1024), + ); + assert.equal(cancel.mock.calls.length, 2); +}); diff --git a/packages/provider-webdriver/src/webdriver-transport.ts b/packages/provider-webdriver/src/webdriver-transport.ts index 83652d96d40..ba0d928f540 100644 --- a/packages/provider-webdriver/src/webdriver-transport.ts +++ b/packages/provider-webdriver/src/webdriver-transport.ts @@ -1,7 +1,10 @@ +import type { EnvMap } from '@agent-device/kernel/source-value'; import { setTimeout as sleep } from 'node:timers/promises'; import type { DiagnosticEventInput } from '@agent-device/contracts/host-diagnostics'; import { AppError, type DispatchDisclosure, type ReasonTable } from '@agent-device/kernel/errors'; +import { readBoundedResponseText, refuseRedirect } from '@agent-device/host-kit/response-body'; import { agentDeviceRequestHeaders } from './request-headers.ts'; +import { admitCredentialDestination } from '@agent-device/host-kit/credential-admission'; import { basicAuthHeader, trimLeadingSlash, withTrailingSlash } from './webdriver-utils.ts'; /** Why a WebDriver request failed at the transport. */ @@ -91,10 +94,13 @@ export type WebDriverRequestOverrides = { timeoutMs?: number; /** Request-bound cancellation supplied by a runtime binding. */ signal?: AbortSignal; + /** Byte budget for a successful answer; an unsuccessful answer always gets the text budget. */ + responseLimitBytes?: number; }; export type WebDriverTransportOptions = { clientVersion: string; + env: Readonly; endpoint: string | URL; auth?: WebDriverAuth; headers?: Record; @@ -112,6 +118,7 @@ type ResolvedWebDriverRequestOverrides = { timeoutMs: number; retryAttempts: number; signal?: AbortSignal; + responseLimitBytes?: number; }; type ResolvedWebDriverRequestPolicy = Required< @@ -139,12 +146,15 @@ export type WebDriverAnswer = { status: number; value: unknown }; /** Focused HTTP/retry policy for one WebDriver endpoint; session semantics stay in WebDriverClient. */ export class WebDriverTransport { private readonly endpoint: URL; + private readonly credentialed: boolean; private readonly headers: Record; private readonly requestPolicy: ResolvedWebDriverRequestPolicy; private readonly diagnostics: WebDriverTransportOptions['diagnostics']; constructor(options: WebDriverTransportOptions) { this.diagnostics = options.diagnostics; + this.credentialed = options.auth !== undefined; + if (options.auth) admitCredentialDestination(String(options.endpoint), options.env); this.endpoint = withTrailingSlash(new URL(options.endpoint)); this.headers = { ...agentDeviceRequestHeaders(options.clientVersion), @@ -180,6 +190,7 @@ export class WebDriverTransport { overrides?.retryAttempts ?? (idempotent ? this.requestPolicy.retryAttempts : 0), timeoutMs: overrides?.timeoutMs ?? this.requestPolicy.timeoutMs, signal: overrides?.signal, + responseLimitBytes: overrides?.responseLimitBytes, }); } @@ -192,7 +203,7 @@ export class WebDriverTransport { let lastError: unknown; for (let attempt = 0; attempt <= overrides.retryAttempts; attempt += 1) { try { - return await this.requestOnce(method, path, body, overrides.timeoutMs, overrides.signal); + return await this.requestOnce(method, path, body, overrides); } catch (error) { lastError = error; if ( @@ -210,16 +221,9 @@ export class WebDriverTransport { method: string, path: string, body: unknown, - timeoutMs: number, - requestSignal?: AbortSignal, + overrides: ResolvedWebDriverRequestOverrides, ): Promise { - const { ok, status, text } = await this.fetchWebDriver( - method, - path, - body, - timeoutMs, - requestSignal, - ); + const { ok, status, text } = await this.fetchWebDriver(method, path, body, overrides); if (ok) return { status, value: readWebDriverValue(text ? parseJsonResponse(text, status) : {}) }; const parsed = text ? parseJsonBody(text) : { json: {} }; @@ -245,8 +249,7 @@ export class WebDriverTransport { method: string, path: string, body: unknown, - timeoutMs: number, - requestSignal?: AbortSignal, + { timeoutMs, signal: requestSignal, responseLimitBytes }: ResolvedWebDriverRequestOverrides, ): Promise & { text: string }> { const url = new URL(trimLeadingSlash(path), this.endpoint); const payload = body === undefined && method === 'POST' ? EMPTY_POST_BODY : body; @@ -257,6 +260,7 @@ export class WebDriverTransport { try { response = await fetch(url, { method, + redirect: this.credentialed ? 'manual' : 'follow', headers: { Accept: 'application/json', ...(payload === undefined ? {} : { 'Content-Type': 'application/json' }), @@ -269,8 +273,14 @@ export class WebDriverTransport { throw classifyWebDriverFetchFailure(error, failure, 'request'); } try { - return { ok: response.ok, status: response.status, text: await response.text() }; + if (this.credentialed) await refuseRedirect(response); + return { + ok: response.ok, + status: response.status, + text: await readBoundedResponseText(response, response.ok ? responseLimitBytes : undefined), + }; } 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..59e6a1aa427 100644 --- a/packages/provider-webdriver/src/webdriver-utils.test.ts +++ b/packages/provider-webdriver/src/webdriver-utils.test.ts @@ -7,6 +7,8 @@ import { AppError } from '@agent-device/kernel/errors'; import { asOptionalRecord } from '@agent-device/kernel/record'; import { appendUrlPath, + fetchProviderSessionDetails, + fetchProviderVerificationJson, appFileUploadForm, createHubUploadApp, postHubAppUpload, @@ -45,6 +47,7 @@ const hub = { service: 'Hub', endpoint: 'https://upload.example.test/app', clientVersion: '0.0.0-test', + env: {}, auth: { username: 'user', accessKey: 'key' }, readAppReference: (body: unknown) => asOptionalRecord(body)?.ref as string | undefined, }; @@ -108,12 +111,15 @@ test('the hub upload helper fails typed when its deadline ends a stalled upload' // Only the deadline the upload arms can end this fetch; without it the spy is never called. const deadline = new AbortController(); const timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockImplementation(() => deadline.signal); + let fetchStarted = false; globalThis.fetch = async (_input, init) => await new Promise((_resolve, reject) => { + fetchStarted = true; init?.signal?.addEventListener('abort', () => reject(init.signal?.reason as Error)); }); try { const pending = postHubAppUpload(new FormData(), hub); + await vi.waitFor(() => assert.ok(fetchStarted)); assert.deepEqual(timeoutSpy.mock.calls, [[15 * 60_000]]); const timeout = new DOMException('The operation was aborted due to timeout', 'TimeoutError'); deadline.abort(timeout); @@ -368,3 +374,47 @@ test('a local app artifact must be an existing file under the connect cwd', asyn message: `Example app file not found: ${path.resolve(tempDir, '.')}`, }); }); + +function hasReason(reason: string) { + return (error: unknown) => error instanceof AppError && error.details?.reason === reason; +} + +test('credentialed provider requests refuse a public http endpoint before fetch', async () => { + const fetchCalls = vi.fn(); + globalThis.fetch = fetchCalls; + const endpoint = 'http://provider.example/api'; + const blocked = hasReason('insecure_credential_transport'); + await assert.rejects(postHubAppUpload(new FormData(), { ...hub, endpoint }), blocked); + await assert.rejects( + fetchProviderSessionDetails(endpoint, { + clientVersion: hub.clientVersion, + env: hub.env, + auth: hub.auth, + service: hub.service, + }), + blocked, + ); + await assert.rejects( + fetchProviderVerificationJson(endpoint, { + clientVersion: hub.clientVersion, + env: hub.env, + auth: hub.auth, + hints: { service: hub.service, unauthorizedHint: 'credentials', networkHint: 'network' }, + }), + blocked, + ); + assert.equal(fetchCalls.mock.calls.length, 0); +}); + +test('a credentialed upload refuses a redirect and an oversized reply', async () => { + globalThis.fetch = async () => new Response(null, { status: 302, headers: { location: '/x' } }); + await assert.rejects( + postHubAppUpload(new FormData(), hub), + hasReason('provider_redirect_refused'), + ); + globalThis.fetch = async () => new Response(new Uint8Array(1024 * 1024 + 1)); + await assert.rejects( + postHubAppUpload(new FormData(), hub), + hasReason('provider_response_too_large'), + ); +}); diff --git a/packages/provider-webdriver/src/webdriver-utils.ts b/packages/provider-webdriver/src/webdriver-utils.ts index 07057f3010e..651202dc300 100644 --- a/packages/provider-webdriver/src/webdriver-utils.ts +++ b/packages/provider-webdriver/src/webdriver-utils.ts @@ -1,3 +1,4 @@ +import type { EnvMap } from '@agent-device/kernel/source-value'; import fs from 'node:fs'; import { stat } from 'node:fs/promises'; import path from 'node:path'; @@ -74,6 +75,30 @@ export function withTrailingSlash(url: URL): URL { type HubCredentials = { username: string; accessKey: string }; +/** Refuses a cleartext public endpoint before a credential is built for it. */ +export async function admitCredentialedEndpoint( + endpoint: string | URL, + env: Readonly, +): Promise { + const { admitCredentialDestination } = + await import('@agent-device/host-kit/credential-admission'); + admitCredentialDestination(String(endpoint), env); + try { + return new URL(endpoint); + } catch (error) { + throw new AppError( + 'INVALID_ARGS', + 'Provider endpoint is not a valid URL.', + { hint: 'Set the provider endpoint to an absolute HTTPS URL.' }, + error, + ); + } +} + +async function loadResponseBody() { + return await import('@agent-device/host-kit/response-body'); +} + /** * 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, @@ -121,16 +146,19 @@ export async function postHubAppUpload( service: string; endpoint: string | URL; clientVersion: string; + env: Readonly; auth: HubCredentials; readAppReference: (body: unknown) => string | undefined; }, signal?: AbortSignal, ): Promise { + const endpoint = await admitCredentialedEndpoint(options.endpoint, options.env); 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, { + redirect: 'manual', method: 'POST', headers: { ...agentDeviceRequestHeaders(options.clientVersion), @@ -139,9 +167,10 @@ export async function postHubAppUpload( body: form, signal: signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal, }); + await (await loadResponseBody()).refuseRedirect(response); json = await readProviderJsonBody(response); } catch (error) { - if (signal?.aborted) throw error; + if (signal?.aborted || error instanceof AppError) throw error; const timedOut = timeoutSignal.aborted; throw new AppError( 'COMMAND_FAILED', @@ -255,6 +284,7 @@ export async function fetchProviderVerificationJson( endpoint: string | URL, options: { clientVersion: string; + env: Readonly; /** Omitted for a public catalog endpoint. */ auth?: { username: string; accessKey: string }; hints: ProviderJsonFailureHints; @@ -262,14 +292,19 @@ export async function fetchProviderVerificationJson( ): Promise { const { service, unauthorizedHint, networkHint } = options.hints; const serviceHint = `Retry connect or check the ${service} service status.`; + const destination = options.auth + ? await admitCredentialedEndpoint(endpoint, options.env) + : endpoint; try { - const response = await fetch(endpoint, { + const response = await fetch(destination, { + redirect: options.auth ? 'manual' : 'follow', headers: { ...agentDeviceRequestHeaders(options.clientVersion), ...(options.auth ? { Authorization: basicAuthHeader(options.auth) } : {}), }, signal: AbortSignal.timeout(PROVIDER_API_TIMEOUT_MS), }); + if (options.auth) await (await loadResponseBody()).refuseRedirect(response); if (!response.ok) { const unauthorized = response.status === 401 || response.status === 403; throw new AppError( @@ -281,7 +316,8 @@ export async function fetchProviderVerificationJson( }, ); } - const json = await readProviderJsonBody(response); + // A catalog or app list may be a large inventory. + const json = await readProviderJsonBody(response, 'large'); if (json === undefined) { throw new AppError( 'COMMAND_FAILED', @@ -309,22 +345,27 @@ export async function fetchProviderSessionDetails( endpoint: string | URL, options: { clientVersion: string; + env: Readonly; auth: { username: string; accessKey: string }; service: string; }, ): Promise> { + const destination = await admitCredentialedEndpoint(endpoint, options.env); let response: Response; let json: unknown; try { - response = await fetch(endpoint, { + response = await fetch(destination, { + redirect: 'manual', headers: { ...agentDeviceRequestHeaders(options.clientVersion), Authorization: basicAuthHeader(options.auth), }, signal: AbortSignal.timeout(PROVIDER_API_TIMEOUT_MS), }); + await (await loadResponseBody()).refuseRedirect(response); json = await readProviderJsonBody(response); } catch (error) { + if (error instanceof AppError) throw error; throw new AppError( 'COMMAND_FAILED', `${options.service} session details lookup failed.`, @@ -346,8 +387,12 @@ 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(); +async function readProviderJsonBody(response: Response, budget?: 'large'): Promise { + const { PROVIDER_LARGE_BODY_LIMIT_BYTES, readBoundedResponseText } = await loadResponseBody(); + const text = await readBoundedResponseText( + response, + budget === 'large' ? PROVIDER_LARGE_BODY_LIMIT_BYTES : undefined, + ); if (text.length === 0) return undefined; try { return JSON.parse(text) as unknown; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 633a1c54e9f..e24c3c1c4d4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1163,6 +1163,9 @@ importers: '@agent-device/contracts': specifier: workspace:* version: link:../contracts + '@agent-device/host-kit': + specifier: workspace:* + version: link:../host-kit '@agent-device/kernel': specifier: workspace:* version: link:../kernel @@ -1173,9 +1176,6 @@ importers: '@agent-device/gestures': specifier: workspace:* version: link:../gestures - '@agent-device/host-kit': - specifier: workspace:* - version: link:../host-kit '@agent-device/test-kit': specifier: workspace:* version: link:../test-kit diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index 040ee28c27f..b1837f363f5 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -626,6 +626,7 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/host-kit/process', '@agent-device/host-kit/project-runtime', '@agent-device/host-kit/request', + '@agent-device/host-kit/response-body', '@agent-device/host-kit/retry', '@agent-device/host-kit/runtime-slots', '@agent-device/host-kit/runtime-transport-hints', @@ -826,6 +827,7 @@ test('the real tree parses, declares, and passes R11', () => { assert.deepEqual([...providerWebDriverPackage.workspaceDependencies].sort(), [ '@agent-device/capture-kit', '@agent-device/contracts', + '@agent-device/host-kit', '@agent-device/kernel', '@agent-device/xml', ]); diff --git a/src/provider-plugin-host-capabilities-limrun-ios-runner.test.ts b/src/provider-plugin-host-capabilities-limrun-ios-runner.test.ts index 160f3826c94..0c6922a7c33 100644 --- a/src/provider-plugin-host-capabilities-limrun-ios-runner.test.ts +++ b/src/provider-plugin-host-capabilities-limrun-ios-runner.test.ts @@ -141,12 +141,12 @@ 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; + const readBody = Object.getOwnPropertyDescriptor(Response.prototype, 'body')!.get!; const responseBody = vi - .spyOn(Response.prototype, 'text') + .spyOn(Response.prototype, 'body', 'get') .mockImplementation(function (this: Response) { if (this.status === 409) markReadStarted(); - return readText.call(this); + return readBody.call(this); }); const realTimeout = AbortSignal.timeout.bind(AbortSignal); const timer = vi @@ -241,14 +241,29 @@ test.each([ const conflict = new Promise((resolve) => { conflictRead = resolve; }); - const originalText = Response.prototype.text; - const responseBody = vi - .spyOn(Response.prototype, 'text') - .mockImplementation(async function (this: Response) { - const body = await originalText.call(this); - if (this.status === 409) conflictRead(); - return body; + const readBody = Object.getOwnPropertyDescriptor(Response.prototype, 'body')!.get!; + const decode = TextDecoder.prototype.decode; + let conflictBodyRequested = false; + const bodyGetter = vi + .spyOn(Response.prototype, 'body', 'get') + .mockImplementation(function (this: Response) { + if (this.status === 409) conflictBodyRequested = true; + return readBody.call(this); }); + const decoder = vi.spyOn(TextDecoder.prototype, 'decode').mockImplementation(function ( + this: TextDecoder, + ...args + ) { + const text = decode.apply(this, args); + if (conflictBodyRequested) conflictRead(); + return text; + }); + const responseBody = { + mockRestore() { + bodyGetter.mockRestore(); + decoder.mockRestore(); + }, + }; vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); try { const restart = new AbortController(); 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/browserstack.md b/website/docs/docs/browserstack.md index dae4e83d50c..ea98fd4c229 100644 --- a/website/docs/docs/browserstack.md +++ b/website/docs/docs/browserstack.md @@ -139,3 +139,5 @@ After `close`, BrowserStack can return session video, Appium logs, device logs, BrowserStack errors distinguish rejected credentials, an unavailable device/OS pair, a missing `bs://` upload, and a missing local app file. To enter text, see [Fill text on hosted WebDriver sessions](/docs/device-clouds#fill-text-on-hosted-webdriver-sessions). + +Endpoints that receive credentials must use HTTPS. HTTP is accepted on loopback, or when `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1` is set. Redirects from credentialed requests are refused. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 33c3d3f084f..7d9fa7d9cfc 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -982,6 +982,7 @@ These reasons can come from more than one command. | `limrun_download_http_error` | The instance refused the download; its HTTP status answers for the refusal. | | `limrun_download_timeout` | The transfer's own deadline passed before the file reached disk. | | `limrun_download_failed` | The request or transfer failed, including when an authenticated endpoint redirects. | +| `limrun_download_too_large` | The download body is larger than the byte budget, so the transfer stopped. | | `limrun_download_endpoint_blocked` | An authenticated download requires HTTPS on the instance origin. | | `limrun_instance_command_failed` | The instance refused or could not answer the command; its text, with this session's credential removed, is the message. | | `limrun_file_response_invalid` | The instance returned an unreadable JSON reply for a simulator file operation. | @@ -1071,6 +1072,13 @@ These reasons can come from more than one command. | --- | --- | | `provider_instance_unallocated` | The provider connection has no live instance. Allocate one with open, boot, or leases.allocate. | +### Provider response + +| Reason | Meaning | +| --- | --- | +| `provider_response_too_large` | A provider response body is larger than the byte budget its caller allows. | +| `provider_redirect_refused` | A provider answered a credentialed request with a redirect, which the sender never follows. | + ### Provider runtime admission | Reason | Meaning | diff --git a/website/docs/docs/testmu.md b/website/docs/docs/testmu.md index cdc59a02608..b0d8cf3f1b3 100644 --- a/website/docs/docs/testmu.md +++ b/website/docs/docs/testmu.md @@ -207,3 +207,5 @@ app list that `connect` uses to check credentials always comes from `https://manual-api.lambdatest.com/app/data`. To enter text, see [Fill text on hosted WebDriver sessions](/docs/device-clouds#fill-text-on-hosted-webdriver-sessions). + +Endpoints that receive credentials must use HTTPS. HTTP is accepted on loopback, or when `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1` is set. Redirects from credentialed requests are refused (`provider_redirect_refused`), so configure each credentialed endpoint with its final HTTPS URL, not a URL that redirects.