diff --git a/packages/command-surface/src/cli-grammar/types.ts b/packages/command-surface/src/cli-grammar/types.ts index a83175f7f71..6c2645879af 100644 --- a/packages/command-surface/src/cli-grammar/types.ts +++ b/packages/command-surface/src/cli-grammar/types.ts @@ -89,7 +89,7 @@ export type SelectionOptions = { export type CliInput = Record; export type CliReader = (positionals: string[], flags: CliFlags) => CliInput; /** Builds the daemon request for one command. Most writers are pure projections of their input. */ -export type DaemonWriter = (input: CommandInput) => DaemonCommandRequest; +export type DaemonWriter = (input: CommandInput, host?: HostEnvironment) => DaemonCommandRequest; /** * A writer that has caller-side work to do before the request exists: reading the replay script diff --git a/packages/command-surface/src/index.ts b/packages/command-surface/src/index.ts index b9362b6a88b..20536318159 100644 --- a/packages/command-surface/src/index.ts +++ b/packages/command-surface/src/index.ts @@ -81,7 +81,7 @@ async function prepareBatchDaemonCommandRequest( throw new AppError( 'INVALID_ARGS', `Batch step ${stepNumber} ${command} input is invalid: ${message}`, - undefined, + error instanceof AppError ? error.details : undefined, error, ); } diff --git a/packages/command-surface/src/replay/index.test.ts b/packages/command-surface/src/replay/index.test.ts index f21d7fb236f..5a6bf0ae338 100644 --- a/packages/command-surface/src/replay/index.test.ts +++ b/packages/command-surface/src/replay/index.test.ts @@ -159,6 +159,16 @@ describe('replay command interface', () => { } }); + test('prepares a large suite for daemon admission', async () => { + const root = mkdtempForTestSync('agent-device-replay-count-'); + for (let index = 0; index < 257; index += 1) { + fs.writeFileSync(path.join(root, `${index}.ad`), ''); + } + const host = { env: {}, cwd: root }; + const request = await testDaemonWriter({ paths: ['.'] }, host); + expect(request.options.replayScriptSources).toHaveLength(257); + }); + test('validates -e keys with the grammar of the resolved replay format', async () => { fs.writeFileSync(path.join(SCRIPT_ROOT, 'flow.yaml'), 'appId: demo.app\n---\n- back\n'); const host = { env: {}, cwd: SCRIPT_ROOT }; diff --git a/packages/command-surface/src/replay/index.ts b/packages/command-surface/src/replay/index.ts index 8fe72d95a84..8d3436bb7b2 100644 --- a/packages/command-surface/src/replay/index.ts +++ b/packages/command-surface/src/replay/index.ts @@ -249,6 +249,16 @@ export const replayDaemonWriter: AsyncDaemonWriter = async (input, host) => { const inputPath = requiredDaemonString(input.path, 'replay requires path'); const replayBackend = readReplayBackend(input); const replayShellEnv = collectReplayClientShellEnv(host.env); + const replayScriptSource = await loadReplayScriptSourceBundle({ + inputPath, + cwd: readReplayClientCwd(input, host.cwd), + replayBackend, + env: readReplayScriptSourceEnv( + input, + replayShellEnv, + resolveReplayFormat(inputPath, replayBackend), + ), + }); return request(REPLAY_COMMAND_NAME, [inputPath], { ...input, replayUpdate: input.update, @@ -258,16 +268,7 @@ export const replayDaemonWriter: AsyncDaemonWriter = async (input, host) => { // #1802: the caller owns the flow files, so it reads them here — the same // client-collects-local-input move `replayShellEnv` already makes — and // the daemon executes only what arrives in this bundle. - replayScriptSource: await loadReplayScriptSourceBundle({ - inputPath, - cwd: readReplayClientCwd(input, host.cwd), - replayBackend, - env: readReplayScriptSourceEnv( - input, - replayShellEnv, - resolveReplayFormat(inputPath, replayBackend), - ), - }), + replayScriptSource, replayFrom: input.resumeFrom, replayPlanDigest: input.resumePlanDigest, replayKeepSession: input.keepSession, @@ -280,6 +281,22 @@ export const testDaemonWriter: AsyncDaemonWriter = async (input, host) => { const replayBackend = readReplayBackend(input); const cwd = readReplayClientCwd(input, host.cwd); const replayShellEnv = collectReplayClientShellEnv(host.env); + const paths = discoverReplaySourcePaths({ inputs, cwd, replayBackend }); + const sources = await Promise.all( + paths.map( + async (inputPath) => + await loadReplayScriptSourceBundle({ + inputPath, + cwd, + replayBackend, + env: readReplayScriptSourceEnv( + input, + replayShellEnv, + resolveReplayFormat(inputPath, replayBackend), + ), + }), + ), + ); return request(TEST_COMMAND_NAME, inputs, { ...stripReplayTestPresentationInput(input), replayUpdate: input.update, @@ -289,21 +306,7 @@ export const testDaemonWriter: AsyncDaemonWriter = async (input, host) => { // #1802: `test` inputs are paths, directories, and globs on the CALLER's // filesystem. Expanding them here keeps discovery order identical for a // local and a remote daemon and ships each discovered source's text. - replayScriptSources: await Promise.all( - discoverReplaySourcePaths({ inputs, cwd, replayBackend }).map( - async (inputPath) => - await loadReplayScriptSourceBundle({ - inputPath, - cwd, - replayBackend, - env: readReplayScriptSourceEnv( - input, - replayShellEnv, - resolveReplayFormat(inputPath, replayBackend), - ), - }), - ), - ), + replayScriptSources: sources, }); }; @@ -330,7 +333,7 @@ export const testCommandFacet = defineCommandFacet({ summary: 'Run replay test suites', searchHint: 'tests ad', cliDetail: - "Relative globs are expanded on the caller from its working directory, whose name is treated literally. Quote glob inputs to defer expansion to test. Copied diagnostic artifacts receive numbered filenames when needed to preserve other artifacts, replay sources, timing traces, and attempt manifests. JUnit reports (--reporter junit:) replace characters forbidden by XML 1.0 with U+FFFD and preserve legal Unicode and whitespace. JSON and other reporters retain the original suite values. Custom reporter getExitCode hooks must return an integer from 0 to 255 or undefined; the highest valid code wins and cannot lower a failing suite's exit code. A nested test stops after a bounded resource refusal even with --retries; other failures keep their configured retries.", + "Relative globs are expanded on the caller from its working directory, whose name is treated literally. Quote glob inputs to defer expansion to test. A public-network remote daemon accepts at most 2 MiB of source text, 256 source bundles, and 2,048 files per request; split a larger suite into smaller invocations. These count limits do not apply to a local daemon. Copied diagnostic artifacts receive numbered filenames when needed to preserve other artifacts, replay sources, timing traces, and attempt manifests. JUnit reports (--reporter junit:) replace characters forbidden by XML 1.0 with U+FFFD and preserve legal Unicode and whitespace. JSON and other reporters retain the original suite values. Custom reporter getExitCode hooks must return an integer from 0 to 255 or undefined; the highest valid code wins and cannot lower a failing suite's exit code. A nested test stops after a bounded resource refusal even with --retries; other failures keep their configured retries.", }, metadata: testCommandMetadata, run: (client, input) => client.replay.test(withCommandRuntimeHints(input)), diff --git a/packages/contracts/src/facades/remote.ts b/packages/contracts/src/facades/remote.ts index 820d3c79b67..abf4b6a367c 100644 --- a/packages/contracts/src/facades/remote.ts +++ b/packages/contracts/src/facades/remote.ts @@ -1,3 +1,5 @@ +import type { ReasonTable } from '@agent-device/kernel/errors'; + export type { CompanionTunnelScope, MetroBridgeScope } from '../companion-tunnel-scope.ts'; export type { MetroBridgeResult, @@ -22,6 +24,13 @@ export { PROVIDER_PROFILE_FIELD_FLAG_ALIASES, PROVIDER_PROFILE_FIELD_FLAGS, } from '../remote-config-fields.ts'; + +/** Why a provider response was rejected before its body was accepted. */ +export const PROVIDER_RESPONSE_REASONS = { + // A provider answered with more bytes than the response budget allows. + tooLarge: { reason: 'provider_response_too_large' }, +} as const satisfies ReasonTable<'provider response'>; + export type { CloudProviderProfileFields, DaemonRpcMode, diff --git a/packages/contracts/src/platform-providers.ts b/packages/contracts/src/platform-providers.ts index 7519e10d4d1..a6438392b43 100644 --- a/packages/contracts/src/platform-providers.ts +++ b/packages/contracts/src/platform-providers.ts @@ -24,6 +24,8 @@ export type PlatformProviderRequestContext = Readonly<{ requestId?: string; /** Daemon policy says that the root may construct its managed Web provider for this request. */ useDefaultWebProvider?: boolean; + /** The daemon's trusted remote-tenant policy for this request. */ + publicNetworkOnly?: true; }>; /** The only request-scoped platform value currently consumed by daemon handlers. diff --git a/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts b/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts index fbc7ee2017d..adf56c12526 100644 --- a/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts +++ b/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts @@ -28,7 +28,6 @@ test('requireTenantOwnedEntry returns entries readable by the tenant', () => { ['owned', { tenantId: 'tenant-a' }], ]); assert.equal(requireTenantOwnedEntry(map, 'shared', undefined, RESOURCE), map.get('shared')); - assert.equal(requireTenantOwnedEntry(map, 'shared', 'tenant-b', RESOURCE), map.get('shared')); assert.equal(requireTenantOwnedEntry(map, 'owned', 'tenant-a', RESOURCE), map.get('owned')); }); @@ -43,12 +42,19 @@ test('missing entries surface as expired resources with a recovery hint', () => }); test('tenant mismatch stays UNAUTHORIZED and honors plural labels', () => { - const map = new Map([['owned', { tenantId: 'tenant-a' }]]); + const map = new Map([ + ['owned', { tenantId: 'tenant-a' }], + ['shared', {}], + ]); const singular = captureAppError(() => requireTenantOwnedEntry(map, 'owned', 'tenant-b', RESOURCE), ); assert.equal(singular.code, 'UNAUTHORIZED'); assert.equal(singular.message, 'Artifact belongs to a different tenant'); + assert.equal( + captureAppError(() => requireTenantOwnedEntry(map, 'shared', 'tenant-b', RESOURCE)).code, + 'UNAUTHORIZED', + ); const plural = captureAppError(() => requireTenantOwnedEntry(map, 'owned', undefined, { diff --git a/packages/daemon/src/core/tenant-owned-entry.ts b/packages/daemon/src/core/tenant-owned-entry.ts index 15018221c31..39c3d292f1a 100644 --- a/packages/daemon/src/core/tenant-owned-entry.ts +++ b/packages/daemon/src/core/tenant-owned-entry.ts @@ -35,10 +35,12 @@ export function requireTenantOwnedEntry( if (!entry) { throw expiredTenantOwnedEntryError(kind, id); } - if (entry.tenantId && entry.tenantId !== tenantId) { + if (entry.tenantId !== tenantId) { throw new AppError( 'UNAUTHORIZED', - `${kind.label} ${kind.plural ? 'belong' : 'belongs'} to a different tenant`, + entry.tenantId + ? `${kind.label} ${kind.plural ? 'belong' : 'belongs'} to a different tenant` + : `${kind.label} ${kind.plural ? 'are' : 'is'} not owned by a tenant`, ); } return entry; diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 2418b802a29..e09ea31c282 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -436,7 +436,7 @@ function archiveFilename(fileName: string): string { } function canReadArtifact(entry: ArtifactEntry, tenantId: string | undefined): boolean { - return !entry.cleanupRequested && (!entry.tenantId || entry.tenantId === tenantId); + return !entry.cleanupRequested && entry.tenantId === tenantId; } function safeArtifactFilename(fileName: string | undefined, fallback: string): string { diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index 64ef035c32c..fd62615a014 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -323,6 +323,14 @@ export class LeaseRegistry { assertLeaseScopeMatch(this.getActiveLease(scope.leaseId), scope); } + /** Admit a scoped read without filling an omitted backend with an allocation default. */ + assertLeaseReadAdmission(request: HeartbeatLeaseRequest): void { + this.cleanupExpiredLeases(); + const lease = this.getActiveLease(normalizeRequiredLeaseId(request.leaseId)); + assertLeaseOwnerScope(lease, request); + assertLeaseScopeMatch(lease, request); + } + /** Whether this daemon ever allocated `tenantId` a `macos-app` lease, released or not. */ hasHeldMacOsAppLease(tenantId: string): boolean { return this.macOsAppTenantIds.has(tenantId); diff --git a/packages/daemon/src/server/__tests__/http-errors-rpc-status.test.ts b/packages/daemon/src/server/__tests__/http-errors-rpc-status.test.ts index 20db8dd88d0..c362cd64ddb 100644 --- a/packages/daemon/src/server/__tests__/http-errors-rpc-status.test.ts +++ b/packages/daemon/src/server/__tests__/http-errors-rpc-status.test.ts @@ -60,3 +60,22 @@ test('a /rpc COMMAND_FAILED without the expiry reason stays a 500', async (t) => await closeLoopbackServer(server); } }); + +test('upload capacity failures answer 503 with a typed reason', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { port, server } = await startRpcServer(TOKEN, async () => ({ + ok: false, + error: { + code: 'COMMAND_FAILED', + message: 'Too many active resumable uploads', + details: { reason: 'UPLOAD_CAPACITY_EXCEEDED', retriable: true }, + }, + })); + try { + const answer = await postRpcCommand(port, TOKEN, 'req-upload-capacity'); + assert.equal(answer.status, 503); + assert.equal(answer.body.error?.data?.details?.reason, 'UPLOAD_CAPACITY_EXCEEDED'); + } finally { + await closeLoopbackServer(server); + } +}); diff --git a/packages/daemon/src/server/__tests__/http-server-artifacts.test.ts b/packages/daemon/src/server/__tests__/http-server-artifacts.test.ts index f713c1bacff..8a6497d690a 100644 --- a/packages/daemon/src/server/__tests__/http-server-artifacts.test.ts +++ b/packages/daemon/src/server/__tests__/http-server-artifacts.test.ts @@ -69,13 +69,13 @@ test('downloadable artifact inventory is filtered by tenant', async () => { (await listDownloadableArtifacts('tenant-a', process.env)).map( (artifact) => artifact.filename, ), - ['public.txt', 'tenant-a.txt'], + ['tenant-a.txt'], ); assert.deepEqual( (await listDownloadableArtifacts('tenant-b', process.env)).map( (artifact) => artifact.filename, ), - ['public.txt', 'tenant-b.txt'], + ['tenant-b.txt'], ); } finally { for (const artifactId of artifactIds) { diff --git a/packages/daemon/src/server/__tests__/http-server-rpc-admission.test.ts b/packages/daemon/src/server/__tests__/http-server-rpc-admission.test.ts index c78d61d6c11..8b33fd91fb9 100644 --- a/packages/daemon/src/server/__tests__/http-server-rpc-admission.test.ts +++ b/packages/daemon/src/server/__tests__/http-server-rpc-admission.test.ts @@ -1,7 +1,8 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; +import http from 'node:http'; import path from 'node:path'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import { @@ -96,6 +97,62 @@ test('the rpc admission registers the tracking id before consulting the auth hoo } }); +test('a disconnected rpc caller cancels a nonresolving auth hook and releases request state', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const state = globalThis as typeof globalThis & { + __rpcAuthHookSignal?: AbortSignal; + }; + const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK; + let dispatches = 0; + const { port, server } = await startWithAuthHook( + `let first = true; + export default ({ signal }) => { + if (!first) return { tenantId: 'tenant-admitted' }; + first = false; + globalThis.__rpcAuthHookSignal = signal; + return new Promise(() => {}); + };`, + async () => { + dispatches++; + return { ok: true, data: {} }; + }, + ); + try { + const request = http.request({ + host: '127.0.0.1', + port, + method: 'POST', + path: '/rpc', + headers: { authorization: `Bearer ${DAEMON_TOKEN}`, 'content-type': 'application/json' }, + }); + request.on('error', () => {}); + request.end( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'agent_device.command', + params: { + command: 'devices', + session: 'default', + meta: { requestId: 'stalled-auth-hook' }, + }, + }), + ); + await vi.waitFor(() => assert.ok(state.__rpcAuthHookSignal), { timeout: 1_000 }); + const signal = state.__rpcAuthHookSignal; + assert.ok(signal); + request.destroy(); + await vi.waitFor(() => assert.equal(signal.aborted, true), { timeout: 1_000 }); + const next = await postRpcCommand(port, DAEMON_TOKEN, 'stalled-auth-hook'); + assert.equal(next.status, 200); + assert.equal(dispatches, 1); + } finally { + delete state.__rpcAuthHookSignal; + restoreEnv('AGENT_DEVICE_HTTP_AUTH_HOOK', previousHook); + await closeLoopbackServer(server); + } +}); + function hookCalls(): number { return Number(process.env[HOOK_CALLS_ENV] ?? 0); } diff --git a/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts b/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts index 3cf669aff43..4174f8d81ad 100644 --- a/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts +++ b/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts @@ -10,6 +10,7 @@ import { trackUploadedArtifact, } from '../../resources/artifact-tracking.ts'; import { resolveInstallSource } from '../../sessions/install-source-resolution.ts'; +import { REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES } from '@agent-device/replay-port/script-source'; import { closeLoopbackServer, listenOnLoopback, @@ -270,7 +271,11 @@ test('remote HTTP accepts an uploaded path artifact without resolving the client const root = mkdtempForTestSync('agent-device-http-uploaded-path-'); const artifactPath = path.join(root, 'uploaded.apk'); fs.writeFileSync(artifactPath, 'uploaded'); - const uploadedArtifactId = trackUploadedArtifact({ artifactPath, tempDir: root }); + const uploadedArtifactId = trackUploadedArtifact({ + artifactPath, + tempDir: root, + tenantId: 'tenant-test', + }); const hookPath = writeAllowingAuthHook(root); const received: DaemonRequest[] = []; const server = await createDaemonHttpServer({ @@ -309,6 +314,39 @@ test('remote HTTP accepts an uploaded path artifact without resolving the client } }); +test('remote replay rejects an oversized raw source before dispatch', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const root = mkdtempForTestSync('agent-device-http-replay-source-limit-'); + const hookPath = writeAllowingAuthHook(root); + let handlerCalls = 0; + const server = await createDaemonHttpServer({ + env: remoteHttpEnvironment(hookPath), + handleRequest: async (): Promise => { + handlerCalls += 1; + return { ok: true, data: {} }; + }, + cwd: process.cwd(), + }); + try { + const port = await listenOnLoopback(server); + const source = 'x'.repeat(REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES + 1); + const response = await postCommandRpc(port, { + command: 'replay', + positionals: ['flow.ad'], + flags: { replayScriptSource: { entry: 'flow.ad', files: { 'flow.ad': source } } }, + }); + assert.equal(response.status, 400); + assert.equal(response.body.error?.data?.code, 'INVALID_ARGS'); + assert.deepEqual(response.body.error?.data?.details, { + limitBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, + totalBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES + 1, + }); + assert.equal(handlerCalls, 0); + } finally { + await closeLoopbackServer(server); + } +}); + test('local command RPC keeps host paths unrestricted', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const received: DaemonRequest[] = []; diff --git a/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts b/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts index a5833ede2b1..66898c9062c 100644 --- a/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts @@ -167,6 +167,81 @@ function openWebRequest(session: string): DaemonRequest { }; } +test('remote web open is refused before a browser runtime binds', async () => { + mockResolveTargetDevice.mockImplementation(webSessionResolution); + const store = makeSessionStore('agent-device-remote-web-denied-'); + let binds = 0; + const handler = createOpenHandler(store, new LeaseRegistry(), { + ...lifecycleDeviceRuntimeGateway, + bind: async (request) => { + binds += 1; + return await lifecycleDeviceRuntimeGateway.bind(request); + }, + }); + + const result = await handler({ + ...openWebRequest('remote-web'), + internal: { publicNetworkOnly: true }, + }); + expect(result).toMatchObject({ + ok: false, + error: { + code: 'UNSUPPORTED_OPERATION', + details: { reason: 'remote_web_public_network_unenforced' }, + }, + }); + expect(binds).toBe(0); + expect(store.toArray()).toEqual([]); +}); + +test('remote requests cannot use an existing web session without a platform flag', async () => { + mockResolveTargetDevice.mockImplementation(webSessionResolution); + const store = makeSessionStore('agent-device-remote-web-existing-'); + store.publish('existing-web', makeSession('existing-web', { device: WEB_DESKTOP_DEVICE })); + let binds = 0; + const handler = createOpenHandler(store, new LeaseRegistry(), { + ...lifecycleDeviceRuntimeGateway, + bind: async (request) => { + binds += 1; + return await lifecycleDeviceRuntimeGateway.bind(request); + }, + }); + + const result = await handler({ + token: 'test-token', + session: 'existing-web', + command: 'snapshot', + positionals: [], + flags: {}, + meta: { requestId: 'remote-existing-web', sessionExplicit: true }, + internal: { publicNetworkOnly: true }, + }); + expect(result).toMatchObject({ + ok: false, + error: { details: { reason: 'remote_web_public_network_unenforced' } }, + }); + expect(binds).toBe(0); +}); + +test('remote close can release an existing web session', async () => { + mockResolveTargetDevice.mockImplementation(webSessionResolution); + const store = makeSessionStore('agent-device-remote-web-close-'); + store.publish('existing-web', makeSession('existing-web', { device: WEB_DESKTOP_DEVICE })); + const handler = createOpenHandler(store); + + const result = await handler({ + token: 'test-token', + session: 'existing-web', + command: 'close', + positionals: [], + flags: {}, + meta: { requestId: 'remote-close-web', sessionExplicit: true }, + internal: { publicNetworkOnly: true }, + }); + expect(result).toMatchObject({ ok: true }); + expect(store.get('existing-web')).toBeUndefined(); +}); + test('implicit web sessions isolate workspaces and retain their device on follow-up requests', async () => { mockResolveTargetDevice.mockImplementation(webSessionResolution); const claimsDir = mkdtempForTestSync('agent-device-web-workspace-claims-'); diff --git a/packages/daemon/src/server/__tests__/resumable-upload.test.ts b/packages/daemon/src/server/__tests__/resumable-upload.test.ts index b6e8c44e8b6..4aa2e3c114f 100644 --- a/packages/daemon/src/server/__tests__/resumable-upload.test.ts +++ b/packages/daemon/src/server/__tests__/resumable-upload.test.ts @@ -572,6 +572,28 @@ test('idempotent preflight does not extend upload expiry', async () => { } }); +test('upload preflights reserve tenant capacity and preserve idempotent tickets', async () => { + vi.useFakeTimers(); + try { + const options = { + ...uploadOptions(Buffer.alloc(0)), + tenantId: 'quota-tenant', + sizeBytes: 2 * 1024 * 1024 * 1024, + }; + const first = beginResumableUpload(options); + beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() }); + assert.equal(beginResumableUpload(options).uploadId, first.uploadId); + assert.throws( + () => beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() }), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'UPLOAD_CAPACITY_EXCEEDED', + ); + } finally { + await vi.advanceTimersByTimeAsync(5 * 60 * 1000); + vi.useRealTimers(); + } +}); + function beginUpload(bytes: Buffer): ReturnType { return beginResumableUpload(uploadOptions(bytes)); } diff --git a/packages/daemon/src/server/http-errors.ts b/packages/daemon/src/server/http-errors.ts index ea1726178f2..c732a303e89 100644 --- a/packages/daemon/src/server/http-errors.ts +++ b/packages/daemon/src/server/http-errors.ts @@ -23,7 +23,9 @@ export function statusCodeForNormalizedError(error: { case 'COMMAND_FAILED': // A TTL registry cannot tell an expired id from one that never existed, // so a gone resource is 404 rather than 410. - return error.details?.reason === 'RESOURCE_EXPIRED' ? 404 : 500; + if (error.details?.reason === 'RESOURCE_EXPIRED') return 404; + if (error.details?.reason === 'UPLOAD_CAPACITY_EXCEEDED') return 503; + return 500; default: return 500; } diff --git a/packages/daemon/src/server/http/http-authorization.test.ts b/packages/daemon/src/server/http/http-authorization.test.ts index 5e927b667df..bdcda9941b6 100644 --- a/packages/daemon/src/server/http/http-authorization.test.ts +++ b/packages/daemon/src/server/http/http-authorization.test.ts @@ -1,7 +1,8 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; +import http from 'node:http'; import path from 'node:path'; import { createDaemonHttpServer } from './http-server.ts'; import { @@ -105,3 +106,28 @@ test('aux route: a hook returning an invalid tenantId answers 500, not a 401 cal }, ); }); + +test('aux route: a disconnected caller cancels a nonresolving auth hook', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const state = globalThis as typeof globalThis & { __auxAuthHookSignal?: AbortSignal }; + try { + await withAuxRouteAndHook( + 'export default ({ signal }) => { globalThis.__auxAuthHookSignal = signal; return new Promise(() => {}); };', + async ({ baseUrl }) => { + const target = new URL('/sessions/default/requests/abc123/diagnostics', baseUrl); + const request = http.request(target, { + headers: { authorization: `Bearer ${DAEMON_TOKEN}` }, + }); + request.on('error', () => {}); + request.end(); + await vi.waitFor(() => assert.ok(state.__auxAuthHookSignal), { timeout: 1_000 }); + const signal = state.__auxAuthHookSignal; + assert.ok(signal); + request.destroy(); + await vi.waitFor(() => assert.equal(signal.aborted, true), { timeout: 1_000 }); + }, + ); + } finally { + delete state.__auxAuthHookSignal; + } +}); diff --git a/packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts b/packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts new file mode 100644 index 00000000000..60299ead9d3 --- /dev/null +++ b/packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts @@ -0,0 +1,45 @@ +import http from 'node:http'; +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; +import { postRpcCommand, startRpcServer } from '../__tests__/http-server-rpc.fixtures.ts'; + +test('unfinished RPC bodies exhaust a bounded ingress budget without dispatch', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let dispatched = 0; + const { port, server } = await startRpcServer('budget-token', async () => { + dispatched += 1; + return { ok: true, data: {} }; + }); + const held: http.ClientRequest[] = []; + let received = 0; + let allReceived!: () => void; + const ready = new Promise((resolve) => { + allReceived = resolve; + }); + server.on('request', (req) => { + if (req.url === '/rpc' && ++received === 32) allReceived(); + }); + try { + for (let index = 0; index < 32; index += 1) { + const request = http.request({ + host: '127.0.0.1', + port, + method: 'POST', + path: '/rpc', + headers: { 'content-type': 'application/json' }, + }); + request.on('error', () => {}); + request.flushHeaders(); + held.push(request); + } + await ready; + const refused = await postRpcCommand(port, 'budget-token', 'overflow'); + assert.equal(refused.status, 503); + assert.equal(refused.body.error?.data?.details?.reason, 'RPC_BODY_CAPACITY_EXCEEDED'); + assert.equal(dispatched, 0); + } finally { + for (const request of held) request.destroy(); + await closeLoopbackServer(server); + } +}); diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 86f57a66bae..09e51e0f0ff 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -11,8 +11,12 @@ import { AsyncResource } from 'node:async_hooks'; import http from 'node:http'; import { TLSSocket } from 'node:tls'; import { randomUUID } from 'node:crypto'; -import type { DiagnosticsRecordRef, NormalizedError } from '@agent-device/kernel/errors'; -import { normalizeError } from '@agent-device/kernel/errors'; +import type { + DiagnosticsRecordRef, + NormalizedError, + ReasonTable, +} from '@agent-device/kernel/errors'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { LEASE_BACKENDS } from '@agent-device/kernel/contracts'; import { isRecord } from '@agent-device/kernel/record'; import type { DaemonInvokeFn, DaemonRequest } from '../../core/daemon-request.ts'; @@ -92,6 +96,14 @@ import { } from './http-checked-rpc.ts'; const MAX_HTTP_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; +const MAX_IN_FLIGHT_RPC_BODIES = 32; +const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; +const RPC_INGRESS_REASONS = { + // Too many daemon RPC requests are in flight through dispatch. The daemon closes a request + // that exceeds its aggregate body-byte limit. + capacityExceeded: { reason: 'RPC_BODY_CAPACITY_EXCEEDED' }, +} as const satisfies ReasonTable<'RPC ingress'>; +type RpcBodyBudget = { active: number; bytes: number }; /** What this daemon serves over HTTP beyond the base RPC contract, as `/health` advertises it. */ const DAEMON_HTTP_CAPABILITIES = [ 'script-artifacts', @@ -145,6 +157,7 @@ export async function createDaemonHttpServer(options: { resolveRequestDiagnosticsPath, onUnownedRequestFailure, } = options; + const rpcBodyBudget: RpcBodyBudget = { active: 0, bytes: 0 }; const onRequest = AsyncResource.bind((req: http.IncomingMessage, res: http.ServerResponse) => { const ingressUrl = nodeHttpRequestUrl(req.url, req.rawHeaders, req.socket instanceof TLSSocket); if (!ingressUrl) { @@ -216,6 +229,7 @@ export async function createDaemonHttpServer(options: { authHook, expectedToken: token, daemonRequest: request.daemonRequest, + signal: responseDisconnectSignal(request.req, request.res), }), }) ) { @@ -234,6 +248,7 @@ export async function createDaemonHttpServer(options: { authHook, expectedToken: token, leaseRegistry: options.leaseRegistry, + signal: responseDisconnectSignal(request.req, request.res), }), }) ) { @@ -247,7 +262,7 @@ export async function createDaemonHttpServer(options: { return; } - readRpcRequestBody(req, res, (body) => { + readRpcRequestBody(req, res, rpcBodyBudget, (body, release) => { // The flow owns this request's lifetime, so this call site must neither hold lifetime state // nor re-run it; the `catch` reports the failure to the daemon-level sink and answers. That // answer is load-bearing: the daemon exits on an `unhandledRejection`, so a rejection dropped @@ -261,9 +276,11 @@ export async function createDaemonHttpServer(options: { instanceId, handleRequest, checked, - }).catch((error: unknown) => { - sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); - }); + }) + .catch((error: unknown) => { + sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); + }) + .finally(release); }); }); // Socket ingress ceilings from one owner (ingress-budget.ts). They bound socket ingress @@ -291,29 +308,63 @@ export async function createDaemonHttpServer(options: { function readRpcRequestBody( req: http.IncomingMessage, res: http.ServerResponse, - onBody: (body: string) => void, + budget: RpcBodyBudget, + onBody: (body: string, release: () => void) => void, ): void { + if (budget.active >= MAX_IN_FLIGHT_RPC_BODIES) { + const failure = normalizeError( + new AppError('COMMAND_FAILED', 'RPC ingress capacity exceeded', { + reason: RPC_INGRESS_REASONS.capacityExceeded.reason, + retriable: true, + }), + ); + sendRpcRefusal(res, rpcRefusal(null, -32000, failure.message, 503, failure)); + req.resume(); + return; + } + budget.active += 1; let body = ''; let bodyBytes = 0; + let released = false; + let bodyComplete = false; + const onAborted = () => { + if (!bodyComplete) release(); + }; + const release = () => { + if (released) return; + released = true; + req.off('aborted', onAborted); + budget.active -= 1; + budget.bytes -= bodyBytes; + }; req.setEncoding('utf8'); req.on('data', (chunk: string) => { - body += chunk; - bodyBytes += Buffer.byteLength(chunk, 'utf8'); - if (bodyBytes > MAX_HTTP_RPC_BODY_BYTES) { + const bytes = Buffer.byteLength(chunk, 'utf8'); + if ( + bodyBytes + bytes > MAX_HTTP_RPC_BODY_BYTES || + budget.bytes + bytes > MAX_IN_FLIGHT_RPC_BODY_BYTES + ) { req.destroy(new Error('request too large')); + return; } + bodyBytes += bytes; + budget.bytes += bytes; + body += chunk; }); req.on('error', () => { + if (!bodyComplete) release(); if (!res.headersSent) { sendRpcRefusal(res, rpcParseErrorRefusal()); } }); + req.once('aborted', onAborted); req.on( 'end', AsyncResource.bind(() => { - onBody(body); + bodyComplete = true; + onBody(body, release); }), ); } @@ -496,6 +547,7 @@ function sendRpcRefusal(res: http.ServerResponse, refusal: RpcRefusal): void { * before `admit`, so a call that was never admitted still cleans up from one place. */ type RpcRequestLifetime = { + signal: AbortSignal; /** * Stamps the daemon's request tracking id into `meta` and registers the request's AbortSignal * under it. An id already in flight throws `duplicate_request_id` from here, so the caller @@ -529,7 +581,7 @@ function beginRpcRequestLifetime(params: { let abortRegistration: ReturnType; let handlerCompleted = false; let canceledInFlight = false; - let disconnectSignal: AbortSignal | undefined; + const disconnectSignal = responseDisconnectSignal(req, res); let onClientGone: (() => void) | undefined; const markCanceledIfResponseIncomplete = () => { @@ -546,6 +598,7 @@ function beginRpcRequestLifetime(params: { }; return { + signal: disconnectSignal, admit(daemonRequest) { requestId = resolveRequestTrackingId(daemonRequest.meta?.requestId, rpcId); abortRegistration = registerRequestAbort(requestId, undefined, { @@ -559,7 +612,6 @@ function beginRpcRequestLifetime(params: { }, watchForClientDisconnect() { onClientGone = AsyncResource.bind(markCanceledIfResponseIncomplete); - disconnectSignal = responseDisconnectSignal(req, res); disconnectSignal.addEventListener('abort', onClientGone, { once: true }); if (disconnectSignal.aborted) { markCanceledIfResponseIncomplete(); @@ -569,7 +621,7 @@ function beginRpcRequestLifetime(params: { handlerCompleted = true; }, release() { - if (onClientGone) disconnectSignal?.removeEventListener('abort', onClientGone); + if (onClientGone) disconnectSignal.removeEventListener('abort', onClientGone); clearRequestAbortRegistration(abortRegistration); }, }; @@ -638,6 +690,7 @@ async function admitRpcRequest(params: { headers: req.headers, rpcRequest, daemonRequest, + signal: lifetime.signal, }); if (!authResult.ok) { return { diff --git a/packages/daemon/src/server/remote-host-input-policy.ts b/packages/daemon/src/server/remote-host-input-policy.ts index 623de0ff2ba..fa9ae6e9210 100644 --- a/packages/daemon/src/server/remote-host-input-policy.ts +++ b/packages/daemon/src/server/remote-host-input-policy.ts @@ -4,13 +4,33 @@ import { validateAndNormalizeBatchSteps } from '@agent-device/command-registry/b import { DEFAULT_BATCH_MAX_STEPS } from '@agent-device/contracts/command'; import type { DaemonRequest } from '../core/daemon-request.ts'; import { remoteScriptOpen } from '../core/session-script-publication-capability.ts'; +import { assertReplayScriptSourcesWithinLimit } from '@agent-device/replay-port/script-source'; +import type { DeviceInfo } from '@agent-device/kernel/device'; const REMOTE_HOST_INPUT_REASONS = { // A remote request supplied a host path or other host input (`details.field`), which a remote // daemon refuses. denied: { reason: 'REMOTE_HOST_INPUT_DENIED' }, + // The managed browser cannot confine a remote tenant's requests to public destinations. + webNetworkUnenforced: { reason: 'remote_web_public_network_unenforced' }, } as const satisfies ReasonTable<'remote daemon'>; +/** Remote browser traffic cannot be restricted at connection time by the managed web backend. */ +export function assertRemoteWebDeviceAdmitted(request: DaemonRequest, device: DeviceInfo): void { + if ( + !request.internal?.publicNetworkOnly || + device.platform !== 'web' || + request.command === 'close' + ) { + return; + } + throw new AppError( + 'UNSUPPORTED_OPERATION', + 'Remote web sessions are unavailable because the managed browser cannot enforce public-network access.', + { reason: REMOTE_HOST_INPUT_REASONS.webNetworkUnenforced.reason, retriable: false }, + ); +} + const HOST_PATH_FIELDS = [ 'sessionSaveScript', 'launchConsole', @@ -28,25 +48,27 @@ const HOST_PATH_FIELDS = [ /** Remote callers choose client destinations; only the daemon chooses host output paths. */ export function restrictRemoteHostInputs(request: DaemonRequest): DaemonRequest { if (!request.internal?.publicNetworkOnly) return request; - const { cwd: _cwd, ...meta } = request.meta ?? {}; - const command = request.command; + if (request.command === 'replay' || request.command === 'test') { + assertReplayScriptSourcesWithinLimit(request.flags as Record | undefined); + } const fields = [request.flags, request.input, request.runtime]; assertRemoteHostToolingInputs(request, fields); + return restrictRemoteOutputInputs(request, fields); +} + +function restrictRemoteOutputInputs( + request: DaemonRequest, + fields: Array, +): DaemonRequest { + const { cwd: _cwd, ...meta } = request.meta ?? {}; const { out: _out, artifactsDir: _artifactsDir, ...flags } = request.flags ?? {}; const { artifactsDir: _inputArtifactsDir, ...input } = request.input ?? {}; - if (command === 'batch') return restrictRemoteBatchSteps({ ...request, flags, meta }); - if (command === 'test') { + if (request.command === 'batch') return restrictRemoteBatchSteps({ ...request, flags, meta }); + if (request.command === 'test') { return { ...request, flags, ...(request.input ? { input } : {}), meta }; } - if (!['screenshot', 'record', 'perf', 'trace'].includes(command)) { - if (fields.some((record) => record && Object.hasOwn(record, 'out'))) { - throw remoteHostInputDenied('out'); - } - if (fields.some((record) => record && Object.hasOwn(record, 'artifactsDir'))) { - throw remoteHostInputDenied('artifactsDir'); - } - return { ...request, meta }; - } + if (!['screenshot', 'record', 'perf', 'trace'].includes(request.command)) + return restrictRemoteOrdinaryOutput(request, fields, meta); return restrictRemoteCaptureOutput({ ...request, flags, @@ -55,6 +77,18 @@ export function restrictRemoteHostInputs(request: DaemonRequest): DaemonRequest }); } +function restrictRemoteOrdinaryOutput( + request: DaemonRequest, + fields: Array, + meta: DaemonRequest['meta'], +): DaemonRequest { + if (fields.some((record) => record && Object.hasOwn(record, 'out'))) + throw remoteHostInputDenied('out'); + if (fields.some((record) => record && Object.hasOwn(record, 'artifactsDir'))) + throw remoteHostInputDenied('artifactsDir'); + return { ...request, meta }; +} + function assertRemoteHostToolingInputs( request: DaemonRequest, fields: Array, diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index fa2d0fdc11a..909a36285d9 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -1,4 +1,7 @@ -import { restrictRemoteHostInputs } from './remote-host-input-policy.ts'; +import { + assertRemoteWebDeviceAdmitted, + restrictRemoteHostInputs, +} from './remote-host-input-policy.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { @@ -612,8 +615,12 @@ function createRequestDeviceAccess(params: { dispatchLedger: params.dispatchLedger, admitDeviceClaim: claimAdmission.admit, admitDevice: - params.admitDevicePin || daemonPolicy || claimPolicy === 'require-owner' + params.admitDevicePin || + daemonPolicy || + claimPolicy === 'require-owner' || + params.req.internal?.publicNetworkOnly ? (device) => { + assertRemoteWebDeviceAdmitted(params.req, device); params.admitDevicePin?.(device); if (daemonPolicy) { assertDaemonPolicyAdmitsDevice(daemonPolicy, device); diff --git a/packages/daemon/src/server/request-platform-provider-context.test.ts b/packages/daemon/src/server/request-platform-provider-context.test.ts index 5c24b640df1..82bf79373d4 100644 --- a/packages/daemon/src/server/request-platform-provider-context.test.ts +++ b/packages/daemon/src/server/request-platform-provider-context.test.ts @@ -76,6 +76,22 @@ test('request provider context preserves an explicitly empty request id', async assert.equal(context?.device.id, IOS_SIMULATOR.id); }); +test('request provider context carries only the daemon-owned network policy', async () => { + const local = await resolvePlatformProviderRequestContext({ + req: request('snapshot'), + existingSession: makeIosSession('ios-session'), + env: process.env, + }); + const remote = await resolvePlatformProviderRequestContext({ + req: { ...request('snapshot'), internal: { publicNetworkOnly: true } }, + existingSession: makeIosSession('ios-session'), + env: process.env, + }); + + assert.equal(local?.publicNetworkOnly, undefined); + assert.equal(remote?.publicNetworkOnly, true); +}); + function request(command: string): DaemonRequest { return { token: 'test-token', diff --git a/packages/daemon/src/server/request-platform-provider-context.ts b/packages/daemon/src/server/request-platform-provider-context.ts index 3784652d663..22704cdc299 100644 --- a/packages/daemon/src/server/request-platform-provider-context.ts +++ b/packages/daemon/src/server/request-platform-provider-context.ts @@ -46,6 +46,7 @@ export async function resolvePlatformProviderRequestContext(params: { } : {}), ...(params.useDefaultWebProvider ? { useDefaultWebProvider: true } : {}), + ...(params.req.internal?.publicNetworkOnly === true ? { publicNetworkOnly: true } : {}), }; } diff --git a/packages/daemon/src/server/resumable-upload.ts b/packages/daemon/src/server/resumable-upload.ts index af3536a0f5a..2ee91d1b54f 100644 --- a/packages/daemon/src/server/resumable-upload.ts +++ b/packages/daemon/src/server/resumable-upload.ts @@ -23,9 +23,15 @@ const UPLOAD_FINALIZE_REASONS = { // Finalizing the upload failed, and removing its staged files failed too; `details.originalError` // holds the first failure. cleanupFailed: { reason: 'UPLOAD_FINALIZE_CLEANUP_FAILED' }, + // A new upload would exceed the active upload count or reserved byte budget. + capacityExceeded: { reason: 'UPLOAD_CAPACITY_EXCEEDED' }, } as const satisfies ReasonTable<'uploads'>; const RESUMABLE_UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; +const MAX_ACTIVE_UPLOADS_PER_TENANT = 32; +const MAX_ACTIVE_UPLOADS_TOTAL = 256; +const MAX_RESERVED_UPLOAD_BYTES_PER_TENANT = 4 * 1024 * 1024 * 1024; +const MAX_RESERVED_UPLOAD_BYTES_TOTAL = 16 * 1024 * 1024 * 1024; const RESUMABLE_UPLOAD_RESOURCE: TenantOwnedResourceKind = { label: 'Upload', expiredHint: `Resumable uploads expire ${RESUMABLE_UPLOAD_CLEANUP_TIMEOUT_MS / 60_000} minutes after the last received chunk. Start the upload again from the beginning.`, @@ -107,6 +113,7 @@ export function beginResumableUpload( const key = buildResumableUploadKey(options); const existingId = RESUMABLE_UPLOADS_BY_KEY().get(key); const existing = existingId ? RESUMABLE_UPLOADS_BY_ID().get(existingId) : undefined; + if (!existing) assertResumableUploadCapacity(options); const entry = existing ?? createResumableUploadEntry(options, key); const ticket = describeResumableUploadTicket(entry, options); if (!publish) return ticket; @@ -122,6 +129,31 @@ export function beginResumableUpload( return ticket; } +function assertResumableUploadCapacity(options: BeginResumableUploadOptions): void { + let tenantCount = 0; + let tenantBytes = 0; + let totalBytes = 0; + for (const entry of RESUMABLE_UPLOADS_BY_ID().values()) { + totalBytes += entry.sizeBytes; + if (entry.tenantId === options.tenantId) { + tenantCount += 1; + tenantBytes += entry.sizeBytes; + } + } + if ( + tenantCount < MAX_ACTIVE_UPLOADS_PER_TENANT && + RESUMABLE_UPLOADS_BY_ID().size < MAX_ACTIVE_UPLOADS_TOTAL && + tenantBytes + options.sizeBytes <= MAX_RESERVED_UPLOAD_BYTES_PER_TENANT && + totalBytes + options.sizeBytes <= MAX_RESERVED_UPLOAD_BYTES_TOTAL + ) { + return; + } + throw new AppError('COMMAND_FAILED', 'Too many active resumable uploads', { + reason: UPLOAD_FINALIZE_REASONS.capacityExceeded.reason, + retriable: true, + }); +} + function describeResumableUploadTicket( entry: ResumableUploadEntry, options: BeginResumableUploadOptions, diff --git a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts index 29840412233..15263141a63 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts @@ -37,6 +37,43 @@ test('artifacts refuses foreign and unknown provider session ids before cloud di assert.deepEqual(world.providerCalls, []); }); +test('artifacts admits an owned lease ID and refuses a foreign lease ID before cloud dispatch', async () => { + const world = createWorld(); + const lease = await allocateLease(world, 'tenant-a', 'run-a'); + + await assert.rejects( + () => listArtifacts(world, { tenantId: 'tenant-b', runId: 'run-b', leaseId: lease.leaseId }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'UNAUTHORIZED'); + assert.equal(error.details?.reason, 'LEASE_SCOPE_MISMATCH'); + return true; + }, + ); + assert.deepEqual(world.providerCalls, []); + + await assert.rejects( + () => listArtifacts(world, { leaseId: lease.leaseId }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'UNAUTHORIZED'); + assert.equal(error.details?.reason, 'LEASE_SCOPE_REQUIRED'); + return true; + }, + ); + assert.deepEqual(world.providerCalls, []); + + const owned = await listArtifacts(world, { + tenantId: 'tenant-a', + runId: 'run-a', + leaseId: lease.leaseId, + }); + assert.equal(owned.ok, true); + assert.deepEqual(world.providerCalls, [ + { provider: CLOUD_PROVIDER, leaseId: lease.leaseId, providerSessionId: undefined }, + ]); +}); + test('artifacts lists an owned active and recently released provider session', async () => { const world = createWorld(); const lease = await allocateLease(world, 'tenant-a', 'run-a'); @@ -287,9 +324,10 @@ async function releaseLease(world: World, lease: DeviceLease): Promise { async function listArtifacts( world: World, scope: { - tenantId: string; - runId: string; - providerSessionId: string; + tenantId?: string; + runId?: string; + providerSessionId?: string; + leaseId?: string; leaseProvider?: string; }, ): Promise { @@ -300,9 +338,10 @@ async function listArtifacts( { tenantId: scope.tenantId, runId: scope.runId, + leaseId: scope.leaseId, leaseProvider: scope.leaseProvider ?? CLOUD_PROVIDER, }, - { providerSessionId: scope.providerSessionId }, + scope.providerSessionId ? { providerSessionId: scope.providerSessionId } : {}, ), sessionName: 'artifact-test', sessionStore: world.sessionStore, diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index 295fa9afb7d..42632d95f0d 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -567,6 +567,9 @@ async function listCloudArtifactsForRequest( 'artifacts requires an active cloud lease or --provider-session .', ); } + if (leaseScope.leaseId && !providerSessionId) { + leaseRegistry.assertLeaseReadAdmission({ ...leaseScope, leaseId: leaseScope.leaseId }); + } const providerSession = resolveProviderSession(leaseRegistry, leaseScope, providerSessionId); const result = await cloudArtifactProvider?.listCloudArtifacts?.({ provider: leaseScope.leaseProvider, diff --git a/packages/platform-web/src/__tests__/agent-browser-provider-text-entry.test.ts b/packages/platform-web/src/__tests__/agent-browser-provider-text-entry.test.ts new file mode 100644 index 00000000000..9997af2a0d3 --- /dev/null +++ b/packages/platform-web/src/__tests__/agent-browser-provider-text-entry.test.ts @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { withCommandExecutorOverride } from '@agent-device/host-kit/command'; +import { bindTestCommandHost } from '@agent-device/test-kit'; +import { + agentBrowserJsonResult, + managedAgentBrowserCliArgs, + withManagedAgentBrowserProvider, +} from './test-utils.ts'; + +bindTestCommandHost(); + +test('ref fill sends a literal double dash after the backend separator', async () => { + const expectedCommand = ['fill', '@e3', '--', '--']; + let batchInput: unknown; + await withManagedAgentBrowserProvider({ session: 'text-entry' }, async (provider) => { + await withCommandExecutorOverride( + async (_command, args, options) => { + assert.deepEqual(managedAgentBrowserCliArgs(args).slice(0, 1), ['batch']); + assert.equal(managedAgentBrowserCliArgs(args).includes('--'), false); + batchInput = JSON.parse(String(options.stdin ?? 'null')); + return agentBrowserJsonResult([{ command: expectedCommand, success: true }]); + }, + async () => { + if (!provider.fillRef) throw new Error('ref fill is unavailable'); + await provider.fillRef('@e3', '--'); + }, + ); + }); + assert.deepEqual(batchInput, [expectedCommand]); +}); diff --git a/packages/platform-web/src/__tests__/test-utils.ts b/packages/platform-web/src/__tests__/test-utils.ts index b1ce155074d..f93c4c8f7a6 100644 --- a/packages/platform-web/src/__tests__/test-utils.ts +++ b/packages/platform-web/src/__tests__/test-utils.ts @@ -59,6 +59,7 @@ export async function withManagedAgentBrowserProvider( session?: string; openWebSessionNames?: () => readonly string[]; ownedProcessRecords?: OwnedProcessRecordStore; + publicNetworkOnly?: true; }, testFn: (provider: WebProvider) => void | Promise, ): Promise { diff --git a/packages/platform-web/src/agent-browser-provider.test.ts b/packages/platform-web/src/agent-browser-provider.test.ts index e7068257140..44a0b1ab4f6 100644 --- a/packages/platform-web/src/agent-browser-provider.test.ts +++ b/packages/platform-web/src/agent-browser-provider.test.ts @@ -56,6 +56,30 @@ test('agent-browser provider keys its browser on its backend key as given', asyn }); }); +test('a confined remote provider refuses before browser cleanup or backend spawn', async () => { + await withManagedAgentBrowserProvider( + { session: 't_remote-session', publicNetworkOnly: true, openWebSessionNames: () => [] }, + async (provider) => { + const calls: AgentBrowserCall[] = []; + await withCommandExecutorOverride(recordingExecutor(calls), async () => { + await assert.rejects( + provider.open('https://example.test'), + (error: unknown) => + error instanceof AppError && + error.code === 'UNSUPPORTED_OPERATION' && + error.details?.reason === 'remote_web_browser_unconfined', + ); + assert.equal(mockProviderStartupCleanup.mock.calls.length, 0); + await provider.close(); + }); + assert.deepEqual( + calls.map((call) => call.args), + [['close', '--json', '--session', 't_remote-session']], + ); + }, + ); +}); + test('agent-browser provider maps supported operations to session-scoped JSON commands', async () => { await withManagedAgentBrowserProvider({ session: 'web-session' }, async (provider) => { const calls: AgentBrowserCall[] = []; @@ -122,7 +146,11 @@ test('agent-browser provider maps supported operations to session-scoped JSON co // Typed text reaches the backend only on stdin, never in its process-table-visible argv. assert.deepEqual( calls.filter((call) => call.args[0] === 'batch').map((call) => JSON.parse(call.stdin ?? '')), - [[['keyboard', 'type', 'Ada']], [['fill', '@e2', 'Grace']], [['keyboard', 'type', 'hello']]], + [ + [['keyboard', 'type', 'Ada']], + [['fill', '@e2', '--', 'Grace']], + [['keyboard', 'type', 'hello']], + ], ); }); }); @@ -602,7 +630,7 @@ test('agent-browser provider preserves Node version guidance for missing managed error instanceof AppError && error.code === 'TOOL_MISSING' && error.details?.hint === 'Web automation requires Node 24+; current Node is v22.19.0.' && - error.details?.version === '0.39.0' && + error.details?.version === '0.42.0' && typeof error.details?.installDir === 'string', ); } finally { diff --git a/packages/platform-web/src/agent-browser-provider.ts b/packages/platform-web/src/agent-browser-provider.ts index ebad95a493a..c5e40d5b433 100644 --- a/packages/platform-web/src/agent-browser-provider.ts +++ b/packages/platform-web/src/agent-browser-provider.ts @@ -30,6 +30,7 @@ import { import type { WebProvider, WebSnapshotOptions, WebSnapshotResult } from './provider.ts'; import { AGENT_BROWSER_REFUSAL_REASONS, + assertManagedAgentBrowserNetworkPolicy, getManagedAgentBrowserStatus, mapManagedAgentBrowserError, runManagedAgentBrowser, @@ -58,9 +59,10 @@ type AgentBrowserProviderOptions = { /** The backend keys of the published web sessions. */ openWebSessionNames?: () => readonly string[]; ownedProcessRecords?: OwnedProcessRecordStore; + publicNetworkOnly?: true; }; -/** How one backend call is executed: cancellation, plus the work it reads from stdin (`batch`). */ +/** Cancellation and stdin work for one backend call. */ type AgentBrowserRunOptions = { signal?: AbortSignal; stdin?: string; @@ -72,9 +74,8 @@ type AgentBrowserRunOptions = { }; export function createAgentBrowserWebProvider(options: AgentBrowserProviderOptions): WebProvider { - const { session } = options; const runJson = async (args: string[], run?: AgentBrowserRunOptions): Promise => - await runAgentBrowserJson(args, { session, options, ...run }); + await runAgentBrowserJson(args, { session: options.session, options, ...run }); return { async open(target) { @@ -140,7 +141,7 @@ export function createAgentBrowserWebProvider(options: AgentBrowserProviderOptio } }, async fillRef(ref, text) { - await sendTextEntry(runJson, 'fill', ['fill', browserRefSelector(ref), text]); + await sendTextEntry(runJson, 'fill', ['fill', browserRefSelector(ref), '--', text]); }, async typeText(text) { await sendTextEntry(runJson, 'type', ['keyboard', 'type', text]); @@ -568,15 +569,7 @@ async function runAgentBrowserJson( } /** Detail keys that hold what an executed backend command printed. */ -const BACKEND_OUTPUT_DETAIL_KEYS: ReadonlySet = new Set([ - 'stdout', - 'stderr', - 'agentBrowserError', -]); - -function hasBackendOutput(error: AppError): boolean { - return Object.keys(error.details ?? {}).some((key) => BACKEND_OUTPUT_DETAIL_KEYS.has(key)); -} +const BACKEND_OUTPUT_DETAIL_KEYS = new Set(['stdout', 'stderr', 'agentBrowserError']); function detailsWithoutBackendOutput(error: AppError): Record { return Object.fromEntries( @@ -600,7 +593,11 @@ function withoutBackendAnswer(error: unknown, label: string): unknown { * ran (the backend missing, a cancellation) carries no output and passes through unchanged. */ function withoutBackendOutput(error: unknown): unknown { - if (!(error instanceof AppError) || !hasBackendOutput(error)) return error; + if ( + !(error instanceof AppError) || + !Object.keys(error.details ?? {}).some((key) => BACKEND_OUTPUT_DETAIL_KEYS.has(key)) + ) + return error; return new AppError(error.code, error.message, detailsWithoutBackendOutput(error)); } @@ -610,6 +607,7 @@ async function runAgentBrowserCommand( interpret: (result: { stdout: string; stderr: string; exitCode: number }) => unknown, run: AgentBrowserRunOptions, ): Promise { + assertManagedAgentBrowserNetworkPolicy(cliArgs, options.publicNetworkOnly); let stdout = ''; let stderr = ''; let exitCode = 0; @@ -627,6 +625,7 @@ async function runAgentBrowserCommand( stateDir: options.stateDir, allowFailure: true, timeoutMs: AGENT_BROWSER_TIMEOUT_MS, + ...(options.publicNetworkOnly ? { publicNetworkOnly: true } : {}), signal: run.signal, stdin: run.stdin, }); diff --git a/packages/platform-web/src/agent-browser-tool.test.ts b/packages/platform-web/src/agent-browser-tool.test.ts index 96892f1290c..3f7af0556de 100644 --- a/packages/platform-web/src/agent-browser-tool.test.ts +++ b/packages/platform-web/src/agent-browser-tool.test.ts @@ -34,7 +34,7 @@ test('managed agent-browser reports actionable guidance when install is missing' (error: unknown) => error instanceof AppError && error.code === 'TOOL_MISSING' && - error.details?.installDir === path.join(stateDir, 'tools', 'agent-browser', '0.39.0') && + error.details?.installDir === path.join(stateDir, 'tools', 'agent-browser', '0.42.0') && error.details?.hint === expectedMissingInstallHint(), ); } finally { @@ -109,7 +109,7 @@ test('managed agent-browser passes the managed runtime home and socket dir to th test('managed agent-browser status ignores a bin shim without the backend package', () => { const stateDir = mkdtempForTestSync('agent-device-web-tool-'); try { - const installDir = path.join(stateDir, 'tools', 'agent-browser', '0.39.0'); + const installDir = path.join(stateDir, 'tools', 'agent-browser', '0.42.0'); const binDir = path.join(installDir, 'package', 'node_modules', '.bin'); fs.mkdirSync(binDir, { recursive: true }); fs.writeFileSync(path.join(binDir, 'agent-browser'), '#!/bin/sh\nexit 0\n'); @@ -224,12 +224,12 @@ for (const scenario of [ assert.deepEqual(npmSpawn?.args.slice(npmSpawn.args.indexOf('install')), [ 'install', '--prefix', - path.join(stateDir, 'tools', 'agent-browser', '0.39.0', 'package'), + path.join(stateDir, 'tools', 'agent-browser', '0.42.0', 'package'), '--no-global', '--no-audit', '--no-fund', '--no-save', - 'agent-browser@0.39.0', + 'agent-browser@0.42.0', ]); } finally { fs.rmSync(stateDir, { recursive: true, force: true }); diff --git a/packages/platform-web/src/agent-browser-tool.ts b/packages/platform-web/src/agent-browser-tool.ts index defd57d917e..6b08a093ebb 100644 --- a/packages/platform-web/src/agent-browser-tool.ts +++ b/packages/platform-web/src/agent-browser-tool.ts @@ -31,7 +31,7 @@ import { resolveAgentBrowserIdleTimeoutMs, } from './agent-browser-lifecycle.ts'; -const MANAGED_AGENT_BROWSER_VERSION = '0.39.0'; +const MANAGED_AGENT_BROWSER_VERSION = '0.42.0'; const AGENT_BROWSER = 'agent-browser'; const MINIMUM_WEB_NODE_MAJOR = 24; @@ -47,6 +47,7 @@ export type ManagedAgentBrowserRunOptions = { timeoutMs: number; allowFailure?: boolean; signal?: AbortSignal; + publicNetworkOnly?: true; /** Written to the backend's stdin, for the command that reads its work from it (`batch`). */ stdin?: string; }; @@ -60,11 +61,23 @@ export async function runManagedAgentBrowser( args: readonly string[], options: ManagedAgentBrowserRunOptions, ): Promise { + assertManagedAgentBrowserNetworkPolicy(args, options.publicNetworkOnly); const status = getManagedAgentBrowserStatus({ host: options.host, stateDir: options.stateDir }); if (!status.installed) throw missingManagedToolError(status); return await spawnManagedAgentBrowser(status, args, options); } +export function assertManagedAgentBrowserNetworkPolicy( + args: readonly string[], + publicNetworkOnly: true | undefined, +): void { + if (!publicNetworkOnly || args[0] === 'close') return; + throw new AppError('UNSUPPORTED_OPERATION', 'Remote web browser network access is unavailable.', { + reason: AGENT_BROWSER_REFUSAL_REASONS.remoteNetworkUnenforced.reason, + retriable: false, + }); +} + export async function setupManagedAgentBrowser(options: { host: HostEnvironment; stateDir?: string; @@ -317,10 +330,11 @@ export function mapManagedAgentBrowserError(error: unknown): AppError { /** * Why the managed `agent-browser` backend's answer cannot be trusted. The backend runs and prints - * JSON; these rows are the shapes that JSON can have which prove the round trip went wrong, and - * the text-entry refusals the entry's own verdict gives. + * JSON; these rows include invalid answers, text-entry refusals, and launch policy refusals. */ export const AGENT_BROWSER_REFUSAL_REASONS = { + // A remote tenant's browser cannot run before its public-network proxy is enforced. + remoteNetworkUnenforced: { reason: 'remote_web_browser_unconfined' }, // The batch call for a text entry answered with something other than its one echoed entry. textEntryResultUnusable: { reason: 'text-entry-result-unusable' }, // The backend ran the fill or type entry and the page refused it. diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index 098e6076e4c..ef3d0698b9d 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -22,6 +22,27 @@ test('uses the public Revyl backend when no URL is configured', () => { assert.equal(client.backendUrl, REVYL_DEFAULT_BACKEND_URL); }); +test('rejects an oversized provider answer before accepting its body', async () => { + const client = clientResponding( + () => + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)); + }, + }), + { status: 200, headers: { 'content-type': 'application/json' } }, + ), + ); + await assert.rejects( + client.verifyCredentials(), + (error: unknown) => + error instanceof AppError && + error.details?.reason === 'provider_response_too_large' && + error.details?.limitBytes === 32 * 1024 * 1024, + ); +}); + test('keeps plain HTTP only on loopback', () => { assert.equal(resolveRevylBackendUrl('http://127.0.0.1:8787'), 'http://127.0.0.1:8787'); assert.equal(resolveRevylBackendUrl('http://localhost:8787'), 'http://localhost:8787'); diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index 11caa8523a9..a9261272b7e 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -6,6 +6,7 @@ import { } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; +import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/remote'; import fs from 'node:fs'; import { Readable } from 'node:stream'; import { setTimeout as sleep } from 'node:timers/promises'; @@ -30,6 +31,8 @@ export const REVYL_DEFAULT_BACKEND_URL = 'https://backend.revyl.ai'; const REVYL_ATTRIBUTION = 'agent-device'; const DEFAULT_REQUEST_TIMEOUT_MS = 30_000; +const MAX_REVYL_RESPONSE_BYTES = 32 * 1024 * 1024; + /** How long `start_device` may take to answer: Revyl assigns a worker and boots the device in it. */ export const REVYL_START_DEVICE_TIMEOUT_MS = 120_000; const RETRY_DELAYS_MS = [500, 1_500] as const; @@ -379,9 +382,10 @@ async function sendOnce( return Object.freeze({ status: response.status, contentType: response.headers.get('content-type') ?? undefined, - body: new Uint8Array(await response.arrayBuffer()), + body: await readRevylResponseBody(response), }); } catch (error) { + if (error instanceof AppError) return error; if (request.signal?.aborted) return requestCanceled(request, error); if (timeout.aborted) return requestTimedOut(request, error); return new AppError( @@ -393,6 +397,29 @@ async function sendOnce( } } +async function readRevylResponseBody(response: Response): Promise { + if (!response.body) return new Uint8Array(); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) return new Uint8Array(Buffer.concat(chunks, bytes)); + bytes += value.byteLength; + if (bytes > MAX_REVYL_RESPONSE_BYTES) { + throw new AppError('COMMAND_FAILED', 'Revyl response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, + limitBytes: MAX_REVYL_RESPONSE_BYTES, + }); + } + chunks.push(value); + } + } finally { + void reader.cancel().catch(() => {}); + } +} + /** * Only a request that never reached Revyl, or a status Revyl marks transient, is replayed. A * cancellation is the caller's own answer, and a timeout has already spent the request's budget, so diff --git a/packages/provider-webdriver/src/webdriver-transport.test.ts b/packages/provider-webdriver/src/webdriver-transport.test.ts index 61bb44bf4c6..8016db15b7b 100644 --- a/packages/provider-webdriver/src/webdriver-transport.test.ts +++ b/packages/provider-webdriver/src/webdriver-transport.test.ts @@ -26,6 +26,28 @@ afterEach(() => { globalThis.fetch = realFetch; }); +test('WebDriver stops reading a response after its byte limit', async () => { + const transport = new WebDriverTransport({ + clientVersion: '0.0.0-test', + endpoint: 'https://cloud-webdriver.test/wd/hub/', + }); + globalThis.fetch = async () => + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)); + }, + }), + ); + await assert.rejects( + transport.requestValue('GET', '/session/x/source'), + (error: unknown) => + error instanceof AppError && + error.details?.reason === 'provider_response_too_large' && + error.details?.dispatched === 'unknown', + ); +}); + // The transport's own deadline must surface as a machine-readable reason, not // as fetch's `AbortError`/`TimeoutError` DOMException name: the session manager // keys its "the provider may still be creating a billed session" branch on diff --git a/packages/provider-webdriver/src/webdriver-transport.ts b/packages/provider-webdriver/src/webdriver-transport.ts index 717aa9e3552..6ec7dd25e42 100644 --- a/packages/provider-webdriver/src/webdriver-transport.ts +++ b/packages/provider-webdriver/src/webdriver-transport.ts @@ -1,7 +1,12 @@ import { setTimeout as sleep } from 'node:timers/promises'; import { AppError, type DispatchDisclosure, type ReasonTable } from '@agent-device/kernel/errors'; import { agentDeviceRequestHeaders } from './request-headers.ts'; -import { basicAuthHeader, trimLeadingSlash, withTrailingSlash } from './webdriver-utils.ts'; +import { + basicAuthHeader, + readProviderTextBody, + trimLeadingSlash, + withTrailingSlash, +} from './webdriver-utils.ts'; /** Why a WebDriver request failed at the transport. */ const WEBDRIVER_TRANSPORT_REASONS = { @@ -261,8 +266,20 @@ export class WebDriverTransport { throw classifyWebDriverFetchFailure(error, failure, 'request'); } try { - return { ok: response.ok, status: response.status, text: await response.text() }; + return { + ok: response.ok, + status: response.status, + text: await readProviderTextBody(response), + }; } catch (error) { + if (error instanceof AppError) { + throw new AppError( + error.code, + error.message, + { ...error.details, ...dispatchDisclosure('unknown') }, + error, + ); + } throw classifyWebDriverFetchFailure(error, failure, 'response'); } } diff --git a/packages/provider-webdriver/src/webdriver-utils.test.ts b/packages/provider-webdriver/src/webdriver-utils.test.ts index d2b62f826ff..48358440e78 100644 --- a/packages/provider-webdriver/src/webdriver-utils.test.ts +++ b/packages/provider-webdriver/src/webdriver-utils.test.ts @@ -63,6 +63,11 @@ test('the hub upload helper posts with credentials and returns the vendor refere assert.equal(await postHubAppUpload(form, hub), 'hub://APP1'); }); +test('the hub upload helper parses a response with a UTF-8 byte-order mark', async () => { + globalThis.fetch = async () => new Response('\ufeff{"ref":"hub://APP1"}'); + assert.equal(await postHubAppUpload(new FormData(), hub), 'hub://APP1'); +}); + test('the hub upload helper fails typed with the status on an error page or a missing reference', async () => { for (const response of [ new Response('502 Bad Gateway', { status: 502 }), diff --git a/packages/provider-webdriver/src/webdriver-utils.ts b/packages/provider-webdriver/src/webdriver-utils.ts index 07057f3010e..d584b958b9d 100644 --- a/packages/provider-webdriver/src/webdriver-utils.ts +++ b/packages/provider-webdriver/src/webdriver-utils.ts @@ -9,6 +9,7 @@ import type { } from '@agent-device/contracts/device'; import { PROVIDER_DEVICE_ORIENTATIONS, + PROVIDER_RESPONSE_REASONS, type ProviderDeviceOrientation, } from '@agent-device/contracts/remote'; import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors'; @@ -74,6 +75,32 @@ export function withTrailingSlash(url: URL): URL { type HubCredentials = { username: string; accessKey: string }; +const MAX_PROVIDER_RESPONSE_BYTES = 32 * 1024 * 1024; + +/** Bound provider answers even when a peer omits or lies about Content-Length. */ +export async function readProviderTextBody(response: Response): Promise { + if (!response.body) return ''; + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) return new TextDecoder().decode(Buffer.concat(chunks, bytes)); + bytes += value.byteLength; + if (bytes > MAX_PROVIDER_RESPONSE_BYTES) { + throw new AppError('COMMAND_FAILED', 'Provider response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, + limitBytes: MAX_PROVIDER_RESPONSE_BYTES, + }); + } + chunks.push(value); + } + } finally { + void reader.cancel().catch(() => {}); + } +} + /** * A multipart form carrying the local app file under the hub's field name. Upload APIs take one * regular file, so anything else (an extracted `.app` directory, a missing path) is refused here, @@ -142,6 +169,7 @@ export async function postHubAppUpload( json = await readProviderJsonBody(response); } catch (error) { if (signal?.aborted) throw error; + if (error instanceof AppError) throw error; const timedOut = timeoutSignal.aborted; throw new AppError( 'COMMAND_FAILED', @@ -325,6 +353,7 @@ export async function fetchProviderSessionDetails( }); json = await readProviderJsonBody(response); } catch (error) { + if (error instanceof AppError) throw error; throw new AppError( 'COMMAND_FAILED', `${options.service} session details lookup failed.`, @@ -347,7 +376,7 @@ export async function fetchProviderSessionDetails( /** A provider response body parsed as JSON, or `undefined` when it is empty or not JSON (a gateway error page). */ async function readProviderJsonBody(response: Response): Promise { - const text = await response.text(); + const text = await readProviderTextBody(response); if (text.length === 0) return undefined; try { return JSON.parse(text) as unknown; diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts index ac3e609b69d..07761e6c716 100644 --- a/packages/proxy/src/daemon-proxy-cancellation.test.ts +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -69,6 +69,42 @@ function rpcRequest(body: unknown, init: RequestInit = {}): Request { }); } +test('a disconnected RPC stops waiting for authentication and releases its body slot', async () => { + let authenticating = 0; + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: async () => Response.json({ ok: true }), + authenticate: () => { + authenticating += 1; + return authenticating <= 32 ? new Promise(() => {}) : { tenantId: 'tenant-a' }; + }, + }); + const controllers = Array.from({ length: 32 }, () => new AbortController()); + const pending = controllers.map((controller) => + proxy.handle( + rpcRequest( + { jsonrpc: '2.0', id: 1, method: 'agent-device.command' }, + { signal: controller.signal }, + ), + ), + ); + await vi.waitFor(() => expect(authenticating).toBe(32)); + const full = await proxy.handle( + rpcRequest({ jsonrpc: '2.0', id: 33, method: 'agent-device.command' }), + ); + expect(full.status).toBe(503); + + controllers[0]!.abort(); + await pending[0]; + const admitted = await proxy.handle( + rpcRequest({ jsonrpc: '2.0', id: 34, method: 'agent-device.command' }), + ); + expect(admitted.status).toBe(200); + for (const controller of controllers.slice(1)) controller.abort(); + await Promise.all(pending); +}); + test.each([ { route: 'rpc', diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index da033696077..1615e1fcf8c 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -210,6 +210,82 @@ test('an oversized rpc body resolves with a 400 instead of rejecting', async () expect(upstream.requests).toHaveLength(0); }); +test('concurrent unread RPC bodies have a bounded proxy budget that releases after refusal', async () => { + const upstream = recordingUpstream(() => Response.json({ ok: true })); + const proxy = proxyWith(upstream.fetch); + const bodies: ReadableStreamDefaultController[] = []; + const pending = Array.from({ length: 32 }, () => { + const body = new ReadableStream({ + start(controller) { + bodies.push(controller); + }, + }); + return proxy.handle( + new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { + method: 'POST', + body, + duplex: 'half', + } as RequestInit & { duplex: 'half' }), + ); + }); + + let refusedBodyCanceled = false; + const refusedBody = new ReadableStream({ + cancel() { + refusedBodyCanceled = true; + }, + }); + const refused = await proxy.handle( + new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { + method: 'POST', + body: refusedBody, + duplex: 'half', + } as RequestInit & { duplex: 'half' }), + ); + expect(refused.status).toBe(503); + await vi.waitFor(() => expect(refusedBodyCanceled).toBe(true)); + expect(await refused.json()).toMatchObject({ + error: { data: { details: { reason: 'PROXY_RPC_BODY_CAPACITY_EXCEEDED' } } }, + }); + expect(upstream.requests).toHaveLength(0); + + for (const body of bodies) body.close(); + await Promise.all(pending); + const admitted = await proxy.handle( + rpcRequest({ jsonrpc: '2.0', id: 34, method: 'agent-device.command' }), + ); + expect(admitted.status).toBe(200); +}); + +test('aborting an unread RPC body releases its proxy budget slot', async () => { + const upstream = recordingUpstream(() => Response.json({ ok: true })); + const proxy = proxyWith(upstream.fetch); + const controllers = Array.from({ length: 32 }, () => new AbortController()); + const pending = controllers.map((controller) => + proxy.handle( + new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { + method: 'POST', + signal: controller.signal, + body: new ReadableStream({}), + duplex: 'half', + } as RequestInit & { duplex: 'half' }), + ), + ); + const full = await proxy.handle( + rpcRequest({ jsonrpc: '2.0', id: 33, method: 'agent-device.command' }), + ); + expect(full.status).toBe(503); + + controllers[0]!.abort(); + await pending[0]; + const admitted = await proxy.handle( + rpcRequest({ jsonrpc: '2.0', id: 34, method: 'agent-device.command' }), + ); + expect(admitted.status).toBe(200); + for (const controller of controllers.slice(1)) controller.abort(); + await Promise.all(pending); +}); + test('an rpc whose upstream exchange fails answers a JSON-RPC error that keeps code and message', async () => { const proxy = proxyWith(async () => { throw new AppError('COMMAND_FAILED', 'Daemon is unreachable', { reason: 'upstream_down' }); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 92e47a60b14..173ee717a6d 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -28,6 +28,7 @@ import { carriesUnbackedHostPathInstallSource, hostPathInstallSourceRefusedResponse, } from './install-source-admission.ts'; +import type { createRpcBodyBudget } from './rpc-body-budget.ts'; /** * Carries one request to the upstream daemon and resolves with its response. Without `upstreamFetch` @@ -119,6 +120,7 @@ type NormalizedProxyOptions = { clientToken: string | undefined; authenticate: DaemonProxyAuthenticate | undefined; maxRpcBodyBytes: number; + getRpcBodyBudget: () => Promise>; upstreamTimeoutMs: number | undefined; upstreamFetch: DaemonProxyUpstreamFetch; upstreamTransport: (route: string, request: Request) => Promise; @@ -202,25 +204,26 @@ async function handleProxyRequest( if (!isRpcRoute(route)) return await handleDaemonRoute(request, route, options, instanceId); - let rpcBody: string; + let ingress: { body: string; release: () => void }; try { - rpcBody = await readRequestText( - request, - options.maxRpcBodyBytes, - 'Proxy request body is too large.', - ); + ingress = await (await options.getRpcBodyBudget()).read(request, options.maxRpcBodyBytes); } catch (error) { return rpcErrorResponse(null, error); } - // The checked route checks its envelope after authentication and the protocol: a caller on - // another protocol is told so before the proxy reads what its own protocol defines. - const envelopeRefusal = - route === DAEMON_HTTP_CHECKED_RPC_ROUTE ? null : refuseInvalidRpcEnvelope(rpcBody); - if (envelopeRefusal) return envelopeRefusal; try { - return await handleDaemonRoute(request, route, options, instanceId, rpcBody); - } catch (error) { - return rpcErrorResponse(readJsonRpcId(rpcBody), error); + const rpcBody = ingress.body; + // The checked route checks its envelope after authentication and the protocol: a caller on + // another protocol is told so before the proxy reads what its own protocol defines. + const envelopeRefusal = + route === DAEMON_HTTP_CHECKED_RPC_ROUTE ? null : refuseInvalidRpcEnvelope(rpcBody); + if (envelopeRefusal) return envelopeRefusal; + try { + return await handleDaemonRoute(request, route, options, instanceId, rpcBody); + } catch (error) { + return rpcErrorResponse(readJsonRpcId(rpcBody), error); + } + } finally { + ingress.release(); } } @@ -278,13 +281,19 @@ async function authenticateCaller( ? { uploadHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } : null; } - const result = await options.authenticate( - forwardedRequest(request, request.url, { - method: request.method, - headers: request.headers, - signal: request.signal, - ...(rpcBody !== undefined ? { body: rpcBody } : {}), - }), + const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); + const result = await awaitWithSignal( + Promise.resolve( + options.authenticate( + forwardedRequest(request, request.url, { + method: request.method, + headers: request.headers, + signal: request.signal, + ...(rpcBody !== undefined ? { body: rpcBody } : {}), + }), + ), + ), + request.signal, ); if (!result) return null; const tenantId = normalizeTenantId( @@ -598,6 +607,7 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti await admission; return fetch(request); }); + let rpcBodyBudget: Promise> | undefined; return { upstreamBaseUrl, publicOrigin: @@ -608,6 +618,10 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti clientToken, authenticate: options.authenticate, maxRpcBodyBytes: options.maxRpcBodyBytes ?? DEFAULT_MAX_RPC_BODY_BYTES, + getRpcBodyBudget: () => + (rpcBodyBudget ??= import('./rpc-body-budget.ts').then((module) => + module.createRpcBodyBudget(), + )), upstreamTimeoutMs: options.upstreamTimeoutMs, upstreamFetch, upstreamTransport: async (route, request) => { @@ -761,28 +775,6 @@ function resolveUpstreamBody( return request.body; } -async function readRequestText( - request: Request, - maxBodyBytes: number, - tooLargeMessage: string, -): Promise { - if (!request.body) return ''; - const reader = request.body.getReader(); - const chunks: Uint8Array[] = []; - let bodyBytes = 0; - for (;;) { - const { done, value } = await reader.read(); - if (done) break; - bodyBytes += value.byteLength; - if (bodyBytes > maxBodyBytes) { - await reader.cancel(); - throw new AppError('INVALID_ARGS', tooLargeMessage); - } - chunks.push(value); - } - return Buffer.concat(chunks).toString('utf8'); -} - function isAuthorized(request: Request, expectedToken: string, rpcBody: string | undefined) { const requestToken = resolveRequestToken(request, rpcBody); return requestToken.length > 0 && timingSafeStringEqual(requestToken, expectedToken); @@ -963,13 +955,14 @@ function rpcRefusalResponse(code: number, message: string): Response { function rpcErrorResponse(rpcId: unknown, error: unknown): Response { const normalized = normalizeError(error); const invalidArgs = normalized.code === 'INVALID_ARGS'; + const capacityExceeded = normalized.details?.reason === 'PROXY_RPC_BODY_CAPACITY_EXCEEDED'; return Response.json( { jsonrpc: '2.0', id: rpcId, error: { code: invalidArgs ? -32602 : -32000, message: normalized.message, data: normalized }, }, - { status: invalidArgs ? 400 : 500 }, + { status: invalidArgs ? 400 : capacityExceeded ? 503 : 500 }, ); } diff --git a/packages/proxy/src/node-http.test.ts b/packages/proxy/src/node-http.test.ts index 351ccc955e3..26378bb976b 100644 --- a/packages/proxy/src/node-http.test.ts +++ b/packages/proxy/src/node-http.test.ts @@ -99,6 +99,37 @@ test('a method Fetch refuses is answered with 404 instead of a dropped socket', } }); +test('a handler can cancel an unread body and still answer the request', async () => { + const proxy: DaemonProxy = { + instanceId: 'test', + handle: async (request) => { + await request.body?.cancel(); + return new Response('body declined', { status: 400 }); + }, + }; + const server = http.createServer((req, res) => void serveProxyRequest(proxy, req, res)); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await new Promise((resolve, reject) => { + const request = http.request( + { port, host: '127.0.0.1', method: 'POST', headers: { 'content-length': '4' } }, + resolve, + ); + request.on('error', reject); + request.setTimeout(1_000, () => request.destroy(new Error('No HTTP response'))); + request.flushHeaders(); + }); + expect(response.statusCode).toBe(400); + expect(response.headers.connection).toBe('close'); + let body = ''; + for await (const chunk of response) body += String(chunk); + expect(body).toBe('body declined'); + } finally { + await new Promise((resolve) => server.close(resolve)); + } +}); + test('real HTTP ingress refuses invalid targets and Host before forwarding', async () => { let calls = 0; const server = http.createServer( diff --git a/packages/proxy/src/node-http.ts b/packages/proxy/src/node-http.ts index b5b8ed60866..a2fb3f3bd82 100644 --- a/packages/proxy/src/node-http.ts +++ b/packages/proxy/src/node-http.ts @@ -23,6 +23,7 @@ export async function serveProxyRequest( const response = await proxy.handle(toWebRequest(url, req, res)); res.statusCode = response.status; for (const [name, value] of response.headers) res.setHeader(name, value); + if (!req.complete) res.setHeader('connection', 'close'); if (!response.body) { res.end(); return; @@ -43,13 +44,17 @@ function requestUrl(req: IncomingMessage): URL | null { function toWebRequest(url: URL, req: IncomingMessage, res: ServerResponse): Request { const method = req.method ?? 'GET'; const hasBody = method !== 'GET' && method !== 'HEAD'; + // The HTTP response owns the socket. Canceling a body read must leave it open to answer. + const body = hasBody + ? ( + Readable.toWeb(req, { strategy: { highWaterMark: 0 } }) as ReadableStream + ).pipeThrough(new TransformStream(), { preventCancel: true }) + : undefined; return new Request(url, { method, headers: toWebHeaders(req), signal: clientGoneSignal(req, res), - ...(hasBody - ? { body: Readable.toWeb(req) as ReadableStream, duplex: 'half' as const } - : {}), + ...(body ? { body, duplex: 'half' as const } : {}), }); } diff --git a/packages/proxy/src/rpc-body-budget.ts b/packages/proxy/src/rpc-body-budget.ts new file mode 100644 index 00000000000..bca4dc51e72 --- /dev/null +++ b/packages/proxy/src/rpc-body-budget.ts @@ -0,0 +1,72 @@ +import { + AppError, + createRequestCanceledError, + type ReasonTable, +} from '@agent-device/kernel/errors'; +import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; + +const MAX_IN_FLIGHT_RPC_BODIES = 32; +const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; +const RPC_INGRESS_REASONS = { + // Too many proxy RPC requests or aggregate body bytes are in flight through dispatch. + capacityExceeded: { reason: 'PROXY_RPC_BODY_CAPACITY_EXCEEDED' }, +} as const satisfies ReasonTable<'proxy RPC ingress'>; + +function capacityError(): AppError { + return new AppError('COMMAND_FAILED', 'Proxy RPC ingress capacity exceeded', { + reason: RPC_INGRESS_REASONS.capacityExceeded.reason, + retriable: true, + }); +} + +/** Holds the body bytes until the caller finishes authentication and dispatch. */ +export function createRpcBodyBudget(): { + read(request: Request, maxBodyBytes: number): Promise<{ body: string; release: () => void }>; +} { + let active = 0; + let totalBytes = 0; + return { + async read(request, maxBodyBytes) { + if (active >= MAX_IN_FLIGHT_RPC_BODIES) { + void request.body?.cancel().catch(() => {}); + throw capacityError(); + } + active += 1; + let ownedBytes = 0; + let released = false; + const release = () => { + if (released) return; + released = true; + active -= 1; + totalBytes -= ownedBytes; + }; + try { + if (!request.body) return { body: '', release }; + const reader = request.body.getReader(); + const chunks: Uint8Array[] = []; + for (;;) { + const { done, value } = await awaitWithSignal(reader.read(), request.signal, () => { + void reader.cancel().catch(() => {}); + return createRequestCanceledError(undefined, request.signal.reason); + }); + if (done) break; + if (ownedBytes + value.byteLength > maxBodyBytes) { + await reader.cancel(); + throw new AppError('INVALID_ARGS', 'Proxy request body is too large.'); + } + if (totalBytes + value.byteLength > MAX_IN_FLIGHT_RPC_BODY_BYTES) { + await reader.cancel(); + throw capacityError(); + } + ownedBytes += value.byteLength; + totalBytes += value.byteLength; + chunks.push(value); + } + return { body: Buffer.concat(chunks).toString('utf8'), release }; + } catch (error) { + release(); + throw error; + } + }, + }; +} diff --git a/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts b/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts index e7d35f20840..51efd11c9b0 100644 --- a/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts +++ b/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts @@ -1,6 +1,15 @@ import { expect, test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { readReplayScriptSourceFile } from '../script-source.ts'; +import { REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES as CLIENT_SOURCE_MAX_BYTES } from '../../script-source-bundle.ts'; +import { + assertReplayScriptSourcesWithinLimit, + readReplayScriptSourceFile, + REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, +} from '../script-source.ts'; + +test('client and daemon enforce the same replay source byte ceiling', () => { + expect(REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES).toBe(CLIENT_SOURCE_MAX_BYTES); +}); test('reading a file the bundle does not carry names the file and the entry', () => { const bundle = { entry: '/flows/login.yaml', files: { '/flows/login.yaml': '---\n- back\n' } }; @@ -15,3 +24,91 @@ test('reading a file the bundle does not carry names the file and the entry', () expect((error as AppError).details).toMatchObject({ entry: '/flows/login.yaml' }); } }); + +test('a remote test request cannot hide oversized sources across bundles', () => { + const half = 'x'.repeat(REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES / 2); + const source = { entry: 'flow.ad', files: { 'flow.ad': half } }; + expect(() => + assertReplayScriptSourcesWithinLimit({ replayScriptSources: [source, source] }), + ).not.toThrow(); + expect(() => + assertReplayScriptSourcesWithinLimit({ + replayScriptSources: [source, { entry: 'extra.ad', files: { 'extra.ad': 'x' } }, source], + }), + ).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ + limitBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, + totalBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES + 1, + }), + }), + ); +}); + +test('an oversized replay source path reports the path byte limit', () => { + const entry = 'flow.ad'; + const longPath = 'x'.repeat(64 * 1024); + expect(() => + assertReplayScriptSourcesWithinLimit({ + replayScriptSource: { entry, files: { [entry]: 'x', [longPath]: 'x' } }, + }), + ).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ + limitBytes: 64 * 1024, + totalBytes: 64 * 1024 + 2 * entry.length, + }), + }), + ); +}); + +test('empty replay source names are refused before suite discovery', () => { + expect(() => + assertReplayScriptSourcesWithinLimit({ replayScriptSource: { entry: '', files: { '': '' } } }), + ).toThrow(expect.objectContaining({ code: 'INVALID_ARGS' })); + expect(() => + assertReplayScriptSourcesWithinLimit({ + replayScriptSource: { entry: 'flow.ad', files: { '': '', 'flow.ad': '' } }, + }), + ).toThrow(expect.objectContaining({ code: 'INVALID_ARGS' })); +}); + +test('an empty source list passes source admission', () => { + expect(() => assertReplayScriptSourcesWithinLimit({ replayScriptSources: [] })).not.toThrow(); +}); + +test('empty replay source text cannot evade bundle or file counts', () => { + const source = { entry: 'flow.ad', files: { 'flow.ad': '' } }; + expect(() => + assertReplayScriptSourcesWithinLimit({ replayScriptSources: Array(256).fill(source) }), + ).not.toThrow(); + expect(() => + assertReplayScriptSourcesWithinLimit({ replayScriptSources: Array(257).fill(source) }), + ).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ + limitCount: 256, + totalCount: 257, + hint: expect.stringContaining('Split the suite'), + }), + }), + ); + const files = Object.fromEntries( + Array.from({ length: 2_049 }, (_, index) => [`file-${index}`, '']), + ); + expect(() => + assertReplayScriptSourcesWithinLimit({ replayScriptSource: { entry: 'file-0', files } }), + ).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ + limitCount: 2_048, + totalCount: 2_049, + hint: expect.stringContaining('Split the suite'), + }), + }), + ); +}); diff --git a/packages/replay-port/src/daemon-port/script-source.ts b/packages/replay-port/src/daemon-port/script-source.ts index 717008434cb..a91df0caa9f 100644 --- a/packages/replay-port/src/daemon-port/script-source.ts +++ b/packages/replay-port/src/daemon-port/script-source.ts @@ -1,5 +1,91 @@ import { AppError } from '@agent-device/kernel/errors'; import type { ReplayScriptSourceBundle } from '@agent-device/contracts/replay'; +export const REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES = 2 * 1024 * 1024; +const REPLAY_SCRIPT_SOURCE_PATH_MAX_BYTES = 64 * 1024; +const REPLAY_SCRIPT_SOURCE_MAX_BUNDLES = 256; +const REPLAY_SCRIPT_SOURCE_MAX_FILES = 2_048; + +/** Admit client-supplied replay sources before any engine reads or splits their text. */ +export function assertReplayScriptSourcesWithinLimit( + flags: Record | undefined, +): void { + if (!flags) return; + const sources = replaySourcesFromFlags(flags); + if (!sources) return; + if (sources.length === 0) return; + if (sources.length > REPLAY_SCRIPT_SOURCE_MAX_BUNDLES) { + throw new AppError('INVALID_ARGS', 'Replay request carries too many source bundles.', { + limitCount: REPLAY_SCRIPT_SOURCE_MAX_BUNDLES, + totalCount: sources.length, + hint: 'Split the suite or shard it into smaller invocations.', + }); + } + const size = { text: 0, paths: 0, files: 0 }; + for (const source of sources) validateReplaySource(source, size); +} + +function replaySourcesFromFlags(flags: Record): unknown[] | undefined { + const single = flags.replayScriptSource; + const multiple = flags.replayScriptSources; + if (single === undefined && multiple === undefined) return undefined; + if (single !== undefined && multiple !== undefined) invalidReplaySources(); + const sources = multiple === undefined ? [single] : multiple; + if (!Array.isArray(sources)) invalidReplaySources(); + return sources; +} + +function validateReplaySource( + source: unknown, + size: { text: number; paths: number; files: number }, +): void { + if ( + !isRecord(source) || + typeof source.entry !== 'string' || + source.entry.length === 0 || + !isRecord(source.files) + ) { + invalidReplaySources(); + } + if (typeof source.files[source.entry] !== 'string') invalidReplaySources(); + size.paths += Buffer.byteLength(source.entry, 'utf8'); + for (const [filePath, text] of Object.entries(source.files)) { + if (filePath.length === 0 || typeof text !== 'string') invalidReplaySources(); + size.files += 1; + if (size.files > REPLAY_SCRIPT_SOURCE_MAX_FILES) { + throw new AppError('INVALID_ARGS', 'Replay request carries too many source files.', { + limitCount: REPLAY_SCRIPT_SOURCE_MAX_FILES, + totalCount: size.files, + hint: 'Split the suite or shard it into smaller invocations.', + }); + } + size.paths += Buffer.byteLength(filePath, 'utf8'); + size.text += Buffer.byteLength(text, 'utf8'); + if (size.text > REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES) { + throw new AppError('INVALID_ARGS', 'Replay script sources exceed the request byte limit.', { + limitBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, + totalBytes: size.text, + }); + } + if (size.paths > REPLAY_SCRIPT_SOURCE_PATH_MAX_BYTES) { + throw new AppError( + 'INVALID_ARGS', + 'Replay script source paths exceed the request byte limit.', + { + limitBytes: REPLAY_SCRIPT_SOURCE_PATH_MAX_BYTES, + totalBytes: size.paths, + }, + ); + } + } +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function invalidReplaySources(): never { + throw new AppError('INVALID_ARGS', 'Replay script sources must contain an entry and text files.'); +} export const REPLAY_SCRIPT_SOURCE_REQUIRED_MESSAGE = 'This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.'; diff --git a/packages/replay-port/src/script-source-bundle.ts b/packages/replay-port/src/script-source-bundle.ts index 57cf3b05c01..c20f58c3558 100644 --- a/packages/replay-port/src/script-source-bundle.ts +++ b/packages/replay-port/src/script-source-bundle.ts @@ -4,7 +4,6 @@ import type { ReplayScriptSourceBundle } from '@agent-device/contracts/replay'; import { resolveUserPath } from '@agent-device/host-kit/file'; import { resolveReplayFormat } from '@agent-device/ad-script'; import type { ReplayBackend } from '@agent-device/contracts/replay-backend'; - export const REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES = 2 * 1024 * 1024; export type ReplayScriptSourceRequest = { diff --git a/packages/test-kit/src/web-managed-agent-browser.ts b/packages/test-kit/src/web-managed-agent-browser.ts index 91b0ef5cbef..36c7f24fee9 100644 --- a/packages/test-kit/src/web-managed-agent-browser.ts +++ b/packages/test-kit/src/web-managed-agent-browser.ts @@ -4,7 +4,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -const TEST_AGENT_BROWSER_VERSION = '0.39.0'; +const TEST_AGENT_BROWSER_VERSION = '0.42.0'; type FakeManagedAgentBrowserInstall = ReturnType; diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 11c8757f593..dd3ae441c96 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -691,6 +691,7 @@ Rules: body: `agent-device help web Use --platform web only for the minimal browser command loop exposed through agent-device. +Managed web sessions run locally. A tenant request through the remote proxy or a daemon auth hook is refused with reason remote_web_public_network_unenforced because browser subrequests cannot be restricted to public destinations. A remote request that reaches the managed browser without passing daemon admission is refused with reason remote_web_browser_unconfined; close remains available for cleanup. Dependency: Browser mechanics come from a managed, pinned agent-browser backend. agent-device owns command/session/replay integration, selectors/refs at the command surface, and artifact routing; agent-browser owns browser launch, page control, screenshots, and browser-specific behavior. diff --git a/src/core/interactors/limrun-http-response.test.ts b/src/core/interactors/limrun-http-response.test.ts new file mode 100644 index 00000000000..403aa59704c --- /dev/null +++ b/src/core/interactors/limrun-http-response.test.ts @@ -0,0 +1,33 @@ +import { expect, test } from 'vitest'; +import { readLimrunControlJson } from './limrun-http-response.ts'; + +test('stops an oversized Limrun control response before accepting its body', async () => { + const response = new Response('{}', { + headers: { 'content-length': String(32 * 1024 * 1024 + 1) }, + }); + + await expect(readLimrunControlJson(response)).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'provider_response_too_large', limitBytes: 32 * 1024 * 1024 }, + }); +}); + +test('stops a streaming Limrun control response without a declared length', async () => { + const response = new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)); + }, + }), + ); + + await expect(readLimrunControlJson(response)).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'provider_response_too_large', limitBytes: 32 * 1024 * 1024 }, + }); +}); + +test('parses a bounded Limrun control response with a UTF-8 byte-order mark', async () => { + const response = new Response('\ufeff{"synced":true}'); + await expect(readLimrunControlJson(response)).resolves.toEqual({ synced: true }); +}); diff --git a/src/core/interactors/limrun-http-response.ts b/src/core/interactors/limrun-http-response.ts new file mode 100644 index 00000000000..0e2a1940ed3 --- /dev/null +++ b/src/core/interactors/limrun-http-response.ts @@ -0,0 +1,48 @@ +import { AppError } from '@agent-device/kernel/errors'; +import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/remote'; + +const MAX_LIMRUN_CONTROL_RESPONSE_BYTES = 32 * 1024 * 1024; + +export async function readLimrunControlText( + response: Response, + signal?: AbortSignal, +): Promise { + signal?.throwIfAborted(); + const declaredBytes = Number(response.headers.get('content-length')); + if (Number.isFinite(declaredBytes) && declaredBytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) { + await response.body?.cancel().catch(() => {}); + throw responseTooLarge(); + } + if (!response.body) return ''; + const reader = response.body.getReader(); + const cancel = () => void reader.cancel(signal?.reason).catch(() => {}); + signal?.addEventListener('abort', cancel, { once: true }); + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + while (true) { + const { done, value } = await reader.read(); + signal?.throwIfAborted(); + if (done) return new TextDecoder().decode(Buffer.concat(chunks, bytes)); + bytes += value.byteLength; + if (bytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) { + throw responseTooLarge(); + } + chunks.push(value); + } + } finally { + signal?.removeEventListener('abort', cancel); + void reader.cancel().catch(() => {}); + } +} + +function responseTooLarge(): AppError { + return new AppError('COMMAND_FAILED', 'Limrun response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, + limitBytes: MAX_LIMRUN_CONTROL_RESPONSE_BYTES, + }); +} + +export async function readLimrunControlJson(response: Response): Promise { + return JSON.parse(await readLimrunControlText(response)) as T; +} diff --git a/src/core/interactors/limrun-ios-files.ts b/src/core/interactors/limrun-ios-files.ts index 9ad197b71d6..7d96f7184d0 100644 --- a/src/core/interactors/limrun-ios-files.ts +++ b/src/core/interactors/limrun-ios-files.ts @@ -9,6 +9,7 @@ import { import type { LimrunRuntimeDependencies } from '@agent-device/provider-limrun'; import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import { downloadLimrunFile } from '../limrun-download-file.ts'; +import { readLimrunControlJson } from './limrun-http-response.ts'; type Session = Parameters[0]; type Files = AppleToolProvider['simulatorFiles']; @@ -95,7 +96,9 @@ export function createLimrunSimulatorFiles( const list = () => operation(container, async (signal) => { const response = await request('GET', urlFor('files/list', '', container), signal); - const result = (await response.json()) as { entries: Array<{ name: string }> }; + const result = await readLimrunControlJson<{ entries: Array<{ name: string }> }>( + response, + ); return result.entries.map((entry) => entry.name); }); try { @@ -141,7 +144,7 @@ export function createLimrunSimulatorFiles( signal, await fs.readFile(localPath, { signal }), ); - return (await response.json()) as { path: string }; + return await readLimrunControlJson<{ path: string }>(response); }).catch(async (error: unknown) => { await remove().catch(() => {}); throw error; diff --git a/src/core/interactors/limrun-ios-runner-products.ts b/src/core/interactors/limrun-ios-runner-products.ts index c4cc114849f..ff305f0e81d 100644 --- a/src/core/interactors/limrun-ios-runner-products.ts +++ b/src/core/interactors/limrun-ios-runner-products.ts @@ -1,4 +1,5 @@ import { limrunRunnerError } from './limrun-ios-runner-errors.ts'; +import { readLimrunControlJson } from './limrun-http-response.ts'; import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { runnerListenerEnv, @@ -305,7 +306,7 @@ export async function uploadLimrunRunnerProducts( }, ); } - return (await response.json()) as { ok?: boolean; needFull?: string[] }; + return await readLimrunControlJson<{ ok?: boolean; needFull?: string[] }>(response); } finally { stream.destroy(); await compression; diff --git a/src/core/interactors/limrun-ios-runner.test.ts b/src/core/interactors/limrun-ios-runner.test.ts index d39348077a9..50c37871fa0 100644 --- a/src/core/interactors/limrun-ios-runner.test.ts +++ b/src/core/interactors/limrun-ios-runner.test.ts @@ -136,16 +136,16 @@ test('an admitted XCTest stream survives its launch deadline', async () => { test('a stalled rejection body respects the launch deadline and does not claim the occupied slot', async () => { const timeout = new AbortController(); - let markReadStarted!: () => void; - const readStarted = new Promise((resolve) => { - markReadStarted = resolve; + let markBodyRead!: () => void; + const bodyRead = new Promise((resolve) => { + markBodyRead = resolve; }); - const readText = Response.prototype.text; + const getBody = Object.getOwnPropertyDescriptor(Response.prototype, 'body')!.get!; const responseBody = vi - .spyOn(Response.prototype, 'text') + .spyOn(Response.prototype, 'body', 'get') .mockImplementation(function (this: Response) { - if (this.status === 409) markReadStarted(); - return readText.call(this); + if (this.status === 409) markBodyRead(); + return getBody.call(this); }); const realTimeout = AbortSignal.timeout.bind(AbortSignal); const timer = vi @@ -163,7 +163,7 @@ test('a stalled rejection body respects the launch deadline and does not claim t { healthCheck: false }, ); const failed = expect(prepare()).rejects.toMatchObject({ details: { status: 409 } }); - await readStarted; + await bodyRead; timeout.abort(new DOMException('Admission expired', 'TimeoutError')); await failed; timer.mockRestore(); @@ -240,13 +240,12 @@ test.each([ const conflict = new Promise((resolve) => { conflictRead = resolve; }); - const originalText = Response.prototype.text; + const getBody = Object.getOwnPropertyDescriptor(Response.prototype, 'body')!.get!; const responseBody = vi - .spyOn(Response.prototype, 'text') - .mockImplementation(async function (this: Response) { - const body = await originalText.call(this); + .spyOn(Response.prototype, 'body', 'get') + .mockImplementation(function (this: Response) { if (this.status === 409) conflictRead(); - return body; + return getBody.call(this); }); vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); try { diff --git a/src/core/interactors/limrun-ios-runner.ts b/src/core/interactors/limrun-ios-runner.ts index d906dc8124f..3094bafeff3 100644 --- a/src/core/interactors/limrun-ios-runner.ts +++ b/src/core/interactors/limrun-ios-runner.ts @@ -21,6 +21,7 @@ import { writeLimrunRunnerConfiguration, type LimrunRunnerProducts, } from './limrun-ios-runner-products.ts'; +import { readLimrunControlText } from './limrun-http-response.ts'; type LimrunIosRunner = Awaited>; type Session = Parameters[0]; @@ -187,7 +188,10 @@ export async function createLimrunIosRunner( `Limrun XCTest launch failed (${result.status})`, { status: result.status, - response: await awaitWithSignal(result.text(), launchSignal).catch(() => undefined), + response: await awaitWithSignal( + readLimrunControlText(result, launchSignal), + launchSignal, + ).catch(() => undefined), }, ); if (result.status === 409) lastConflict = failure; diff --git a/src/platform-runtime-provider-scope.test.ts b/src/platform-runtime-provider-scope.test.ts index fcb273c7356..70d7e5369e7 100644 --- a/src/platform-runtime-provider-scope.test.ts +++ b/src/platform-runtime-provider-scope.test.ts @@ -1,5 +1,8 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; +import { AppError } from '@agent-device/kernel/errors'; +import { webSessionDevice } from '@agent-device/kernel/device'; +import { withCommandExecutorOverride } from '@agent-device/host-kit/command'; import type { PlatformProviderRequestContext, RequestPlatformProviderScope, @@ -9,6 +12,8 @@ import { IOS_SIMULATOR, MACOS_DEVICE, WEB_DESKTOP_DEVICE, + bindTestCommandHost, + createTestHostEnvironment, } from '@agent-device/test-kit'; import { createLocalAppleToolProvider, runXcrun } from '@agent-device/platform-apple/tool-provider'; import { buildSimctlArgsForDevice } from '@agent-device/platform-apple/simctl'; @@ -23,6 +28,8 @@ import { type PlatformProviderResolvers, } from './platform-runtime.ts'; +bindTestCommandHost(); + const OTHER_IOS_SIMULATOR = { platform: 'apple', id: 'sim-2', @@ -176,6 +183,40 @@ test('web provider scope uses the context device', async () => { assert.deepEqual(calls, ['web-session:agent-browser-chrome', 'open:https://example.test']); }); +test('default web provider carries remote confinement through composition before browser work', async () => { + const browserCalls: string[] = []; + const providers = createRequestPlatformProviders({ + defaultWebProvider: { + host: createTestHostEnvironment(), + openWebSessionNames: () => [], + }, + }); + const device = webSessionDevice(WEB_DESKTOP_DEVICE, { name: 'remote-web' }); + await withCommandExecutorOverride( + async (cmd) => { + browserCalls.push(cmd); + throw new Error('confined browser must refuse before command execution'); + }, + async () => { + await assert.rejects( + providers.run( + { + ...context(device, 'remote-web'), + useDefaultWebProvider: true, + publicNetworkOnly: true, + }, + async () => await (await scopedWebProvider()).open('https://example.test'), + ), + (error: unknown) => + error instanceof AppError && + error.code === 'UNSUPPORTED_OPERATION' && + error.details?.reason === 'remote_web_browser_unconfined', + ); + }, + ); + assert.deepEqual(browserCalls, []); +}); + test('generic Apple runner provider cannot borrow local recording authority', async () => { await withRequestPlatformProviderScope( context(MACOS_DEVICE, 'macos-session'), diff --git a/src/platform-runtime/request-providers.ts b/src/platform-runtime/request-providers.ts index 7dd3adadd8b..ddbcf8a3fa6 100644 --- a/src/platform-runtime/request-providers.ts +++ b/src/platform-runtime/request-providers.ts @@ -159,6 +159,7 @@ async function providersForContext( stateDir: defaultWebProvider.stateDir, openWebSessionNames: defaultWebProvider.openWebSessionNames, ownedProcessRecords: defaultWebProvider.ownedProcessRecords, + ...(context.publicNetworkOnly === true ? { publicNetworkOnly: true } : {}), }); return { ...providers, diff --git a/test/integration/provider-scenarios/web-provider.test.ts b/test/integration/provider-scenarios/web-provider.test.ts index a4dfd247c56..945f94e4a70 100644 --- a/test/integration/provider-scenarios/web-provider.test.ts +++ b/test/integration/provider-scenarios/web-provider.test.ts @@ -231,8 +231,9 @@ test('non-dense browser refs survive snapshot storage and routed fill and click' const entries = JSON.parse(String(options.stdin)) as string[][]; const results = entries.map((entry) => { assert.equal(entry[0], 'fill', `Unexpected batch entry: ${entry}`); + assert.equal(entry[2], '--', `Missing fill value separator: ${entry}`); calls.push(entry); - values[entry[1]!] = entry[2]!; + values[entry[1]!] = entry[3]!; return { command: entry, error: null, result: {}, success: true }; }); return { stdout: JSON.stringify(results), stderr: '', exitCode: 0 }; @@ -292,7 +293,7 @@ test('non-dense browser refs survive snapshot storage and routed fill and click' assert.equal(click.json.error, undefined); assert.equal(signedIn, true); assert.deepEqual(calls, [ - ['fill', '@e2', 'Ada'], + ['fill', '@e2', '--', 'Ada'], ['click', '@e4'], ]); } finally { diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index fe101d4a583..f33634a6690 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -86,7 +86,7 @@ "packages/daemon/src/server/http-errors.ts#NormalizedHttpError": "sha256:2c2111802fe5f193acbeacc454de9cfab82bc8e4274b896f485e19a14f5518cf", "packages/daemon/src/server/http-errors.ts#failStreamedHttpResponse": "sha256:3e6b642cb41b88ab1e6f3269ebd14918f912cbecf09f40e9b591fdd28a2ba489", "packages/daemon/src/server/http-errors.ts#sendRestJsonError": "sha256:aef588e77ea73eb3cf6e94ec2f2c98a434fcaaeb96de6973a43c442b704694ad", - "packages/daemon/src/server/http-errors.ts#statusCodeForNormalizedError": "sha256:39aa61eed8459527d7077e31e23be4fe0275021ed99c70ad692538091db91125", + "packages/daemon/src/server/http-errors.ts#statusCodeForNormalizedError": "sha256:2d13b89473a83112ed98c53c885e62d852d0ee7cda858ff979c5b294a3bac2a1", "packages/daemon/src/server/http-request-target.ts#decodeUriSegment": "sha256:b37622771ea4e61d1a9820169dbdc5809b5c38889bfad79277d7b22f3c3f1ef1", "packages/daemon/src/server/request-diagnostics-http.ts#REQUEST_DIAGNOSTICS_CONTENT_TYPE": "sha256:16bbd9ae7eaeaaa8c8cbd6e65c4ce786a6c5230c5351288228bbf1a6f11bdcdc", "packages/daemon/src/server/request-diagnostics-http.ts#RequestDiagnosticsHttpAuthorizer": "sha256:24b0fa6b1d965e5cf6503a4665148dc6360c56bf5a0ae710eeaa76a73a62c52a", @@ -508,8 +508,8 @@ }, { "declaration": "packages/daemon/src/server/http-errors.ts#statusCodeForNormalizedError", - "digest": "sha256:39aa61eed8459527d7077e31e23be4fe0275021ed99c70ad692538091db91125", - "rationale": "The mapper now takes the normalized error (code plus details) instead of the code alone. A gone resource now answers 404 instead of 500: COMMAND_FAILED with details.reason RESOURCE_EXPIRED (an artifact, upload ticket, uploaded artifact or materialized path id the TTL registry no longer holds) maps to 404. The mapper also takes over the DEVICE_IN_USE human_control_active 423 rule, which statusCodeForDaemonError applied only to a failed response a /rpc handler returned. The rule now also reaches the REST routes and thrown /rpc failures, which answered 500: a PUT /admin/leases/ refused during a human-control hold, or a non-streamed /rpc call whose handler throws human_control_active, now answers 423. /admin/* is host-only on the loopback port and the proxy never forwards it, and the host already reads 423 for the same refusal on a returned /rpc failure. No released client branches on 404 versus 500 for these routes: downloadRemoteArtifactFromUrl treats any status >= 400 alike, the upload client fails any non-2xx and decides retries from a typed stream detail rather than the status, the /rpc client parses the JSON-RPC error envelope whatever the status and only special-cases 409, and the proxy passes the status through. The error code, message and JSON-RPC error data a peer parses are unchanged, so a protocol 2 peer reports the same failure it did before." + "digest": "sha256:2d13b89473a83112ed98c53c885e62d852d0ee7cda858ff979c5b294a3bac2a1", + "rationale": "The mapper now takes the normalized error (code plus details) instead of the code alone. A gone resource now answers 404 instead of 500: COMMAND_FAILED with details.reason RESOURCE_EXPIRED (an artifact, upload ticket, uploaded artifact or materialized path id the TTL registry no longer holds) maps to 404. The mapper also takes over the DEVICE_IN_USE human_control_active 423 rule, which statusCodeForDaemonError applied only to a failed response a /rpc handler returned. The rule now also reaches the REST routes and thrown /rpc failures, which answered 500: a PUT /admin/leases/ refused during a human-control hold, or a non-streamed /rpc call whose handler throws human_control_active, now answers 423. /admin/* is host-only on the loopback port and the proxy never forwards it, and the host already reads 423 for the same refusal on a returned /rpc failure. No released client branches on 404 versus 500 for these routes: downloadRemoteArtifactFromUrl treats any status >= 400 alike, the upload client fails any non-2xx and decides retries from a typed stream detail rather than the status, the /rpc client parses the JSON-RPC error envelope whatever the status and only special-cases 409, and the proxy passes the status through. The error code, message and JSON-RPC error data a peer parses are unchanged, so a protocol 2 peer reports the same failure it did before. The newly introduced UPLOAD_CAPACITY_EXCEEDED reason answers 503 instead of the mapper default of 500; no released daemon emitted this reason, and older clients still parse the unchanged error body on either status." }, { "declaration": "packages/daemon/src/server/http-errors.ts#sendRestJsonError", diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index e3d31e2239c..552560b1298 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -526,6 +526,8 @@ Exact behavior: `agent-device help web`. `--platform web` drives a browser through [agent-browser](https://github.com/vercel-labs/agent-browser) and requires Node 24+. Use it when a browser step belongs inside an `agent-device` session, replay, batch, MCP, or Node.js client flow. For standalone browser automation, use `agent-browser` directly. +If your state directory has only managed browser version 0.39.0 installed, web commands can fail with `TOOL_MISSING` after you upgrade `agent-device`. Rerun `agent-device web setup` with the upgraded CLI using the same state directory. Do this for each CI or MCP host that uses the managed browser. + Set up and verify the managed web backend before you open a web session: ```bash @@ -551,6 +553,7 @@ agent-device close --platform web ``` - Run `web setup` before first use and in CI bootstrap. Web commands never install the backend themselves. `web doctor` verifies the install. +- Managed web sessions are available to local requests. A tenant request through the remote proxy or a daemon auth hook is refused when it binds a web device with `remote_web_public_network_unenforced`, including requests for an existing web session that omit `--platform web`. A remote request that reaches the managed browser without passing daemon admission is refused with `remote_web_browser_unconfined` because browser subrequests cannot be restricted to public destinations. `close` remains available to release an existing session. - Each web session has its own browser, cookies, and storage. Sessions with different `--session` names run at once. A session name is 1 to 30 letters, digits, `_`, or `-` (1 to 17 under tenant isolation); another name fails with `web_session_name_invalid`. Without `--session`, each workspace gets its own browser. - Supported: URL open, snapshot refs, `get text/attrs`, `is visible/hidden/exists/absent/focused/text`, `find text/selector`, click/press, hover, fill/type, wait, `network dump`, `audio probe`, screenshot, close, and replay scripts made from those commands. - A coordinate or selector `fill` clicks the point and replaces the field's text. When the click does not reach an editable text field, such as a date input or a field in a cross-origin frame, it fails with `text_entry_focus_not_observed` and types nothing. Run `snapshot -i` and fill the field by ref instead. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index de8b3304a60..de5c147e0e8 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -456,6 +456,12 @@ Treat a reason that this page does not list as unknown, not as an error in the r These reasons can come from more than one command. +### RPC ingress + +| Reason | Meaning | +| --- | --- | +| `RPC_BODY_CAPACITY_EXCEEDED` | Too many daemon RPC requests are in flight through dispatch. The daemon closes a request that exceeds its aggregate body-byte limit. | + ### Swift helper cache | Reason | Meaning | @@ -905,6 +911,18 @@ 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 | +| --- | --- | +| `PROXY_RPC_BODY_CAPACITY_EXCEEDED` | Too many proxy RPC requests or aggregate body bytes are in flight through dispatch. | + ### Ref frames | Reason | Meaning | @@ -939,6 +957,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `REMOTE_HOST_INPUT_DENIED` | A remote request supplied a host path or other host input (`details.field`), which a remote daemon refuses. | +| `remote_web_public_network_unenforced` | The managed browser cannot confine a remote tenant's requests to public destinations. | ### Remote transfer @@ -1051,6 +1070,7 @@ These reasons can come from more than one command. | `UPLOAD_STATE_CORRUPT` | The staged upload holds more bytes than it declared, so it cannot resume; start a new upload. | | `UPLOAD_ROLLBACK_FAILED` | A failed chunk could not be rolled back, so the upload ticket was invalidated; start a new upload. | | `UPLOAD_FINALIZE_CLEANUP_FAILED` | Finalizing the upload failed, and removing its staged files failed too; `details.originalError` holds the first failure. | +| `UPLOAD_CAPACITY_EXCEEDED` | A new upload would exceed the active upload count or reserved byte budget. | | `transfer_ingress_deadline_exceeded` | The upload request exceeded its aggregate deadline (`details.timeoutMs`), which also covers processing after the body arrived. | | `upload_canceled` | The client disconnected or canceled before the upload finished. | @@ -1058,6 +1078,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | +| `remote_web_browser_unconfined` | A remote tenant's browser cannot run before its public-network proxy is enforced. | | `text-entry-result-unusable` | The batch call for a text entry answered with something other than its one echoed entry. | | `text-entry-failed` | The backend ran the fill or type entry and the page refused it. | | `snapshot-refs-unmeasurable` | Every snapshot ref failed to measure, so the capture's refs belong to no live nodes. | diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 91b932471c3..0a71f2c0a50 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -99,6 +99,10 @@ destination on your machine. A recording is different: it downloads to the path `record start` path does not carry over; the working-directory fallback keeps only its file name. Direct RPC callers receive artifact IDs and download each result with `GET /artifacts/` using the same authentication. +For trace and performance stop or report, a destination on the current request wins. Without one, +the client uses a path the daemon echoes from an earlier start request when present. If neither +path is present, it downloads to the working directory using the artifact file name. + By default, artifacts leave the inventory after download or after 15 minutes. `AGENT_DEVICE_RETAIN_ARTIFACTS` keeps downloaded artifacts in inventory until expiry. Downloads already in progress can finish before their files are removed, including overlapping downloads of a directory archive. diff --git a/website/docs/docs/replay-e2e.md b/website/docs/docs/replay-e2e.md index decad3881d1..3b90bf1e4ea 100644 --- a/website/docs/docs/replay-e2e.md +++ b/website/docs/docs/replay-e2e.md @@ -131,6 +131,7 @@ agent-device replay ~/.agent-device/sessions/e2e-2026-02-09T12-00-00-000Z.ad --s - Replay reads `.ad` scripts. - The CLI reads script paths on your machine and sends the script, with the Maestro `runFlow` includes it can resolve and read, to the daemon. An include it cannot read is left out, and the run fails if it reaches that include. The same `replay` or `test` command works against a local or a remote daemon without copying files. A script that doesn't exist on your machine fails at once, naming the path you typed. +- Each replay source bundle is limited to 2 MiB of script text, whether the daemon is local or remote. A non-local remote daemon also accepts at most 2 MiB of source text per request. A `test` request can carry at most 256 source bundles and 2,048 files across those bundles. Split the inputs into separate invocations whose discovered sources fit the count limits. These count limits do not apply to a local daemon. - A script that does not end in `close` leaves its session open. For a script that does end in `close`, pass `--keep-session` to skip only that final action and keep working in the same session: diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 9e7fd4cc42c..2be64326234 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -18,10 +18,10 @@ CLI commands run through a per-user background daemon: - The daemon binds to `127.0.0.1` only, on ephemeral ports, for both its socket and HTTP transports. It is not reachable from the network unless you put your own proxy in front of it. - Command (RPC), upload, artifact-download, and `/admin/human-control/*` requests must present a token that the daemon generates fresh on each start (24 random bytes). The only unauthenticated endpoint is `GET /health`, which returns only liveness, package and protocol version, instance ID, and host CPU architecture; like the rest of the server, it is reachable only over loopback. The token is stored in `daemon.json` inside the daemon state directory (`~/.agent-device` for packaged installs; source checkouts use a worktree-scoped directory under `~/.agent-device/dev/`) with `0600` permissions. Anyone who can read that file already has your user account. - A client reuses a running daemon only when the daemon runs the same version and the same code. Two installs of the same published version share one daemon. An older client refuses to replace a reachable daemon on a newer version, so it does not disrupt that daemon's sessions; upgrade the client instead. Any other mismatch, such as a source checkout against an install, restarts the daemon instead of running code the client cannot identify. The code check compares file sizes and timestamps, not contents, so it does not detect an install whose files were hand-replaced under the same version. -- Artifact uploads are size-capped, filenames are sanitized, and archive extraction rejects path-traversal entries. Artifact downloads resolve through server-side IDs, never client-supplied paths. +- Artifact uploads are size-capped, filenames are sanitized, and archive extraction rejects path-traversal entries. Resumable uploads allow at most 32 active tickets and 4 GiB of reserved bytes per tenant, with daemon-wide limits of 256 tickets and 16 GiB. A ticket expires after five minutes without a received chunk. Artifact downloads resolve through server-side IDs, never client-supplied paths. - `install-from-source` protects the daemon host while it downloads and extracts the artifact; it does not vouch for the app inside. An app installed and launched on an iOS simulator runs as a process on the host Mac, so treat permission to send install requests as permission to run code on that Mac. -For remote or cloud deployments, you can add a custom auth hook for remotely consumable HTTP routes: set `AGENT_DEVICE_HTTP_AUTH_HOOK` to a module path that the daemon imports, and `AGENT_DEVICE_HTTP_AUTH_EXPORT` to select the export. Relative hook paths resolve from the daemon host's working directory. The host-local `/admin/human-control/*` route uses the daemon token instead. The hook runs with the daemon's full privileges, so treat it as trusted code: point it only at a read-only path you control, never at a location that less-trusted users or processes can write to. Whoever controls the daemon's environment controls the hook. On the upload routes, the hook context carries a `signal` that aborts when the upload request times out or its client disconnects. The daemon stops waiting for the hook at that point, so a hook that calls a slow identity service can use the signal to stop that call. +For remote or cloud deployments, you can add a custom auth hook for remotely consumable HTTP routes: set `AGENT_DEVICE_HTTP_AUTH_HOOK` to a module path that the daemon imports, and `AGENT_DEVICE_HTTP_AUTH_EXPORT` to select the export. Relative hook paths resolve from the daemon host's working directory. The host-local `/admin/human-control/*` route uses the daemon token instead. The hook runs with the daemon's full privileges, so treat it as trusted code: point it only at a read-only path you control, never at a location that less-trusted users or processes can write to. Whoever controls the daemon's environment controls the hook. On upload and RPC routes, the hook context carries a `signal` that aborts when the client disconnects. An upload deadline also aborts its signal. The daemon stops waiting for the hook at that point, so a hook that calls a slow identity service can use the signal to stop that call. Lease-owner human-control RPCs pass normal authentication and tenant/lease admission. They can target only the admitted lease's device and cannot alter a host administrator's hold. Host @@ -31,6 +31,8 @@ Holds and leases live in memory; neither survives a daemon restart. When a hook is configured, it must attest a `tenantId` on every request it wants admitted. If the hook's result has no `tenantId`, the daemon rejects the request with 401. It never falls back to a tenant the client declares (RPC body `meta.tenantId` or `flags.tenant`, or the `x-agent-device-tenant` header on the upload, artifact-download, and diagnostics routes), and it never admits the request unscoped. This keeps a caller with a shared token from claiming another tenant's identity, or from reading a tenant-owned session or artifact by declaring no tenant. Deployments without a hook are unaffected. +A tenant can read only artifacts registered to that tenant. Artifacts produced by local work without a tenant remain available to local callers without a tenant. Cloud artifact lookup by lease ID requires an active lease whose tenant, run, and provider match the request. The daemon and proxy each limit concurrent RPC requests to 32 and their accumulated request bodies to 128 MiB. These budgets remain reserved through request dispatch. When the concurrent request limit is reached, the daemon returns 503 with reason `RPC_BODY_CAPACITY_EXCEEDED`; when its aggregate byte limit is reached, it closes the request. The proxy returns 503 with reason `PROXY_RPC_BODY_CAPACITY_EXCEEDED` when either limit is reached. + ## Remote access The supported remote setup keeps the daemon and proxy HTTP listeners on `127.0.0.1` and reaches them through an encrypted channel: