Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/host-kit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
49 changes: 49 additions & 0 deletions packages/host-kit/src/response-body.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
61 changes: 61 additions & 0 deletions packages/host-kit/src/response-body.ts
Original file line number Diff line number Diff line change
@@ -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<Uint8Array> {
const reader = response.body?.getReader();
Comment thread
thymikee marked this conversation as resolved.
Resolved
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,
});
}
Comment thread
thymikee marked this conversation as resolved.
Resolved
chunks.push(value);
}
} finally {
await reader.cancel().catch(() => {});
}
}

export async function readBoundedResponseText(
response: Response,
maxBytes?: number,
): Promise<string> {
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<void> {
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,
},
);
}
Comment thread
thymikee marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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<EnvMap> };

export async function verifyBrowserStackConnection(
options: BrowserStackConnectionVerificationOptions,
clientVersion: string,
client: ProviderRequestClient,
): Promise<BrowserStackConnectionVerification> {
const { parseBrowserStackAppReference } = await import('./browserstack.ts');
const { sameOsVersion } = await import('@agent-device/provider-webdriver/plugin');
Comment thread
thymikee marked this conversation as resolved.
Resolved
Expand All @@ -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) =>
Expand All @@ -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',
Expand All @@ -79,14 +83,14 @@ async function verifyBrowserStackApp(
app: string,
options: BrowserStackConnectionVerificationOptions,
auth: { username: string; accessKey: string },
clientVersion: string,
client: ProviderRequestClient,
): Promise<ProviderConnectionResource> {
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) {
Expand Down Expand Up @@ -117,11 +121,11 @@ async function verifyBrowserStackApp(
async function fetchBrowserStackJson(
endpoint: string | URL,
auth: { username: string; accessKey: string },
clientVersion: string,
client: ProviderRequestClient,
): Promise<unknown> {
const { fetchProviderVerificationJson } = await import('@agent-device/provider-webdriver/plugin');
return await fetchProviderVerificationJson(endpoint, {
clientVersion,
...client,
auth,
hints: {
service: 'BrowserStack',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() }),
Expand Down
3 changes: 3 additions & 0 deletions packages/provider-browserstack/src/browserstack-webdriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
}),
Expand All @@ -60,6 +62,7 @@ function createBrowserStackWebDriver(host: ProviderPluginHost): CloudWebDriverRu
);
const upload = {
clientVersion,
env,
...credentials,
endpoint: env.BROWSERSTACK_APP_UPLOAD_ENDPOINT ?? BROWSERSTACK_APP_UPLOAD_ENDPOINT,
};
Expand Down
3 changes: 2 additions & 1 deletion packages/provider-browserstack/src/browserstack.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
},
Expand All @@ -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-');
Expand Down
11 changes: 10 additions & 1 deletion packages/provider-browserstack/src/browserstack.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -54,6 +56,7 @@ export type BrowserStackCapabilitiesOptions = {

export type BrowserStackSessionDetailsOptions = {
clientVersion: string;
env: Readonly<EnvMap>;
username: string;
accessKey: string;
endpoint?: string | URL;
Expand All @@ -77,6 +80,7 @@ export async function listBrowserStackCloudArtifacts(

export type BrowserStackUploadOptions = {
clientVersion: string;
env: Readonly<EnvMap>;
username: string;
accessKey: string;
endpoint?: string | URL;
Expand All @@ -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,
},
Expand Down Expand Up @@ -182,11 +187,15 @@ async function fetchBrowserStackSessionDetails(
options: BrowserStackSessionDetailsOptions,
): Promise<Record<string, unknown>> {
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',
});
Expand Down
2 changes: 1 addition & 1 deletion packages/provider-browserstack/src/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export function createBrowserStackConnection(
),
app: requireResolvedProfileValue(flags.providerApp, 'BrowserStack profile missed app.'),
},
host.clientVersion,
{ clientVersion: host.clientVersion, env: host.env },
),
};
}
Expand Down
15 changes: 15 additions & 0 deletions packages/provider-limrun/src/download-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Comment thread
thymikee marked this conversation as resolved.
Resolved
});
expect(fs.existsSync(destinationPath)).toBe(false);
});
27 changes: 24 additions & 3 deletions packages/provider-limrun/src/download-file.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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'>;
Expand All @@ -39,7 +41,25 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise<v
const url = instance ? instanceDownloadUrl(instance.apiUrl, options.url) : options.url;
await fs.promises.mkdir(path.dirname(options.destinationPath), { recursive: true });
const body = await openFetchDownload(url, instance?.token, signal);
await writeDownloadBody(body, options.destinationPath, signal);
const { createByteLimitStream, MAX_ARTIFACT_COMPRESSED_BYTES } =
await import('@agent-device/host-kit/archive');
const maxBytes = Math.min(
options.maxBytes ?? MAX_ARTIFACT_COMPRESSED_BYTES,
MAX_ARTIFACT_COMPRESSED_BYTES,
);
await writeDownloadBody(
body,
options.destinationPath,
signal,
createByteLimitStream({
maxBytes,
createLimitError: () =>
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);
Expand Down Expand Up @@ -69,14 +89,15 @@ async function writeDownloadBody(
body: WebReadableStream<Uint8Array> | null,
destinationPath: string,
signal: AbortSignal,
limit: Transform,
): Promise<void> {
if (!body) {
throw new AppError('COMMAND_FAILED', 'Limrun download returned no body', {
reason: LIMRUN_DOWNLOAD_REASONS.emptyBody.reason,
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 {
Expand Down
Loading
Loading