From eab6024a7aff7bbe0eada48c29a4bdb13e5f6dcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 14:01:16 +0100 Subject: [PATCH 01/15] fix(daemon): enforce tenant and ingress security boundaries --- .../core/__tests__/tenant-owned-entry.test.ts | 10 ++- .../daemon/src/core/tenant-owned-entry.ts | 2 +- .../daemon/src/resources/artifact-tracking.ts | 2 +- .../daemon/src/resources/lease-registry.ts | 8 ++ .../__tests__/http-server-artifacts.test.ts | 4 +- .../http-server-rpc-admission.test.ts | 57 ++++++++++++++ .../http-server-rpc-validation.test.ts | 36 ++++++++- .../request-router-web-sessions.test.ts | 56 +++++++++++++ .../server/__tests__/resumable-upload.test.ts | 22 ++++++ .../http-server-rpc-ingress-budget.test.ts | 45 +++++++++++ .../daemon/src/server/http/http-server.ts | 78 +++++++++++++++---- .../src/server/remote-host-input-policy.ts | 60 ++++++++++---- .../src/server/request-execution-scope.ts | 11 ++- .../daemon/src/server/resumable-upload.ts | 32 ++++++++ .../__tests__/lease-artifacts.test.ts | 27 ++++++- .../daemon/src/sessions/handlers/lease.ts | 3 + packages/proxy/src/daemon-proxy.test.ts | 36 +++++++++ packages/proxy/src/daemon-proxy.ts | 58 ++++++-------- packages/proxy/src/rpc-body-budget.ts | 61 +++++++++++++++ .../__tests__/script-source.test.ts | 24 +++++- .../src/daemon-port/script-source.ts | 50 ++++++++++++ .../replay-port/src/script-source-bundle.ts | 1 - src/commands/schema/cli-help.ts | 1 + website/docs/docs/commands.md | 1 + website/docs/docs/error-reasons.md | 14 ++++ website/docs/docs/remote-proxy.md | 4 + website/docs/docs/security-trust.md | 6 +- 27 files changed, 631 insertions(+), 78 deletions(-) create mode 100644 packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts create mode 100644 packages/proxy/src/rpc-body-budget.ts 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..3a6ec4b178b 100644 --- a/packages/daemon/src/core/tenant-owned-entry.ts +++ b/packages/daemon/src/core/tenant-owned-entry.ts @@ -35,7 +35,7 @@ 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`, 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-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..a1112d0c298 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 @@ -2,6 +2,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { test } 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 { @@ -11,6 +12,7 @@ import { skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; import { postRpcCommand, startRpcServer } from './http-server-rpc.fixtures.ts'; +import { getRequestSignal } from '@agent-device/host-kit/request'; const DAEMON_TOKEN = 'admission-daemon-secret'; const HOOK_CALLS_ENV = 'AGENT_DEVICE_TEST_HOOK_CALLS'; @@ -96,6 +98,61 @@ 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 & { + __rpcAuthHookReady?: () => void; + __rpcAuthHookSignal?: AbortSignal; + }; + const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK; + let signalReady!: () => void; + const ready = new Promise((resolve) => { + signalReady = resolve; + }); + state.__rpcAuthHookReady = signalReady; + const { port, server } = await startWithAuthHook( + 'export default ({ signal }) => { globalThis.__rpcAuthHookSignal = signal; globalThis.__rpcAuthHookReady(); return new Promise(() => {}); };', + async () => ({ 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 ready; + const signal = state.__rpcAuthHookSignal; + assert.ok(signal); + request.destroy(); + if (!signal.aborted) + await new Promise((resolve) => + signal.addEventListener('abort', () => resolve(), { once: true }), + ); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(getRequestSignal('stalled-auth-hook'), undefined); + } finally { + delete state.__rpcAuthHookReady; + 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..c856f1dbf0b 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,35 @@ 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.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..7b7aa02c040 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,62 @@ 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('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/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..0550199b654 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,13 @@ 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 RPC bodies or aggregate bytes are in flight before request authentication. + 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 +156,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) { @@ -247,7 +259,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 +273,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 +305,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 +544,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 +578,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 +595,7 @@ function beginRpcRequestLifetime(params: { }; return { + signal: disconnectSignal, admit(daemonRequest) { requestId = resolveRequestTrackingId(daemonRequest.meta?.requestId, rpcId); abortRegistration = registerRequestAbort(requestId, undefined, { @@ -559,7 +609,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 +618,7 @@ function beginRpcRequestLifetime(params: { handlerCompleted = true; }, release() { - if (onClientGone) disconnectSignal?.removeEventListener('abort', onClientGone); + if (onClientGone) disconnectSignal.removeEventListener('abort', onClientGone); clearRequestAbortRegistration(abortRegistration); }, }; @@ -638,6 +687,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/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..c71cb805fee 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,27 @@ 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) => error instanceof AppError && error.code === 'UNAUTHORIZED', + ); + 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'); @@ -289,7 +310,8 @@ async function listArtifacts( scope: { tenantId: string; runId: string; - providerSessionId: string; + providerSessionId?: string; + leaseId?: string; leaseProvider?: string; }, ): Promise { @@ -300,9 +322,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..663b54e1c56 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.tenantId && 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/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index da033696077..62d4884b221 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -210,6 +210,42 @@ 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' }), + ); + }); + + const refused = await proxy.handle( + rpcRequest({ jsonrpc: '2.0', id: 33, method: 'agent-device.command' }), + ); + expect(refused.status).toBe(500); + 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('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..0d9f898e941 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(); } } @@ -598,6 +601,7 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti await admission; return fetch(request); }); + let rpcBodyBudget: Promise> | undefined; return { upstreamBaseUrl, publicOrigin: @@ -608,6 +612,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 +769,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); diff --git a/packages/proxy/src/rpc-body-budget.ts b/packages/proxy/src/rpc-body-budget.ts new file mode 100644 index 00000000000..4e26166bd54 --- /dev/null +++ b/packages/proxy/src/rpc-body-budget.ts @@ -0,0 +1,61 @@ +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; + +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 bodies or aggregate bytes are in flight before authentication. + 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) 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 reader.read(); + 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..8225ea03c91 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,16 @@ 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' })); +}); diff --git a/packages/replay-port/src/daemon-port/script-source.ts b/packages/replay-port/src/daemon-port/script-source.ts index 717008434cb..ff267ca3dab 100644 --- a/packages/replay-port/src/daemon-port/script-source.ts +++ b/packages/replay-port/src/daemon-port/script-source.ts @@ -1,5 +1,55 @@ 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; + +/** 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; + const size = { text: 0, paths: 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 }): void { + if (!isRecord(source) || typeof source.entry !== 'string' || !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 (typeof text !== 'string') invalidReplaySources(); + 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 > 64 * 1024) invalidReplaySources(); + } +} + +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/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 11c8757f593..6273ca22468 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 remote tenant request to a web device is refused with reason remote_web_public_network_unenforced because browser subrequests cannot be confined to public destinations; 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/website/docs/docs/commands.md b/website/docs/docs/commands.md index e3d31e2239c..1a36dc2d588 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -551,6 +551,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. +- Web sessions require a local daemon. A remote daemon refuses web device commands with `remote_web_public_network_unenforced`; `close` remains available to release an existing remote web 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..52ab0b1916e 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 RPC bodies or aggregate bytes are in flight before request authentication. | + ### Swift helper cache | Reason | Meaning | @@ -905,6 +911,12 @@ These reasons can come from more than one command. | `exit-timeout` | SIGKILL was sent and nothing proved the process exited within the budget it was given. | | `identity-unverified` | Nothing confirmed the pid names the recorded process, so signalling it was refused. | +### Proxy RPC ingress + +| Reason | Meaning | +| --- | --- | +| `PROXY_RPC_BODY_CAPACITY_EXCEEDED` | Too many proxy RPC bodies or aggregate bytes are in flight before authentication. | + ### Ref frames | Reason | Meaning | @@ -939,6 +951,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 +1064,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. | diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 91b932471c3..dc2ebff2c98 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 downloads to a unique file in its working directory using the artifact name as a stem. A path echoed by the +daemon from an earlier start request does not select a client destination. + 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/security-trust.md b/website/docs/docs/security-trust.md index 9e7fd4cc42c..a0d5f492cae 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 bound concurrent RPC bodies to 32 requests and 128 MiB of accumulated body bytes. When that request limit is reached, the daemon returns 503 with reason `RPC_BODY_CAPACITY_EXCEEDED`; the proxy returns a JSON-RPC failure with reason `PROXY_RPC_BODY_CAPACITY_EXCEEDED`. + ## 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: From 61864c741539fae7060234eba8b3ec43c656cdc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 14:15:28 +0100 Subject: [PATCH 02/15] fix(daemon): close security review gaps --- .../daemon/src/core/tenant-owned-entry.ts | 4 +- .../__tests__/http-errors-rpc-status.test.ts | 19 ++++++++ .../http-server-rpc-admission.test.ts | 23 +++------- .../http-server-rpc-validation.test.ts | 4 ++ .../request-router-web-sessions.test.ts | 19 ++++++++ packages/daemon/src/server/http-errors.ts | 4 +- .../__tests__/lease-artifacts.test.ts | 22 ++++++++-- .../daemon/src/sessions/handlers/lease.ts | 2 +- .../src/daemon-proxy-cancellation.test.ts | 36 +++++++++++++++ packages/proxy/src/daemon-proxy.test.ts | 44 ++++++++++++++++++- packages/proxy/src/daemon-proxy.ts | 23 ++++++---- packages/proxy/src/rpc-body-budget.ts | 19 ++++++-- .../__tests__/script-source.test.ts | 28 +++++++++++- .../src/daemon-port/script-source.ts | 12 ++++- website/docs/docs/commands.md | 2 +- website/docs/docs/error-reasons.md | 4 +- website/docs/docs/remote-proxy.md | 4 +- website/docs/docs/security-trust.md | 2 +- 18 files changed, 227 insertions(+), 44 deletions(-) diff --git a/packages/daemon/src/core/tenant-owned-entry.ts b/packages/daemon/src/core/tenant-owned-entry.ts index 3a6ec4b178b..39c3d292f1a 100644 --- a/packages/daemon/src/core/tenant-owned-entry.ts +++ b/packages/daemon/src/core/tenant-owned-entry.ts @@ -38,7 +38,9 @@ export function requireTenantOwnedEntry( 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/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-rpc-admission.test.ts b/packages/daemon/src/server/__tests__/http-server-rpc-admission.test.ts index a1112d0c298..3ff99a18171 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,5 +1,5 @@ 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'; @@ -101,17 +101,11 @@ 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 & { - __rpcAuthHookReady?: () => void; __rpcAuthHookSignal?: AbortSignal; }; const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK; - let signalReady!: () => void; - const ready = new Promise((resolve) => { - signalReady = resolve; - }); - state.__rpcAuthHookReady = signalReady; const { port, server } = await startWithAuthHook( - 'export default ({ signal }) => { globalThis.__rpcAuthHookSignal = signal; globalThis.__rpcAuthHookReady(); return new Promise(() => {}); };', + 'export default ({ signal }) => { globalThis.__rpcAuthHookSignal = signal; return new Promise(() => {}); };', async () => ({ ok: true, data: {} }), ); try { @@ -135,18 +129,15 @@ test('a disconnected rpc caller cancels a nonresolving auth hook and releases re }, }), ); - await ready; + await vi.waitFor(() => assert.ok(state.__rpcAuthHookSignal), { timeout: 1_000 }); const signal = state.__rpcAuthHookSignal; assert.ok(signal); request.destroy(); - if (!signal.aborted) - await new Promise((resolve) => - signal.addEventListener('abort', () => resolve(), { once: true }), - ); - await new Promise((resolve) => setImmediate(resolve)); - assert.equal(getRequestSignal('stalled-auth-hook'), undefined); + await vi.waitFor(() => assert.equal(signal.aborted, true), { timeout: 1_000 }); + await vi.waitFor(() => assert.equal(getRequestSignal('stalled-auth-hook'), undefined), { + timeout: 1_000, + }); } finally { - delete state.__rpcAuthHookReady; delete state.__rpcAuthHookSignal; restoreEnv('AGENT_DEVICE_HTTP_AUTH_HOOK', previousHook); await closeLoopbackServer(server); 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 c856f1dbf0b..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 @@ -337,6 +337,10 @@ test('remote replay rejects an oversized raw source before dispatch', async (t) }); 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); 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 7b7aa02c040..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 @@ -223,6 +223,25 @@ test('remote requests cannot use an existing web session without a platform flag 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/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/sessions/handlers/__tests__/lease-artifacts.test.ts b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts index c71cb805fee..15263141a63 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts @@ -43,7 +43,23 @@ test('artifacts admits an owned lease ID and refuses a foreign lease ID before c await assert.rejects( () => listArtifacts(world, { tenantId: 'tenant-b', runId: 'run-b', leaseId: lease.leaseId }), - (error: unknown) => error instanceof AppError && error.code === 'UNAUTHORIZED', + (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, []); @@ -308,8 +324,8 @@ async function releaseLease(world: World, lease: DeviceLease): Promise { async function listArtifacts( world: World, scope: { - tenantId: string; - runId: string; + tenantId?: string; + runId?: string; providerSessionId?: string; leaseId?: string; leaseProvider?: string; diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index 663b54e1c56..42632d95f0d 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -567,7 +567,7 @@ async function listCloudArtifactsForRequest( 'artifacts requires an active cloud lease or --provider-session .', ); } - if (leaseScope.tenantId && leaseScope.leaseId && !providerSessionId) { + if (leaseScope.leaseId && !providerSessionId) { leaseRegistry.assertLeaseReadAdmission({ ...leaseScope, leaseId: leaseScope.leaseId }); } const providerSession = resolveProviderSession(leaseRegistry, leaseScope, providerSessionId); 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 62d4884b221..1615e1fcf8c 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -229,10 +229,21 @@ test('concurrent unread RPC bodies have a bounded proxy budget that releases aft ); }); + let refusedBodyCanceled = false; + const refusedBody = new ReadableStream({ + cancel() { + refusedBodyCanceled = true; + }, + }); const refused = await proxy.handle( - rpcRequest({ jsonrpc: '2.0', id: 33, method: 'agent-device.command' }), + new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { + method: 'POST', + body: refusedBody, + duplex: 'half', + } as RequestInit & { duplex: 'half' }), ); - expect(refused.status).toBe(500); + 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' } } }, }); @@ -246,6 +257,35 @@ test('concurrent unread RPC bodies have a bounded proxy budget that releases aft 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 0d9f898e941..b75b3818116 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -1,6 +1,7 @@ import { randomUUID } from 'node:crypto'; import http from 'node:http'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { timingSafeStringEqual } from '@agent-device/host-kit/transport'; import { buildDaemonHealthPayload, @@ -281,13 +282,18 @@ 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 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( @@ -949,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/rpc-body-budget.ts b/packages/proxy/src/rpc-body-budget.ts index 4e26166bd54..736d3a48328 100644 --- a/packages/proxy/src/rpc-body-budget.ts +++ b/packages/proxy/src/rpc-body-budget.ts @@ -1,9 +1,14 @@ -import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +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 bodies or aggregate bytes are in flight before authentication. + // Too many proxy RPC requests or aggregate body bytes are in flight. capacityExceeded: { reason: 'PROXY_RPC_BODY_CAPACITY_EXCEEDED' }, } as const satisfies ReasonTable<'proxy RPC ingress'>; @@ -22,7 +27,10 @@ export function createRpcBodyBudget(): { let totalBytes = 0; return { async read(request, maxBodyBytes) { - if (active >= MAX_IN_FLIGHT_RPC_BODIES) throw capacityError(); + if (active >= MAX_IN_FLIGHT_RPC_BODIES) { + void request.body?.cancel().catch(() => {}); + throw capacityError(); + } active += 1; let ownedBytes = 0; let released = false; @@ -37,7 +45,10 @@ export function createRpcBodyBudget(): { const reader = request.body.getReader(); const chunks: Uint8Array[] = []; for (;;) { - const { done, value } = await reader.read(); + 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(); 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 8225ea03c91..82e83c0c3d0 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 @@ -35,5 +35,31 @@ test('a remote test request cannot hide oversized sources across bundles', () => assertReplayScriptSourcesWithinLimit({ replayScriptSources: [source, { entry: 'extra.ad', files: { 'extra.ad': 'x' } }, source], }), - ).toThrow(expect.objectContaining({ code: 'INVALID_ARGS' })); + ).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, + }), + }), + ); }); diff --git a/packages/replay-port/src/daemon-port/script-source.ts b/packages/replay-port/src/daemon-port/script-source.ts index ff267ca3dab..7f73fa6da0c 100644 --- a/packages/replay-port/src/daemon-port/script-source.ts +++ b/packages/replay-port/src/daemon-port/script-source.ts @@ -1,6 +1,7 @@ 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; /** Admit client-supplied replay sources before any engine reads or splits their text. */ export function assertReplayScriptSourcesWithinLimit( @@ -39,7 +40,16 @@ function validateReplaySource(source: unknown, size: { text: number; paths: numb totalBytes: size.text, }); } - if (size.paths > 64 * 1024) invalidReplaySources(); + 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, + }, + ); + } } } diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 1a36dc2d588..737181ac8bc 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -551,7 +551,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. -- Web sessions require a local daemon. A remote daemon refuses web device commands with `remote_web_public_network_unenforced`; `close` remains available to release an existing remote web session. +- Managed web sessions require a local daemon. A remote daemon refuses requests that bind a web device with `remote_web_public_network_unenforced`, including requests for an existing web session that omit `--platform web`. `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 52ab0b1916e..e0f3bd8c51e 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -460,7 +460,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `RPC_BODY_CAPACITY_EXCEEDED` | Too many RPC bodies or aggregate bytes are in flight before request authentication. | +| `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 @@ -915,7 +915,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `PROXY_RPC_BODY_CAPACITY_EXCEEDED` | Too many proxy RPC bodies or aggregate bytes are in flight before authentication. | +| `PROXY_RPC_BODY_CAPACITY_EXCEEDED` | Too many proxy RPC requests or aggregate body bytes are in flight through dispatch. | ### Ref frames diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index dc2ebff2c98..0a71f2c0a50 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -100,8 +100,8 @@ destination on your machine. A recording is different: it downloads to the path `GET /artifacts/` using the same authentication. For trace and performance stop or report, a destination on the current request wins. Without one, -the client downloads to a unique file in its working directory using the artifact name as a stem. A path echoed by the -daemon from an earlier start request does not select a client destination. +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 diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index a0d5f492cae..2be64326234 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -31,7 +31,7 @@ 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 bound concurrent RPC bodies to 32 requests and 128 MiB of accumulated body bytes. When that request limit is reached, the daemon returns 503 with reason `RPC_BODY_CAPACITY_EXCEEDED`; the proxy returns a JSON-RPC failure with reason `PROXY_RPC_BODY_CAPACITY_EXCEEDED`. +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 From 71c6f3c52b9f020655b463b99196db6b3099a9a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 14:27:53 +0100 Subject: [PATCH 03/15] chore(gates): align security reasons and wire ledger --- packages/daemon/src/server/http/http-server.ts | 3 ++- packages/proxy/src/daemon-proxy.ts | 2 +- packages/proxy/src/rpc-body-budget.ts | 2 +- test/wire-compat/ledger.json | 6 +++--- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 0550199b654..c06a4549eba 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -99,7 +99,8 @@ 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 RPC bodies or aggregate bytes are in flight before request authentication. + // 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 }; diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index b75b3818116..173ee717a6d 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -1,7 +1,6 @@ import { randomUUID } from 'node:crypto'; import http from 'node:http'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; -import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { timingSafeStringEqual } from '@agent-device/host-kit/transport'; import { buildDaemonHealthPayload, @@ -282,6 +281,7 @@ async function authenticateCaller( ? { uploadHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } : null; } + const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); const result = await awaitWithSignal( Promise.resolve( options.authenticate( diff --git a/packages/proxy/src/rpc-body-budget.ts b/packages/proxy/src/rpc-body-budget.ts index 736d3a48328..bca4dc51e72 100644 --- a/packages/proxy/src/rpc-body-budget.ts +++ b/packages/proxy/src/rpc-body-budget.ts @@ -8,7 +8,7 @@ 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. + // 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'>; 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", From cb1d6bb076eb3169b185972b0226740d31c71088 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:08:31 +0100 Subject: [PATCH 04/15] fix(daemon): cancel auxiliary auth on disconnect --- .../server/http/http-authorization.test.ts | 28 ++++++++++++++++++- .../daemon/src/server/http/http-server.ts | 2 ++ 2 files changed, 29 insertions(+), 1 deletion(-) 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.ts b/packages/daemon/src/server/http/http-server.ts index c06a4549eba..09e51e0f0ff 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -229,6 +229,7 @@ export async function createDaemonHttpServer(options: { authHook, expectedToken: token, daemonRequest: request.daemonRequest, + signal: responseDisconnectSignal(request.req, request.res), }), }) ) { @@ -247,6 +248,7 @@ export async function createDaemonHttpServer(options: { authHook, expectedToken: token, leaseRegistry: options.leaseRegistry, + signal: responseDisconnectSignal(request.req, request.res), }), }) ) { From 5c1e8fb1687a122166ad824ab0ab8bdf385201e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 07:40:52 +0100 Subject: [PATCH 05/15] fix(replay): bound source bundle and file counts (#5277) * fix(replay): bound source bundle and file counts * fix: let empty replay source lists reach suite discovery * fix: preflight remote replay source counts on client * chore: format replay source preflight * fix(replay): enforce remote source limits in nested batch steps * fix(replay): type structured batch regression fixture * fix: preserve batch step error details --- packages/client/src/index.ts | 5 ++ .../command-surface/src/batch/projection.ts | 5 +- .../command-surface/src/cli-grammar/types.ts | 7 +- packages/command-surface/src/index.test.ts | 40 +++++++++- packages/command-surface/src/index.ts | 10 ++- .../command-surface/src/replay/index.test.ts | 52 ++++++++++++- packages/command-surface/src/replay/index.ts | 74 +++++++++++-------- .../__tests__/script-source-bundle.test.ts | 16 ++++ .../__tests__/script-source.test.ts | 61 ++++++++++++++- .../src/daemon-port/script-source.ts | 34 ++++++++- .../replay-port/src/script-source-bundle.ts | 20 +++++ website/docs/docs/replay-e2e.md | 1 + 12 files changed, 282 insertions(+), 43 deletions(-) diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index c996faae504..e422776be7f 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -202,6 +202,11 @@ export function createAgentDeviceClient( command, coordinateUnit === undefined ? options : { ...options, coordinateUnit }, host, + { + remoteSourceLimits: !daemonBaseUrlIsLocal( + options.daemonBaseUrl ?? config.daemonBaseUrl ?? host.env.AGENT_DEVICE_DAEMON_BASE_URL, + ), + }, ); return (await execute( request.command, diff --git a/packages/command-surface/src/batch/projection.ts b/packages/command-surface/src/batch/projection.ts index 0a34a2d12fc..aa38b359c2c 100644 --- a/packages/command-surface/src/batch/projection.ts +++ b/packages/command-surface/src/batch/projection.ts @@ -28,6 +28,7 @@ type PrepareDaemonCommandRequest = ( stepNumber: number, host: HostEnvironment, coordinateUnit: CommandInput['coordinateUnit'], + context: { remoteSourceLimits?: boolean } | undefined, ) => Promise; type PrepareBatchStep = ( @@ -39,11 +40,11 @@ type PrepareBatchStep = ( export function createBatchDaemonWriter( prepareDaemonCommandRequest: PrepareDaemonCommandRequest, ): AsyncDaemonWriter { - return async (input, host) => + return async (input, host, context) => request(PUBLIC_COMMANDS.batch, [], { ...input, batchSteps: await readBatchDaemonSteps(input.steps, (command, stepInput, stepNumber) => - prepareDaemonCommandRequest(command, stepInput, stepNumber, host, input.coordinateUnit), + prepareDaemonCommandRequest(command, stepInput, stepNumber, host, input.coordinateUnit, context), ), batchOnError: input.onError, batchMaxSteps: input.maxSteps, diff --git a/packages/command-surface/src/cli-grammar/types.ts b/packages/command-surface/src/cli-grammar/types.ts index a83175f7f71..0cfe6faf684 100644 --- a/packages/command-surface/src/cli-grammar/types.ts +++ b/packages/command-surface/src/cli-grammar/types.ts @@ -89,7 +89,11 @@ 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, + context?: { remoteSourceLimits?: boolean }, +) => DaemonCommandRequest; /** * A writer that has caller-side work to do before the request exists: reading the replay script @@ -100,6 +104,7 @@ export type DaemonWriter = (input: CommandInput) => DaemonCommandRequest; export type AsyncDaemonWriter = ( input: CommandInput, host: HostEnvironment, + context?: { remoteSourceLimits?: boolean }, ) => Promise; export type AnyDaemonWriter = DaemonWriter | AsyncDaemonWriter; diff --git a/packages/command-surface/src/index.test.ts b/packages/command-surface/src/index.test.ts index 96b4450545c..720490d42d1 100644 --- a/packages/command-surface/src/index.test.ts +++ b/packages/command-surface/src/index.test.ts @@ -1,6 +1,10 @@ -import { expect, expectTypeOf, test } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, expectTypeOf, test, vi } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; import { prepareDaemonCommandRequest, type DaemonCommandName } from './index.ts'; import type { BatchCommandName } from './batch/projection.ts'; +import type { CommandInput } from './cli-grammar/types.ts'; const host = { env: {}, cwd: '/workspace' }; @@ -30,3 +34,37 @@ test('projection rejects an invalid shared client option', async () => { test('every structured batch command has a daemon writer', () => { expectTypeOf().toExtend(); }); + +test('remote batch test step checks source count before reading files', async () => { + const root = mkdtempForTestSync('agent-device-batch-source-count-'); + for (let index = 0; index < 257; index += 1) { + fs.writeFileSync(path.join(root, `${index}.ad`), ''); + } + const read = vi.spyOn(fs, 'readFileSync'); + try { + await expect( + prepareDaemonCommandRequest( + 'batch', + { steps: [{ command: 'test', input: { paths: ['.'] } }] } as unknown as CommandInput, + { env: {}, cwd: root }, + { remoteSourceLimits: true }, + ), + ).rejects.toMatchObject({ + code: 'INVALID_ARGS', + message: expect.stringContaining('Batch step 1 test input is invalid:'), + details: { + limitCount: 256, + totalCount: 257, + hint: expect.stringContaining('Split the suite'), + }, + cause: expect.objectContaining({ + details: expect.objectContaining({ limitCount: 256, totalCount: 257 }), + }), + }); + expect( + read.mock.calls.filter(([file]) => typeof file === 'string' && file.startsWith(root)), + ).toEqual([]); + } finally { + read.mockRestore(); + } +}); diff --git a/packages/command-surface/src/index.ts b/packages/command-surface/src/index.ts index b9362b6a88b..4a95f542ca2 100644 --- a/packages/command-surface/src/index.ts +++ b/packages/command-surface/src/index.ts @@ -56,6 +56,7 @@ async function prepareBatchDaemonCommandRequest( stepNumber: number, host: HostEnvironment, coordinateUnit: CommandInput['coordinateUnit'], + context: { remoteSourceLimits?: boolean } | undefined, ): Promise { const writer = (daemonWriters as Readonly>)[command]; if (!writer) { @@ -75,13 +76,14 @@ async function prepareBatchDaemonCommandRequest( metadata, coordinateUnit === undefined ? stepInput : { ...stepInput, coordinateUnit }, host, + context, ); } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new AppError( 'INVALID_ARGS', `Batch step ${stepNumber} ${command} input is invalid: ${message}`, - undefined, + error instanceof AppError ? error.details : undefined, error, ); } @@ -96,6 +98,7 @@ export async function prepareDaemonCommandRequest( command: DaemonCommandName, input: CommandInput, host: HostEnvironment, + context?: { remoteSourceLimits?: boolean }, ): Promise { const writer = daemonWriters[command]; if (!writer) { @@ -103,7 +106,7 @@ export async function prepareDaemonCommandRequest( } refuseRetiredCommonInput(input as Record); const metadata = findCommandMetadata(command); - return await prepareRequestWithMetadataFlags(writer, metadata, input, host); + return await prepareRequestWithMetadataFlags(writer, metadata, input, host, context); } async function prepareRequestWithMetadataFlags( @@ -111,8 +114,9 @@ async function prepareRequestWithMetadataFlags( metadata: ReturnType, input: CommandInput, host: HostEnvironment, + context: { remoteSourceLimits?: boolean } | undefined, ): Promise { - const request = await writer(input, host); + const request = await writer(input, host, context); return { ...request, ...(metadata ? { metadataFlags: readMetadataCommandFlags(metadata, request.options) } : {}), diff --git a/packages/command-surface/src/replay/index.test.ts b/packages/command-surface/src/replay/index.test.ts index f21d7fb236f..3df120b96ab 100644 --- a/packages/command-surface/src/replay/index.test.ts +++ b/packages/command-surface/src/replay/index.test.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; -import { afterEach, describe, expect, test } from 'vitest'; +import { afterEach, describe, expect, test, vi } from 'vitest'; import type { CliFlags } from '@agent-device/contracts/command'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { REPLAY_ONLY_TEST_FLAG_REJECTIONS } from '@agent-device/replay-port/session-replay-test-policy'; @@ -159,6 +159,56 @@ describe('replay command interface', () => { } }); + test('remote suite count fails before loading bundles while local suite still runs', 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 read = vi.spyOn(fs, 'readFileSync'); + try { + await expect( + testDaemonWriter({ paths: ['.'] }, host, { remoteSourceLimits: true }), + ).rejects.toMatchObject({ + code: 'INVALID_ARGS', + details: { + limitCount: 256, + totalCount: 257, + hint: expect.stringContaining('Split the suite'), + }, + }); + expect( + read.mock.calls.filter(([file]) => typeof file === 'string' && file.startsWith(root)), + ).toEqual([]); + } finally { + read.mockRestore(); + } + const local = await testDaemonWriter({ paths: ['.'] }, host); + expect(local.options.replayScriptSources).toHaveLength(257); + }); + + test('remote replay refuses a Maestro include closure over the file limit before request', async () => { + const root = mkdtempForTestSync('agent-device-replay-file-count-'); + const includes: string[] = []; + for (let index = 0; index < 2_048; index += 1) { + const name = `${index}.yaml`; + fs.writeFileSync(path.join(root, name), '---\n- back\n'); + includes.push(`- runFlow: ${name}`); + } + fs.writeFileSync(path.join(root, 'flow.yaml'), `appId: demo\n---\n${includes.join('\n')}\n`); + + await expect( + replayDaemonWriter( + { path: './flow.yaml', backend: 'maestro' }, + { env: {}, cwd: root }, + { remoteSourceLimits: true }, + ), + ).rejects.toMatchObject({ + code: 'INVALID_ARGS', + details: { limitCount: 2_048, totalCount: 2_049 }, + }); + }); + 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..4f0419a8d5b 100644 --- a/packages/command-surface/src/replay/index.ts +++ b/packages/command-surface/src/replay/index.ts @@ -33,7 +33,11 @@ import { resolveReplayFormat, type ReplayFormat, } from '@agent-device/ad-script'; -import { loadReplayScriptSourceBundle } from '@agent-device/replay-port/script-source-bundle'; +import { + assertReplaySourceBundleCount, + assertReplaySourceFileCount, + loadReplayScriptSourceBundle, +} from '@agent-device/replay-port/script-source-bundle'; import { discoverReplaySourcePaths } from '@agent-device/replay-port/source-discovery'; const REPLAY_COMMAND_NAME = 'replay'; @@ -245,10 +249,23 @@ export const testCliReader: CliReader = (positionals, flags) => ({ testIme: flags.testIme, }); -export const replayDaemonWriter: AsyncDaemonWriter = async (input, host) => { +export const replayDaemonWriter: AsyncDaemonWriter = async (input, host, context) => { 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), + ), + }); + if (context?.remoteSourceLimits) { + assertReplaySourceFileCount(Object.keys(replayScriptSource.files).length); + } return request(REPLAY_COMMAND_NAME, [inputPath], { ...input, replayUpdate: input.update, @@ -258,16 +275,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, @@ -275,11 +283,33 @@ export const replayDaemonWriter: AsyncDaemonWriter = async (input, host) => { }); }; -export const testDaemonWriter: AsyncDaemonWriter = async (input, host) => { +export const testDaemonWriter: AsyncDaemonWriter = async (input, host, context) => { const inputs = input.paths ?? []; const replayBackend = readReplayBackend(input); const cwd = readReplayClientCwd(input, host.cwd); const replayShellEnv = collectReplayClientShellEnv(host.env); + const paths = discoverReplaySourcePaths({ inputs, cwd, replayBackend }); + if (context?.remoteSourceLimits) assertReplaySourceBundleCount(paths.length); + const sources = await Promise.all( + paths.map( + async (inputPath) => + await loadReplayScriptSourceBundle({ + inputPath, + cwd, + replayBackend, + env: readReplayScriptSourceEnv( + input, + replayShellEnv, + resolveReplayFormat(inputPath, replayBackend), + ), + }), + ), + ); + if (context?.remoteSourceLimits) { + assertReplaySourceFileCount( + sources.reduce((count, source) => count + Object.keys(source.files).length, 0), + ); + } return request(TEST_COMMAND_NAME, inputs, { ...stripReplayTestPresentationInput(input), replayUpdate: input.update, @@ -289,21 +319,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 +346,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/replay-port/src/__tests__/script-source-bundle.test.ts b/packages/replay-port/src/__tests__/script-source-bundle.test.ts index 0ab47f92742..d3c61b391f3 100644 --- a/packages/replay-port/src/__tests__/script-source-bundle.test.ts +++ b/packages/replay-port/src/__tests__/script-source-bundle.test.ts @@ -2,8 +2,10 @@ import fs from 'node:fs'; import path from 'node:path'; import { expect, test } from 'vitest'; import { + assertReplaySourceFileCount, loadReplayScriptSourceBundle, REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, + REPLAY_SCRIPT_SOURCE_MAX_FILES, } from '@agent-device/replay-port/script-source-bundle'; import { DAEMON_REQUEST_MAX_BYTES } from '@agent-device/contracts/daemon-http'; import { mkdtempForTestSync } from '../tmp-dir.fixtures.ts'; @@ -11,6 +13,20 @@ import { mkdtempForTestSync } from '../tmp-dir.fixtures.ts'; // #1802: the caller reads every script file a replay run needs and sends the text. These pin the // collection itself; that the daemon consumes only the result is pinned beside the replay handler. +test('client refuses the first file beyond the remote request ceiling', () => { + expect(() => assertReplaySourceFileCount(REPLAY_SCRIPT_SOURCE_MAX_FILES)).not.toThrow(); + expect(() => assertReplaySourceFileCount(REPLAY_SCRIPT_SOURCE_MAX_FILES + 1)).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ + limitCount: REPLAY_SCRIPT_SOURCE_MAX_FILES, + totalCount: REPLAY_SCRIPT_SOURCE_MAX_FILES + 1, + hint: expect.stringContaining('Split the suite'), + }), + }), + ); +}); + test('a native .ad bundle carries the entry script resolved against the caller cwd', async () => { const root = mkdtempForTestSync('agent-device-bundle-native-'); const script = 'open "Demo"\nclick "Save"\n'; 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 82e83c0c3d0..66776819497 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,14 +1,22 @@ import { expect, test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES as CLIENT_SOURCE_MAX_BYTES } from '../../script-source-bundle.ts'; +import { + REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES as CLIENT_SOURCE_MAX_BYTES, + REPLAY_SCRIPT_SOURCE_MAX_BUNDLES as CLIENT_SOURCE_MAX_BUNDLES, + REPLAY_SCRIPT_SOURCE_MAX_FILES as CLIENT_SOURCE_MAX_FILES, +} from '../../script-source-bundle.ts'; import { assertReplayScriptSourcesWithinLimit, readReplayScriptSourceFile, REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, + REPLAY_SCRIPT_SOURCE_MAX_BUNDLES, + REPLAY_SCRIPT_SOURCE_MAX_FILES, } from '../script-source.ts'; -test('client and daemon enforce the same replay source byte ceiling', () => { +test('client and daemon enforce the same replay source ceilings', () => { expect(REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES).toBe(CLIENT_SOURCE_MAX_BYTES); + expect(REPLAY_SCRIPT_SOURCE_MAX_BUNDLES).toBe(CLIENT_SOURCE_MAX_BUNDLES); + expect(REPLAY_SCRIPT_SOURCE_MAX_FILES).toBe(CLIENT_SOURCE_MAX_FILES); }); test('reading a file the bundle does not carry names the file and the entry', () => { @@ -63,3 +71,52 @@ test('an oversized replay source path reports the path byte limit', () => { }), ); }); + +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 7f73fa6da0c..8a08c796801 100644 --- a/packages/replay-port/src/daemon-port/script-source.ts +++ b/packages/replay-port/src/daemon-port/script-source.ts @@ -2,6 +2,8 @@ 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; +export const REPLAY_SCRIPT_SOURCE_MAX_BUNDLES = 256; +export const REPLAY_SCRIPT_SOURCE_MAX_FILES = 2_048; /** Admit client-supplied replay sources before any engine reads or splits their text. */ export function assertReplayScriptSourcesWithinLimit( @@ -10,7 +12,15 @@ export function assertReplayScriptSourcesWithinLimit( if (!flags) return; const sources = replaySourcesFromFlags(flags); if (!sources) return; - const size = { text: 0, paths: 0 }; + 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); } @@ -24,14 +34,30 @@ function replaySourcesFromFlags(flags: Record): unknown[] | und return sources; } -function validateReplaySource(source: unknown, size: { text: number; paths: number }): void { - if (!isRecord(source) || typeof source.entry !== 'string' || !isRecord(source.files)) { +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 (typeof text !== 'string') invalidReplaySources(); + 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) { diff --git a/packages/replay-port/src/script-source-bundle.ts b/packages/replay-port/src/script-source-bundle.ts index c20f58c3558..82aa9c50a6e 100644 --- a/packages/replay-port/src/script-source-bundle.ts +++ b/packages/replay-port/src/script-source-bundle.ts @@ -5,6 +5,26 @@ 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 const REPLAY_SCRIPT_SOURCE_MAX_BUNDLES = 256; +export const REPLAY_SCRIPT_SOURCE_MAX_FILES = 2_048; + +export function assertReplaySourceBundleCount(count: number): void { + if (count <= REPLAY_SCRIPT_SOURCE_MAX_BUNDLES) return; + throw new AppError('INVALID_ARGS', 'Replay request carries too many source bundles.', { + limitCount: REPLAY_SCRIPT_SOURCE_MAX_BUNDLES, + totalCount: count, + hint: 'Split the suite or shard it into smaller invocations.', + }); +} + +export function assertReplaySourceFileCount(count: number): void { + if (count <= REPLAY_SCRIPT_SOURCE_MAX_FILES) return; + throw new AppError('INVALID_ARGS', 'Replay request carries too many source files.', { + limitCount: REPLAY_SCRIPT_SOURCE_MAX_FILES, + totalCount: count, + hint: 'Split the suite or shard it into smaller invocations.', + }); +} export type ReplayScriptSourceRequest = { inputPath: string; 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: From 49b75ab31dc068cd44895fd8f1ba0974c40c027b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 08:58:08 +0100 Subject: [PATCH 06/15] fix(replay): leave source count admission to daemon --- packages/client/src/index.ts | 5 -- .../command-surface/src/batch/projection.ts | 5 +- .../command-surface/src/cli-grammar/types.ts | 2 - packages/command-surface/src/index.test.ts | 40 +--------------- packages/command-surface/src/index.ts | 8 +--- .../command-surface/src/replay/index.test.ts | 48 ++----------------- packages/command-surface/src/replay/index.ts | 19 ++------ .../__tests__/script-source-bundle.test.ts | 16 ------- .../__tests__/script-source.test.ts | 6 +-- .../replay-port/src/script-source-bundle.ts | 20 -------- 10 files changed, 13 insertions(+), 156 deletions(-) diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index e422776be7f..c996faae504 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -202,11 +202,6 @@ export function createAgentDeviceClient( command, coordinateUnit === undefined ? options : { ...options, coordinateUnit }, host, - { - remoteSourceLimits: !daemonBaseUrlIsLocal( - options.daemonBaseUrl ?? config.daemonBaseUrl ?? host.env.AGENT_DEVICE_DAEMON_BASE_URL, - ), - }, ); return (await execute( request.command, diff --git a/packages/command-surface/src/batch/projection.ts b/packages/command-surface/src/batch/projection.ts index aa38b359c2c..0a34a2d12fc 100644 --- a/packages/command-surface/src/batch/projection.ts +++ b/packages/command-surface/src/batch/projection.ts @@ -28,7 +28,6 @@ type PrepareDaemonCommandRequest = ( stepNumber: number, host: HostEnvironment, coordinateUnit: CommandInput['coordinateUnit'], - context: { remoteSourceLimits?: boolean } | undefined, ) => Promise; type PrepareBatchStep = ( @@ -40,11 +39,11 @@ type PrepareBatchStep = ( export function createBatchDaemonWriter( prepareDaemonCommandRequest: PrepareDaemonCommandRequest, ): AsyncDaemonWriter { - return async (input, host, context) => + return async (input, host) => request(PUBLIC_COMMANDS.batch, [], { ...input, batchSteps: await readBatchDaemonSteps(input.steps, (command, stepInput, stepNumber) => - prepareDaemonCommandRequest(command, stepInput, stepNumber, host, input.coordinateUnit, context), + prepareDaemonCommandRequest(command, stepInput, stepNumber, host, input.coordinateUnit), ), batchOnError: input.onError, batchMaxSteps: input.maxSteps, diff --git a/packages/command-surface/src/cli-grammar/types.ts b/packages/command-surface/src/cli-grammar/types.ts index 0cfe6faf684..78a3f352003 100644 --- a/packages/command-surface/src/cli-grammar/types.ts +++ b/packages/command-surface/src/cli-grammar/types.ts @@ -92,7 +92,6 @@ export type CliReader = (positionals: string[], flags: CliFlags) => CliInput; export type DaemonWriter = ( input: CommandInput, host?: HostEnvironment, - context?: { remoteSourceLimits?: boolean }, ) => DaemonCommandRequest; /** @@ -104,7 +103,6 @@ export type DaemonWriter = ( export type AsyncDaemonWriter = ( input: CommandInput, host: HostEnvironment, - context?: { remoteSourceLimits?: boolean }, ) => Promise; export type AnyDaemonWriter = DaemonWriter | AsyncDaemonWriter; diff --git a/packages/command-surface/src/index.test.ts b/packages/command-surface/src/index.test.ts index 720490d42d1..96b4450545c 100644 --- a/packages/command-surface/src/index.test.ts +++ b/packages/command-surface/src/index.test.ts @@ -1,10 +1,6 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { expect, expectTypeOf, test, vi } from 'vitest'; -import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { expect, expectTypeOf, test } from 'vitest'; import { prepareDaemonCommandRequest, type DaemonCommandName } from './index.ts'; import type { BatchCommandName } from './batch/projection.ts'; -import type { CommandInput } from './cli-grammar/types.ts'; const host = { env: {}, cwd: '/workspace' }; @@ -34,37 +30,3 @@ test('projection rejects an invalid shared client option', async () => { test('every structured batch command has a daemon writer', () => { expectTypeOf().toExtend(); }); - -test('remote batch test step checks source count before reading files', async () => { - const root = mkdtempForTestSync('agent-device-batch-source-count-'); - for (let index = 0; index < 257; index += 1) { - fs.writeFileSync(path.join(root, `${index}.ad`), ''); - } - const read = vi.spyOn(fs, 'readFileSync'); - try { - await expect( - prepareDaemonCommandRequest( - 'batch', - { steps: [{ command: 'test', input: { paths: ['.'] } }] } as unknown as CommandInput, - { env: {}, cwd: root }, - { remoteSourceLimits: true }, - ), - ).rejects.toMatchObject({ - code: 'INVALID_ARGS', - message: expect.stringContaining('Batch step 1 test input is invalid:'), - details: { - limitCount: 256, - totalCount: 257, - hint: expect.stringContaining('Split the suite'), - }, - cause: expect.objectContaining({ - details: expect.objectContaining({ limitCount: 256, totalCount: 257 }), - }), - }); - expect( - read.mock.calls.filter(([file]) => typeof file === 'string' && file.startsWith(root)), - ).toEqual([]); - } finally { - read.mockRestore(); - } -}); diff --git a/packages/command-surface/src/index.ts b/packages/command-surface/src/index.ts index 4a95f542ca2..20536318159 100644 --- a/packages/command-surface/src/index.ts +++ b/packages/command-surface/src/index.ts @@ -56,7 +56,6 @@ async function prepareBatchDaemonCommandRequest( stepNumber: number, host: HostEnvironment, coordinateUnit: CommandInput['coordinateUnit'], - context: { remoteSourceLimits?: boolean } | undefined, ): Promise { const writer = (daemonWriters as Readonly>)[command]; if (!writer) { @@ -76,7 +75,6 @@ async function prepareBatchDaemonCommandRequest( metadata, coordinateUnit === undefined ? stepInput : { ...stepInput, coordinateUnit }, host, - context, ); } catch (error) { const message = error instanceof Error ? error.message : String(error); @@ -98,7 +96,6 @@ export async function prepareDaemonCommandRequest( command: DaemonCommandName, input: CommandInput, host: HostEnvironment, - context?: { remoteSourceLimits?: boolean }, ): Promise { const writer = daemonWriters[command]; if (!writer) { @@ -106,7 +103,7 @@ export async function prepareDaemonCommandRequest( } refuseRetiredCommonInput(input as Record); const metadata = findCommandMetadata(command); - return await prepareRequestWithMetadataFlags(writer, metadata, input, host, context); + return await prepareRequestWithMetadataFlags(writer, metadata, input, host); } async function prepareRequestWithMetadataFlags( @@ -114,9 +111,8 @@ async function prepareRequestWithMetadataFlags( metadata: ReturnType, input: CommandInput, host: HostEnvironment, - context: { remoteSourceLimits?: boolean } | undefined, ): Promise { - const request = await writer(input, host, context); + const request = await writer(input, host); return { ...request, ...(metadata ? { metadataFlags: readMetadataCommandFlags(metadata, request.options) } : {}), diff --git a/packages/command-surface/src/replay/index.test.ts b/packages/command-surface/src/replay/index.test.ts index 3df120b96ab..5a6bf0ae338 100644 --- a/packages/command-surface/src/replay/index.test.ts +++ b/packages/command-surface/src/replay/index.test.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; -import { afterEach, describe, expect, test, vi } from 'vitest'; +import { afterEach, describe, expect, test } from 'vitest'; import type { CliFlags } from '@agent-device/contracts/command'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { REPLAY_ONLY_TEST_FLAG_REJECTIONS } from '@agent-device/replay-port/session-replay-test-policy'; @@ -159,54 +159,14 @@ describe('replay command interface', () => { } }); - test('remote suite count fails before loading bundles while local suite still runs', async () => { + 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 read = vi.spyOn(fs, 'readFileSync'); - try { - await expect( - testDaemonWriter({ paths: ['.'] }, host, { remoteSourceLimits: true }), - ).rejects.toMatchObject({ - code: 'INVALID_ARGS', - details: { - limitCount: 256, - totalCount: 257, - hint: expect.stringContaining('Split the suite'), - }, - }); - expect( - read.mock.calls.filter(([file]) => typeof file === 'string' && file.startsWith(root)), - ).toEqual([]); - } finally { - read.mockRestore(); - } - const local = await testDaemonWriter({ paths: ['.'] }, host); - expect(local.options.replayScriptSources).toHaveLength(257); - }); - - test('remote replay refuses a Maestro include closure over the file limit before request', async () => { - const root = mkdtempForTestSync('agent-device-replay-file-count-'); - const includes: string[] = []; - for (let index = 0; index < 2_048; index += 1) { - const name = `${index}.yaml`; - fs.writeFileSync(path.join(root, name), '---\n- back\n'); - includes.push(`- runFlow: ${name}`); - } - fs.writeFileSync(path.join(root, 'flow.yaml'), `appId: demo\n---\n${includes.join('\n')}\n`); - - await expect( - replayDaemonWriter( - { path: './flow.yaml', backend: 'maestro' }, - { env: {}, cwd: root }, - { remoteSourceLimits: true }, - ), - ).rejects.toMatchObject({ - code: 'INVALID_ARGS', - details: { limitCount: 2_048, totalCount: 2_049 }, - }); + 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 () => { diff --git a/packages/command-surface/src/replay/index.ts b/packages/command-surface/src/replay/index.ts index 4f0419a8d5b..8d3436bb7b2 100644 --- a/packages/command-surface/src/replay/index.ts +++ b/packages/command-surface/src/replay/index.ts @@ -33,11 +33,7 @@ import { resolveReplayFormat, type ReplayFormat, } from '@agent-device/ad-script'; -import { - assertReplaySourceBundleCount, - assertReplaySourceFileCount, - loadReplayScriptSourceBundle, -} from '@agent-device/replay-port/script-source-bundle'; +import { loadReplayScriptSourceBundle } from '@agent-device/replay-port/script-source-bundle'; import { discoverReplaySourcePaths } from '@agent-device/replay-port/source-discovery'; const REPLAY_COMMAND_NAME = 'replay'; @@ -249,7 +245,7 @@ export const testCliReader: CliReader = (positionals, flags) => ({ testIme: flags.testIme, }); -export const replayDaemonWriter: AsyncDaemonWriter = async (input, host, context) => { +export const replayDaemonWriter: AsyncDaemonWriter = async (input, host) => { const inputPath = requiredDaemonString(input.path, 'replay requires path'); const replayBackend = readReplayBackend(input); const replayShellEnv = collectReplayClientShellEnv(host.env); @@ -263,9 +259,6 @@ export const replayDaemonWriter: AsyncDaemonWriter = async (input, host, context resolveReplayFormat(inputPath, replayBackend), ), }); - if (context?.remoteSourceLimits) { - assertReplaySourceFileCount(Object.keys(replayScriptSource.files).length); - } return request(REPLAY_COMMAND_NAME, [inputPath], { ...input, replayUpdate: input.update, @@ -283,13 +276,12 @@ export const replayDaemonWriter: AsyncDaemonWriter = async (input, host, context }); }; -export const testDaemonWriter: AsyncDaemonWriter = async (input, host, context) => { +export const testDaemonWriter: AsyncDaemonWriter = async (input, host) => { const inputs = input.paths ?? []; const replayBackend = readReplayBackend(input); const cwd = readReplayClientCwd(input, host.cwd); const replayShellEnv = collectReplayClientShellEnv(host.env); const paths = discoverReplaySourcePaths({ inputs, cwd, replayBackend }); - if (context?.remoteSourceLimits) assertReplaySourceBundleCount(paths.length); const sources = await Promise.all( paths.map( async (inputPath) => @@ -305,11 +297,6 @@ export const testDaemonWriter: AsyncDaemonWriter = async (input, host, context) }), ), ); - if (context?.remoteSourceLimits) { - assertReplaySourceFileCount( - sources.reduce((count, source) => count + Object.keys(source.files).length, 0), - ); - } return request(TEST_COMMAND_NAME, inputs, { ...stripReplayTestPresentationInput(input), replayUpdate: input.update, diff --git a/packages/replay-port/src/__tests__/script-source-bundle.test.ts b/packages/replay-port/src/__tests__/script-source-bundle.test.ts index d3c61b391f3..0ab47f92742 100644 --- a/packages/replay-port/src/__tests__/script-source-bundle.test.ts +++ b/packages/replay-port/src/__tests__/script-source-bundle.test.ts @@ -2,10 +2,8 @@ import fs from 'node:fs'; import path from 'node:path'; import { expect, test } from 'vitest'; import { - assertReplaySourceFileCount, loadReplayScriptSourceBundle, REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, - REPLAY_SCRIPT_SOURCE_MAX_FILES, } from '@agent-device/replay-port/script-source-bundle'; import { DAEMON_REQUEST_MAX_BYTES } from '@agent-device/contracts/daemon-http'; import { mkdtempForTestSync } from '../tmp-dir.fixtures.ts'; @@ -13,20 +11,6 @@ import { mkdtempForTestSync } from '../tmp-dir.fixtures.ts'; // #1802: the caller reads every script file a replay run needs and sends the text. These pin the // collection itself; that the daemon consumes only the result is pinned beside the replay handler. -test('client refuses the first file beyond the remote request ceiling', () => { - expect(() => assertReplaySourceFileCount(REPLAY_SCRIPT_SOURCE_MAX_FILES)).not.toThrow(); - expect(() => assertReplaySourceFileCount(REPLAY_SCRIPT_SOURCE_MAX_FILES + 1)).toThrow( - expect.objectContaining({ - code: 'INVALID_ARGS', - details: expect.objectContaining({ - limitCount: REPLAY_SCRIPT_SOURCE_MAX_FILES, - totalCount: REPLAY_SCRIPT_SOURCE_MAX_FILES + 1, - hint: expect.stringContaining('Split the suite'), - }), - }), - ); -}); - test('a native .ad bundle carries the entry script resolved against the caller cwd', async () => { const root = mkdtempForTestSync('agent-device-bundle-native-'); const script = 'open "Demo"\nclick "Save"\n'; 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 66776819497..9871888ad63 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 @@ -2,8 +2,6 @@ import { expect, test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; import { REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES as CLIENT_SOURCE_MAX_BYTES, - REPLAY_SCRIPT_SOURCE_MAX_BUNDLES as CLIENT_SOURCE_MAX_BUNDLES, - REPLAY_SCRIPT_SOURCE_MAX_FILES as CLIENT_SOURCE_MAX_FILES, } from '../../script-source-bundle.ts'; import { assertReplayScriptSourcesWithinLimit, @@ -13,10 +11,8 @@ import { REPLAY_SCRIPT_SOURCE_MAX_FILES, } from '../script-source.ts'; -test('client and daemon enforce the same replay source ceilings', () => { +test('client and daemon enforce the same replay source byte ceiling', () => { expect(REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES).toBe(CLIENT_SOURCE_MAX_BYTES); - expect(REPLAY_SCRIPT_SOURCE_MAX_BUNDLES).toBe(CLIENT_SOURCE_MAX_BUNDLES); - expect(REPLAY_SCRIPT_SOURCE_MAX_FILES).toBe(CLIENT_SOURCE_MAX_FILES); }); test('reading a file the bundle does not carry names the file and the entry', () => { diff --git a/packages/replay-port/src/script-source-bundle.ts b/packages/replay-port/src/script-source-bundle.ts index 82aa9c50a6e..c20f58c3558 100644 --- a/packages/replay-port/src/script-source-bundle.ts +++ b/packages/replay-port/src/script-source-bundle.ts @@ -5,26 +5,6 @@ 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 const REPLAY_SCRIPT_SOURCE_MAX_BUNDLES = 256; -export const REPLAY_SCRIPT_SOURCE_MAX_FILES = 2_048; - -export function assertReplaySourceBundleCount(count: number): void { - if (count <= REPLAY_SCRIPT_SOURCE_MAX_BUNDLES) return; - throw new AppError('INVALID_ARGS', 'Replay request carries too many source bundles.', { - limitCount: REPLAY_SCRIPT_SOURCE_MAX_BUNDLES, - totalCount: count, - hint: 'Split the suite or shard it into smaller invocations.', - }); -} - -export function assertReplaySourceFileCount(count: number): void { - if (count <= REPLAY_SCRIPT_SOURCE_MAX_FILES) return; - throw new AppError('INVALID_ARGS', 'Replay request carries too many source files.', { - limitCount: REPLAY_SCRIPT_SOURCE_MAX_FILES, - totalCount: count, - hint: 'Split the suite or shard it into smaller invocations.', - }); -} export type ReplayScriptSourceRequest = { inputPath: string; From dc6a6d41d70a38fadda2216438ed9378f68064e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 09:15:50 +0100 Subject: [PATCH 07/15] fix(web): carry remote network policy into browser provider (#5265) * docs(security): design remote web network confinement * docs(security): phase remote web confinement * docs(security): correct Chromium proxy bypass * docs(security): require isolated confined browser sessions * docs(security): bind remote web confinement to session state * docs(security): cover DNS64 in remote web confinement design * fix(web): carry remote network policy into browser provider * fix(web): own confined browser refusal at launch * fix(web): refuse confined commands before provider cleanup * refactor(web): keep confinement admission before browser effects * docs(web): scope remote refusal to tenant ingress * fix(web): prove confined default provider composition --- packages/contracts/src/platform-providers.ts | 2 + .../request-platform-provider-context.test.ts | 16 ++++++++ .../request-platform-provider-context.ts | 1 + .../platform-web/src/__tests__/test-utils.ts | 1 + .../src/agent-browser-provider.test.ts | 24 +++++++++++ .../src/agent-browser-provider.ts | 25 ++++++----- .../platform-web/src/agent-browser-tool.ts | 18 +++++++- src/commands/schema/cli-help.ts | 2 +- src/platform-runtime-provider-scope.test.ts | 41 +++++++++++++++++++ src/platform-runtime/request-providers.ts | 1 + website/docs/docs/commands.md | 2 +- website/docs/docs/error-reasons.md | 1 + 12 files changed, 117 insertions(+), 17 deletions(-) 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/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/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..dd394df9a56 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[] = []; diff --git a/packages/platform-web/src/agent-browser-provider.ts b/packages/platform-web/src/agent-browser-provider.ts index ebad95a493a..7b47bf3d204 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) { @@ -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.ts b/packages/platform-web/src/agent-browser-tool.ts index defd57d917e..59113431d30 100644 --- a/packages/platform-web/src/agent-browser-tool.ts +++ b/packages/platform-web/src/agent-browser-tool.ts @@ -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/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 6273ca22468..dd3ae441c96 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -691,7 +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 remote tenant request to a web device is refused with reason remote_web_public_network_unenforced because browser subrequests cannot be confined to public destinations; close remains available for cleanup. +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/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/website/docs/docs/commands.md b/website/docs/docs/commands.md index 737181ac8bc..f822e2f9eb8 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -551,7 +551,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 require a local daemon. A remote daemon refuses requests that bind a web device with `remote_web_public_network_unenforced`, including requests for an existing web session that omit `--platform web`. `close` remains available to release an existing session. +- 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 e0f3bd8c51e..c25317eeb27 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -1072,6 +1072,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. | From e68c9dbbfe7a48600e842be06ca4be09aa4ce2d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 09:15:51 +0100 Subject: [PATCH 08/15] fix(web): classify public destinations for remote proxy (#5268) * fix(web): classify public network destinations before proxy connect * fix(web): admit only allocated IPv6 destination ranges * refactor(web): separate destination admission decisions --- .../src/public-network-addresses.test.ts | 154 +++++++++++++ .../src/public-network-addresses.ts | 206 ++++++++++++++++++ 2 files changed, 360 insertions(+) create mode 100644 packages/platform-web/src/public-network-addresses.test.ts create mode 100644 packages/platform-web/src/public-network-addresses.ts diff --git a/packages/platform-web/src/public-network-addresses.test.ts b/packages/platform-web/src/public-network-addresses.test.ts new file mode 100644 index 00000000000..c370794d2b2 --- /dev/null +++ b/packages/platform-web/src/public-network-addresses.test.ts @@ -0,0 +1,154 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { admitPublicDestinationAddress, type ResolvedAddress } from './public-network-addresses.ts'; + +const noInterfaces = {}; + +function literal(hostname: string) { + return admitPublicDestinationAddress(hostname, [], noInterfaces); +} + +test('admits public numeric IPv4 and IPv6 destinations after canonicalization', () => { + assert.deepEqual(literal('8.8.8.8'), { + ok: true, + hostname: '8.8.8.8', + address: '8.8.8.8', + family: 4, + }); + assert.deepEqual(literal('2001:4860:4860::8888'), { + ok: true, + hostname: '2001:4860:4860::8888', + address: '2001:4860:4860::8888', + family: 6, + }); + assert.deepEqual(literal('2606:4700:4700::1111'), { + ok: true, + hostname: '2606:4700:4700::1111', + address: '2606:4700:4700::1111', + family: 6, + }); + assert.deepEqual(literal('::ffff:8.8.8.8'), { + ok: true, + hostname: '::ffff:808:808', + address: '8.8.8.8', + family: 4, + }); +}); + +test('refuses reserved and host-local numeric destinations, including IPv4 URL variants', () => { + for (const hostname of [ + '0.0.0.0', + '10.1.2.3', + '100.100.100.200', + '127.0.0.1', + '127.1', + '0177.0.0.1', + '0x7f000001', + '2130706433', + '169.254.169.254', + '172.16.0.1', + '192.0.0.1', + '192.0.2.1', + '192.88.99.1', + '192.168.1.1', + '198.18.0.1', + '198.51.100.1', + '203.0.113.1', + '224.0.0.1', + '255.255.255.255', + '::', + '::1', + '::ffff:127.0.0.1', + '64:ff9b::1', + '2001::1', + '2001:db8::1', + '2002::1', + '2d00::1', + '3000::1', + '3ffe::1', + '3fff::1', + 'fc00::1', + 'fe80::1', + 'ff02::1', + ]) { + assert.deepEqual(literal(hostname), { ok: false, reason: 'non_public_address' }, hostname); + } +}); + +test('refuses malformed destinations and mixed or invalid DNS answer sets', () => { + for (const hostname of ['', 'user@host.test', 'host.test/path', 'host.test:80', 'fe80::1%en0']) { + assert.deepEqual(literal(hostname), { ok: false, reason: 'invalid_destination' }, hostname); + } + assert.deepEqual(admitPublicDestinationAddress('public.test', [], noInterfaces), { + ok: false, + reason: 'invalid_destination', + }); + const mixed: ResolvedAddress[] = [ + { address: '8.8.8.8', family: 4 }, + { address: '127.0.0.1', family: 4 }, + ]; + assert.deepEqual(admitPublicDestinationAddress('public.test', mixed, noInterfaces), { + ok: false, + reason: 'non_public_address', + }); + assert.deepEqual( + admitPublicDestinationAddress('public.test', [...mixed].reverse(), noInterfaces), + { + ok: false, + reason: 'non_public_address', + }, + ); + assert.deepEqual( + admitPublicDestinationAddress('public.test', [{ address: '8.8.8.8', family: 6 }], noInterfaces), + { ok: false, reason: 'invalid_destination' }, + ); + assert.deepEqual( + admitPublicDestinationAddress( + 'public.test', + [{ address: '::ffff:127.0.0.1', family: 6 }], + noInterfaces, + ), + { ok: false, reason: 'non_public_address' }, + ); + assert.deepEqual( + admitPublicDestinationAddress( + 'public.test', + [{ address: '::ffff:8.8.8.8', family: 6 }], + noInterfaces, + ), + { ok: true, hostname: 'public.test', address: '8.8.8.8', family: 4 }, + ); +}); + +test('refuses public addresses assigned to the daemon host, including mapped IPv4', () => { + const interfaces = { + en0: [{ address: '8.8.8.8' }, { address: '2001:4860:4860::8888' }], + }; + assert.deepEqual(admitPublicDestinationAddress('8.8.8.8', [], interfaces), { + ok: false, + reason: 'local_interface_address', + }); + assert.deepEqual(admitPublicDestinationAddress('::ffff:8.8.8.8', [], interfaces), { + ok: false, + reason: 'local_interface_address', + }); + assert.deepEqual(admitPublicDestinationAddress('2001:4860:4860::8888', [], interfaces), { + ok: false, + reason: 'local_interface_address', + }); + assert.deepEqual( + admitPublicDestinationAddress('public.test', [{ address: '1.1.1.1', family: 4 }], interfaces), + { ok: true, hostname: 'public.test', address: '1.1.1.1', family: 4 }, + ); + assert.deepEqual( + admitPublicDestinationAddress( + 'public.test', + [ + { address: '1.1.1.1', family: 4 }, + { address: '8.8.8.8', family: 4 }, + ], + interfaces, + ), + { ok: false, reason: 'local_interface_address' }, + ); +}); diff --git a/packages/platform-web/src/public-network-addresses.ts b/packages/platform-web/src/public-network-addresses.ts new file mode 100644 index 00000000000..f8ed8c5cacf --- /dev/null +++ b/packages/platform-web/src/public-network-addresses.ts @@ -0,0 +1,206 @@ +import { BlockList, isIP } from 'node:net'; + +export type ResolvedAddress = Readonly<{ address: string; family: 4 | 6 }>; + +type InterfaceAddresses = Readonly< + Record[] | undefined> +>; + +type AdmittedAddress = Readonly<{ + ok: true; + hostname: string; + address: string; + family: 4 | 6; +}>; + +type RefusedAddress = Readonly<{ + ok: false; + reason: 'invalid_destination' | 'non_public_address' | 'local_interface_address'; +}>; + +export type PublicDestinationAddress = AdmittedAddress | RefusedAddress; +type CandidateDecision = Readonly<{ ok: true; candidate: ResolvedAddress }> | RefusedAddress; + +const deniedIpv4 = new BlockList(); +for (const [subnet, prefix] of [ + ['0.0.0.0', 8], + ['10.0.0.0', 8], + ['100.64.0.0', 10], + ['127.0.0.0', 8], + ['169.254.0.0', 16], + ['172.16.0.0', 12], + ['192.0.0.0', 24], + ['192.0.2.0', 24], + ['192.88.99.0', 24], + ['192.168.0.0', 16], + ['198.18.0.0', 15], + ['198.51.100.0', 24], + ['203.0.113.0', 24], + ['224.0.0.0', 4], + ['240.0.0.0', 4], +] as const) { + deniedIpv4.addSubnet(subnet, prefix, 'ipv4'); +} + +// IANA IPv6 Global Unicast Address Space (2025-10-10): unlisted 2000::/3 ranges are reserved. +const allocatedIpv6 = new BlockList(); +for (const [subnet, prefix] of [ + ['2001:200::', 23], + ['2001:400::', 23], + ['2001:600::', 23], + ['2001:800::', 22], + ['2001:c00::', 23], + ['2001:e00::', 23], + ['2001:1200::', 23], + ['2001:1400::', 22], + ['2001:1800::', 23], + ['2001:1a00::', 23], + ['2001:1c00::', 22], + ['2001:2000::', 19], + ['2001:4000::', 23], + ['2001:4200::', 23], + ['2001:4400::', 23], + ['2001:4600::', 23], + ['2001:4800::', 23], + ['2001:4a00::', 23], + ['2001:4c00::', 23], + ['2001:5000::', 20], + ['2001:8000::', 19], + ['2001:a000::', 20], + ['2001:b000::', 20], + ['2003::', 18], + ['2400::', 12], + ['2410::', 12], + ['2600::', 12], + ['2610::', 23], + ['2620::', 23], + ['2630::', 12], + ['2800::', 12], + ['2a00::', 12], + ['2a10::', 12], + ['2c00::', 12], +] as const) { + allocatedIpv6.addSubnet(subnet, prefix, 'ipv6'); +} +const deniedIpv6 = new BlockList(); +deniedIpv6.addSubnet('2001:db8::', 32, 'ipv6'); + +// Classifies one connection's complete DNS answer set. The proxy must call it again for each new connection. +export function admitPublicDestinationAddress( + rawHostname: string, + answers: readonly ResolvedAddress[], + interfaces: InterfaceAddresses, +): PublicDestinationAddress { + const hostname = normalizeHostname(rawHostname); + if (hostname === undefined) return { ok: false, reason: 'invalid_destination' }; + + const literal = parseAddress(hostname); + const candidates = literal === undefined ? answers : [literal]; + if (candidates.length === 0) return { ok: false, reason: 'invalid_destination' }; + + const localAddresses = collectLocalAddresses(interfaces); + if (localAddresses === undefined) return { ok: false, reason: 'invalid_destination' }; + const decision = selectAdmittedCandidate(candidates, localAddresses); + if (!decision.ok) return decision; + return { ok: true, hostname, ...decision.candidate }; +} + +function collectLocalAddresses(interfaces: InterfaceAddresses): ReadonlySet | undefined { + const localAddresses = new Set(); + for (const group of Object.values(interfaces)) { + for (const entry of group ?? []) { + const local = parseAddress(entry.address.split('%', 1)[0] ?? ''); + if (local === undefined) return undefined; + localAddresses.add(`${local.family}:${local.address}`); + } + } + return localAddresses; +} + +function selectAdmittedCandidate( + candidates: readonly ResolvedAddress[], + localAddresses: ReadonlySet, +): CandidateDecision { + let selected: ResolvedAddress | undefined; + for (const candidate of candidates) { + const decision = classifyCandidate(candidate, localAddresses); + if (!decision.ok) return decision; + selected ??= decision.candidate; + } + return selected === undefined + ? { ok: false, reason: 'invalid_destination' } + : { ok: true, candidate: selected }; +} + +function classifyCandidate( + candidate: ResolvedAddress, + localAddresses: ReadonlySet, +): CandidateDecision { + const parsed = parseAddress(candidate.address); + const mappedIpv4 = + candidate.family === 6 && parsed?.family === 4 && isIP(candidate.address) === 6; + if (parsed === undefined || (parsed.family !== candidate.family && !mappedIpv4)) { + return { ok: false, reason: 'invalid_destination' }; + } + if (!isGlobalAddress(parsed)) return { ok: false, reason: 'non_public_address' }; + if (localAddresses.has(`${parsed.family}:${parsed.address}`)) { + return { ok: false, reason: 'local_interface_address' }; + } + return { ok: true, candidate: parsed }; +} + +function normalizeHostname(raw: string): string | undefined { + if (!raw || /[\s@/?#%\\]/u.test(raw)) return undefined; + const ipv6 = isIP(raw) === 6; + if (!ipv6 && raw.includes(':') && !(raw.startsWith('[') && raw.endsWith(']'))) { + return undefined; + } + const authority = ipv6 ? `[${raw}]` : raw; + try { + const url = new URL(`http://${authority}/`); + if ( + url.username || + url.password || + url.port || + url.pathname !== '/' || + url.search || + url.hash + ) { + return undefined; + } + return url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname; + } catch { + return undefined; + } +} + +function parseAddress(address: string): ResolvedAddress | undefined { + if (address.includes('%')) return undefined; + const family = isIP(address); + if (family === 4) return { address, family }; + if (family !== 6) return undefined; + let normalized: string; + try { + normalized = new URL(`http://[${address}]/`).hostname.slice(1, -1); + } catch { + return undefined; + } + const mapped = /^::ffff:([0-9a-f]+):([0-9a-f]+)$/u.exec(normalized); + if (mapped) { + const high = Number.parseInt(mapped[1] ?? '', 16); + const low = Number.parseInt(mapped[2] ?? '', 16); + if (high > 0xffff || low > 0xffff) return undefined; + return { + address: `${high >>> 8}.${high & 255}.${low >>> 8}.${low & 255}`, + family: 4, + }; + } + return { address: normalized, family: 6 }; +} + +function isGlobalAddress(candidate: ResolvedAddress): boolean { + if (candidate.family === 4) return !deniedIpv4.check(candidate.address, 'ipv4'); + return ( + allocatedIpv6.check(candidate.address, 'ipv6') && !deniedIpv6.check(candidate.address, 'ipv6') + ); +} From 8dccdbbbe1694191cd6c28e876062002d8eff837 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 09:30:15 +0100 Subject: [PATCH 09/15] fix(replay): remove stale count imports and format types --- packages/command-surface/src/cli-grammar/types.ts | 5 +---- .../src/daemon-port/__tests__/script-source.test.ts | 6 +----- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/packages/command-surface/src/cli-grammar/types.ts b/packages/command-surface/src/cli-grammar/types.ts index 78a3f352003..6c2645879af 100644 --- a/packages/command-surface/src/cli-grammar/types.ts +++ b/packages/command-surface/src/cli-grammar/types.ts @@ -89,10 +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, - host?: HostEnvironment, -) => 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/replay-port/src/daemon-port/__tests__/script-source.test.ts b/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts index 9871888ad63..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,14 +1,10 @@ import { expect, test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { - REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES as CLIENT_SOURCE_MAX_BYTES, -} from '../../script-source-bundle.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, - REPLAY_SCRIPT_SOURCE_MAX_BUNDLES, - REPLAY_SCRIPT_SOURCE_MAX_FILES, } from '../script-source.ts'; test('client and daemon enforce the same replay source byte ceiling', () => { From ed02ba5a908450dbc3e99f29c273102eea73154a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 09:31:45 +0100 Subject: [PATCH 10/15] refactor(replay): keep daemon count limits private --- packages/replay-port/src/daemon-port/script-source.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/replay-port/src/daemon-port/script-source.ts b/packages/replay-port/src/daemon-port/script-source.ts index 8a08c796801..a91df0caa9f 100644 --- a/packages/replay-port/src/daemon-port/script-source.ts +++ b/packages/replay-port/src/daemon-port/script-source.ts @@ -2,8 +2,8 @@ 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; -export const REPLAY_SCRIPT_SOURCE_MAX_BUNDLES = 256; -export const REPLAY_SCRIPT_SOURCE_MAX_FILES = 2_048; +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( From ed2ccd2d535a155f4f64e1fb3550a7edd93fd1e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 10:05:59 +0100 Subject: [PATCH 11/15] fix(providers): bound credential endpoints and responses (#5244) * fix(providers): bound credential endpoints and responses * fix(providers): require origin fences for authenticated downloads * fix(providers): bound Limrun control responses * fix(providers): satisfy response boundary gates * fix(providers): share response failure vocabulary * fix(providers): cancel stalled Limrun response reads * docs: regenerate provider response reasons * chore(gates): refresh contracts export snapshot * test(providers): narrow stalled response observation * fix(providers): preserve observed Limrun rejection status * test(providers): await client-observed rejection body * test(providers): observe retry conflict body seam * fix(providers): keep response reason in existing closure * fix: preserve anonymous Limrun release redirects and BOM decoding * fix(providers): close credential and response boundaries * fix(contracts): keep response reasons in remote facade * docs(contracts): summarize provider response reason * fix(providers): narrow response bounds to buffered bodies * fix(revyl): report oversized responses with shared reason --- packages/contracts/src/facades/remote.ts | 9 ++++ .../provider-revyl/src/revyl-client.test.ts | 21 ++++++++ packages/provider-revyl/src/revyl-client.ts | 29 ++++++++++- .../src/webdriver-transport.test.ts | 22 +++++++++ .../src/webdriver-transport.ts | 21 +++++++- .../src/webdriver-utils.test.ts | 5 ++ .../provider-webdriver/src/webdriver-utils.ts | 31 +++++++++++- .../interactors/limrun-http-response.test.ts | 33 +++++++++++++ src/core/interactors/limrun-http-response.ts | 48 +++++++++++++++++++ src/core/interactors/limrun-ios-files.ts | 7 ++- .../interactors/limrun-ios-runner-products.ts | 3 +- .../interactors/limrun-ios-runner.test.ts | 25 +++++----- src/core/interactors/limrun-ios-runner.ts | 6 ++- website/docs/docs/error-reasons.md | 6 +++ 14 files changed, 245 insertions(+), 21 deletions(-) create mode 100644 src/core/interactors/limrun-http-response.test.ts create mode 100644 src/core/interactors/limrun-http-response.ts diff --git a/packages/contracts/src/facades/remote.ts b/packages/contracts/src/facades/remote.ts index 820d3c79b67..abf4b6a367c 100644 --- a/packages/contracts/src/facades/remote.ts +++ b/packages/contracts/src/facades/remote.ts @@ -1,3 +1,5 @@ +import type { ReasonTable } from '@agent-device/kernel/errors'; + export type { CompanionTunnelScope, MetroBridgeScope } from '../companion-tunnel-scope.ts'; export type { MetroBridgeResult, @@ -22,6 +24,13 @@ export { PROVIDER_PROFILE_FIELD_FLAG_ALIASES, PROVIDER_PROFILE_FIELD_FLAGS, } from '../remote-config-fields.ts'; + +/** Why a provider response was rejected before its body was accepted. */ +export const PROVIDER_RESPONSE_REASONS = { + // A provider answered with more bytes than the response budget allows. + tooLarge: { reason: 'provider_response_too_large' }, +} as const satisfies ReasonTable<'provider response'>; + export type { CloudProviderProfileFields, DaemonRpcMode, diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index 098e6076e4c..ef3d0698b9d 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -22,6 +22,27 @@ test('uses the public Revyl backend when no URL is configured', () => { assert.equal(client.backendUrl, REVYL_DEFAULT_BACKEND_URL); }); +test('rejects an oversized provider answer before accepting its body', async () => { + const client = clientResponding( + () => + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)); + }, + }), + { status: 200, headers: { 'content-type': 'application/json' } }, + ), + ); + await assert.rejects( + client.verifyCredentials(), + (error: unknown) => + error instanceof AppError && + error.details?.reason === 'provider_response_too_large' && + error.details?.limitBytes === 32 * 1024 * 1024, + ); +}); + test('keeps plain HTTP only on loopback', () => { assert.equal(resolveRevylBackendUrl('http://127.0.0.1:8787'), 'http://127.0.0.1:8787'); assert.equal(resolveRevylBackendUrl('http://localhost:8787'), 'http://localhost:8787'); diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index 11caa8523a9..a9261272b7e 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -6,6 +6,7 @@ import { } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; +import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/remote'; import fs from 'node:fs'; import { Readable } from 'node:stream'; import { setTimeout as sleep } from 'node:timers/promises'; @@ -30,6 +31,8 @@ export const REVYL_DEFAULT_BACKEND_URL = 'https://backend.revyl.ai'; const REVYL_ATTRIBUTION = 'agent-device'; const DEFAULT_REQUEST_TIMEOUT_MS = 30_000; +const MAX_REVYL_RESPONSE_BYTES = 32 * 1024 * 1024; + /** How long `start_device` may take to answer: Revyl assigns a worker and boots the device in it. */ export const REVYL_START_DEVICE_TIMEOUT_MS = 120_000; const RETRY_DELAYS_MS = [500, 1_500] as const; @@ -379,9 +382,10 @@ async function sendOnce( return Object.freeze({ status: response.status, contentType: response.headers.get('content-type') ?? undefined, - body: new Uint8Array(await response.arrayBuffer()), + body: await readRevylResponseBody(response), }); } catch (error) { + if (error instanceof AppError) return error; if (request.signal?.aborted) return requestCanceled(request, error); if (timeout.aborted) return requestTimedOut(request, error); return new AppError( @@ -393,6 +397,29 @@ async function sendOnce( } } +async function readRevylResponseBody(response: Response): Promise { + if (!response.body) return new Uint8Array(); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) return new Uint8Array(Buffer.concat(chunks, bytes)); + bytes += value.byteLength; + if (bytes > MAX_REVYL_RESPONSE_BYTES) { + throw new AppError('COMMAND_FAILED', 'Revyl response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, + limitBytes: MAX_REVYL_RESPONSE_BYTES, + }); + } + chunks.push(value); + } + } finally { + void reader.cancel().catch(() => {}); + } +} + /** * Only a request that never reached Revyl, or a status Revyl marks transient, is replayed. A * cancellation is the caller's own answer, and a timeout has already spent the request's budget, so diff --git a/packages/provider-webdriver/src/webdriver-transport.test.ts b/packages/provider-webdriver/src/webdriver-transport.test.ts index 61bb44bf4c6..8016db15b7b 100644 --- a/packages/provider-webdriver/src/webdriver-transport.test.ts +++ b/packages/provider-webdriver/src/webdriver-transport.test.ts @@ -26,6 +26,28 @@ afterEach(() => { globalThis.fetch = realFetch; }); +test('WebDriver stops reading a response after its byte limit', async () => { + const transport = new WebDriverTransport({ + clientVersion: '0.0.0-test', + endpoint: 'https://cloud-webdriver.test/wd/hub/', + }); + globalThis.fetch = async () => + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)); + }, + }), + ); + await assert.rejects( + transport.requestValue('GET', '/session/x/source'), + (error: unknown) => + error instanceof AppError && + error.details?.reason === 'provider_response_too_large' && + error.details?.dispatched === 'unknown', + ); +}); + // The transport's own deadline must surface as a machine-readable reason, not // as fetch's `AbortError`/`TimeoutError` DOMException name: the session manager // keys its "the provider may still be creating a billed session" branch on diff --git a/packages/provider-webdriver/src/webdriver-transport.ts b/packages/provider-webdriver/src/webdriver-transport.ts index 717aa9e3552..6ec7dd25e42 100644 --- a/packages/provider-webdriver/src/webdriver-transport.ts +++ b/packages/provider-webdriver/src/webdriver-transport.ts @@ -1,7 +1,12 @@ import { setTimeout as sleep } from 'node:timers/promises'; import { AppError, type DispatchDisclosure, type ReasonTable } from '@agent-device/kernel/errors'; import { agentDeviceRequestHeaders } from './request-headers.ts'; -import { basicAuthHeader, trimLeadingSlash, withTrailingSlash } from './webdriver-utils.ts'; +import { + basicAuthHeader, + readProviderTextBody, + trimLeadingSlash, + withTrailingSlash, +} from './webdriver-utils.ts'; /** Why a WebDriver request failed at the transport. */ const WEBDRIVER_TRANSPORT_REASONS = { @@ -261,8 +266,20 @@ export class WebDriverTransport { throw classifyWebDriverFetchFailure(error, failure, 'request'); } try { - return { ok: response.ok, status: response.status, text: await response.text() }; + return { + ok: response.ok, + status: response.status, + text: await readProviderTextBody(response), + }; } catch (error) { + if (error instanceof AppError) { + throw new AppError( + error.code, + error.message, + { ...error.details, ...dispatchDisclosure('unknown') }, + error, + ); + } throw classifyWebDriverFetchFailure(error, failure, 'response'); } } diff --git a/packages/provider-webdriver/src/webdriver-utils.test.ts b/packages/provider-webdriver/src/webdriver-utils.test.ts index d2b62f826ff..48358440e78 100644 --- a/packages/provider-webdriver/src/webdriver-utils.test.ts +++ b/packages/provider-webdriver/src/webdriver-utils.test.ts @@ -63,6 +63,11 @@ test('the hub upload helper posts with credentials and returns the vendor refere assert.equal(await postHubAppUpload(form, hub), 'hub://APP1'); }); +test('the hub upload helper parses a response with a UTF-8 byte-order mark', async () => { + globalThis.fetch = async () => new Response('\ufeff{"ref":"hub://APP1"}'); + assert.equal(await postHubAppUpload(new FormData(), hub), 'hub://APP1'); +}); + test('the hub upload helper fails typed with the status on an error page or a missing reference', async () => { for (const response of [ new Response('502 Bad Gateway', { status: 502 }), diff --git a/packages/provider-webdriver/src/webdriver-utils.ts b/packages/provider-webdriver/src/webdriver-utils.ts index 07057f3010e..d584b958b9d 100644 --- a/packages/provider-webdriver/src/webdriver-utils.ts +++ b/packages/provider-webdriver/src/webdriver-utils.ts @@ -9,6 +9,7 @@ import type { } from '@agent-device/contracts/device'; import { PROVIDER_DEVICE_ORIENTATIONS, + PROVIDER_RESPONSE_REASONS, type ProviderDeviceOrientation, } from '@agent-device/contracts/remote'; import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors'; @@ -74,6 +75,32 @@ export function withTrailingSlash(url: URL): URL { type HubCredentials = { username: string; accessKey: string }; +const MAX_PROVIDER_RESPONSE_BYTES = 32 * 1024 * 1024; + +/** Bound provider answers even when a peer omits or lies about Content-Length. */ +export async function readProviderTextBody(response: Response): Promise { + if (!response.body) return ''; + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) return new TextDecoder().decode(Buffer.concat(chunks, bytes)); + bytes += value.byteLength; + if (bytes > MAX_PROVIDER_RESPONSE_BYTES) { + throw new AppError('COMMAND_FAILED', 'Provider response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, + limitBytes: MAX_PROVIDER_RESPONSE_BYTES, + }); + } + chunks.push(value); + } + } finally { + void reader.cancel().catch(() => {}); + } +} + /** * A multipart form carrying the local app file under the hub's field name. Upload APIs take one * regular file, so anything else (an extracted `.app` directory, a missing path) is refused here, @@ -142,6 +169,7 @@ export async function postHubAppUpload( json = await readProviderJsonBody(response); } catch (error) { if (signal?.aborted) throw error; + if (error instanceof AppError) throw error; const timedOut = timeoutSignal.aborted; throw new AppError( 'COMMAND_FAILED', @@ -325,6 +353,7 @@ export async function fetchProviderSessionDetails( }); json = await readProviderJsonBody(response); } catch (error) { + if (error instanceof AppError) throw error; throw new AppError( 'COMMAND_FAILED', `${options.service} session details lookup failed.`, @@ -347,7 +376,7 @@ export async function fetchProviderSessionDetails( /** A provider response body parsed as JSON, or `undefined` when it is empty or not JSON (a gateway error page). */ async function readProviderJsonBody(response: Response): Promise { - const text = await response.text(); + const text = await readProviderTextBody(response); if (text.length === 0) return undefined; try { return JSON.parse(text) as unknown; diff --git a/src/core/interactors/limrun-http-response.test.ts b/src/core/interactors/limrun-http-response.test.ts new file mode 100644 index 00000000000..403aa59704c --- /dev/null +++ b/src/core/interactors/limrun-http-response.test.ts @@ -0,0 +1,33 @@ +import { expect, test } from 'vitest'; +import { readLimrunControlJson } from './limrun-http-response.ts'; + +test('stops an oversized Limrun control response before accepting its body', async () => { + const response = new Response('{}', { + headers: { 'content-length': String(32 * 1024 * 1024 + 1) }, + }); + + await expect(readLimrunControlJson(response)).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'provider_response_too_large', limitBytes: 32 * 1024 * 1024 }, + }); +}); + +test('stops a streaming Limrun control response without a declared length', async () => { + const response = new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)); + }, + }), + ); + + await expect(readLimrunControlJson(response)).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'provider_response_too_large', limitBytes: 32 * 1024 * 1024 }, + }); +}); + +test('parses a bounded Limrun control response with a UTF-8 byte-order mark', async () => { + const response = new Response('\ufeff{"synced":true}'); + await expect(readLimrunControlJson(response)).resolves.toEqual({ synced: true }); +}); diff --git a/src/core/interactors/limrun-http-response.ts b/src/core/interactors/limrun-http-response.ts new file mode 100644 index 00000000000..0e2a1940ed3 --- /dev/null +++ b/src/core/interactors/limrun-http-response.ts @@ -0,0 +1,48 @@ +import { AppError } from '@agent-device/kernel/errors'; +import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/remote'; + +const MAX_LIMRUN_CONTROL_RESPONSE_BYTES = 32 * 1024 * 1024; + +export async function readLimrunControlText( + response: Response, + signal?: AbortSignal, +): Promise { + signal?.throwIfAborted(); + const declaredBytes = Number(response.headers.get('content-length')); + if (Number.isFinite(declaredBytes) && declaredBytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) { + await response.body?.cancel().catch(() => {}); + throw responseTooLarge(); + } + if (!response.body) return ''; + const reader = response.body.getReader(); + const cancel = () => void reader.cancel(signal?.reason).catch(() => {}); + signal?.addEventListener('abort', cancel, { once: true }); + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + while (true) { + const { done, value } = await reader.read(); + signal?.throwIfAborted(); + if (done) return new TextDecoder().decode(Buffer.concat(chunks, bytes)); + bytes += value.byteLength; + if (bytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) { + throw responseTooLarge(); + } + chunks.push(value); + } + } finally { + signal?.removeEventListener('abort', cancel); + void reader.cancel().catch(() => {}); + } +} + +function responseTooLarge(): AppError { + return new AppError('COMMAND_FAILED', 'Limrun response exceeds the size limit.', { + reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason, + limitBytes: MAX_LIMRUN_CONTROL_RESPONSE_BYTES, + }); +} + +export async function readLimrunControlJson(response: Response): Promise { + return JSON.parse(await readLimrunControlText(response)) as T; +} diff --git a/src/core/interactors/limrun-ios-files.ts b/src/core/interactors/limrun-ios-files.ts index 9ad197b71d6..7d96f7184d0 100644 --- a/src/core/interactors/limrun-ios-files.ts +++ b/src/core/interactors/limrun-ios-files.ts @@ -9,6 +9,7 @@ import { import type { LimrunRuntimeDependencies } from '@agent-device/provider-limrun'; import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import { downloadLimrunFile } from '../limrun-download-file.ts'; +import { readLimrunControlJson } from './limrun-http-response.ts'; type Session = Parameters[0]; type Files = AppleToolProvider['simulatorFiles']; @@ -95,7 +96,9 @@ export function createLimrunSimulatorFiles( const list = () => operation(container, async (signal) => { const response = await request('GET', urlFor('files/list', '', container), signal); - const result = (await response.json()) as { entries: Array<{ name: string }> }; + const result = await readLimrunControlJson<{ entries: Array<{ name: string }> }>( + response, + ); return result.entries.map((entry) => entry.name); }); try { @@ -141,7 +144,7 @@ export function createLimrunSimulatorFiles( signal, await fs.readFile(localPath, { signal }), ); - return (await response.json()) as { path: string }; + return await readLimrunControlJson<{ path: string }>(response); }).catch(async (error: unknown) => { await remove().catch(() => {}); throw error; diff --git a/src/core/interactors/limrun-ios-runner-products.ts b/src/core/interactors/limrun-ios-runner-products.ts index c4cc114849f..ff305f0e81d 100644 --- a/src/core/interactors/limrun-ios-runner-products.ts +++ b/src/core/interactors/limrun-ios-runner-products.ts @@ -1,4 +1,5 @@ import { limrunRunnerError } from './limrun-ios-runner-errors.ts'; +import { readLimrunControlJson } from './limrun-http-response.ts'; import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { runnerListenerEnv, @@ -305,7 +306,7 @@ export async function uploadLimrunRunnerProducts( }, ); } - return (await response.json()) as { ok?: boolean; needFull?: string[] }; + return await readLimrunControlJson<{ ok?: boolean; needFull?: string[] }>(response); } finally { stream.destroy(); await compression; diff --git a/src/core/interactors/limrun-ios-runner.test.ts b/src/core/interactors/limrun-ios-runner.test.ts index d39348077a9..50c37871fa0 100644 --- a/src/core/interactors/limrun-ios-runner.test.ts +++ b/src/core/interactors/limrun-ios-runner.test.ts @@ -136,16 +136,16 @@ test('an admitted XCTest stream survives its launch deadline', async () => { test('a stalled rejection body respects the launch deadline and does not claim the occupied slot', async () => { const timeout = new AbortController(); - let markReadStarted!: () => void; - const readStarted = new Promise((resolve) => { - markReadStarted = resolve; + let markBodyRead!: () => void; + const bodyRead = new Promise((resolve) => { + markBodyRead = resolve; }); - const readText = Response.prototype.text; + const getBody = Object.getOwnPropertyDescriptor(Response.prototype, 'body')!.get!; const responseBody = vi - .spyOn(Response.prototype, 'text') + .spyOn(Response.prototype, 'body', 'get') .mockImplementation(function (this: Response) { - if (this.status === 409) markReadStarted(); - return readText.call(this); + if (this.status === 409) markBodyRead(); + return getBody.call(this); }); const realTimeout = AbortSignal.timeout.bind(AbortSignal); const timer = vi @@ -163,7 +163,7 @@ test('a stalled rejection body respects the launch deadline and does not claim t { healthCheck: false }, ); const failed = expect(prepare()).rejects.toMatchObject({ details: { status: 409 } }); - await readStarted; + await bodyRead; timeout.abort(new DOMException('Admission expired', 'TimeoutError')); await failed; timer.mockRestore(); @@ -240,13 +240,12 @@ test.each([ const conflict = new Promise((resolve) => { conflictRead = resolve; }); - const originalText = Response.prototype.text; + const getBody = Object.getOwnPropertyDescriptor(Response.prototype, 'body')!.get!; const responseBody = vi - .spyOn(Response.prototype, 'text') - .mockImplementation(async function (this: Response) { - const body = await originalText.call(this); + .spyOn(Response.prototype, 'body', 'get') + .mockImplementation(function (this: Response) { if (this.status === 409) conflictRead(); - return body; + return getBody.call(this); }); vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); try { diff --git a/src/core/interactors/limrun-ios-runner.ts b/src/core/interactors/limrun-ios-runner.ts index d906dc8124f..3094bafeff3 100644 --- a/src/core/interactors/limrun-ios-runner.ts +++ b/src/core/interactors/limrun-ios-runner.ts @@ -21,6 +21,7 @@ import { writeLimrunRunnerConfiguration, type LimrunRunnerProducts, } from './limrun-ios-runner-products.ts'; +import { readLimrunControlText } from './limrun-http-response.ts'; type LimrunIosRunner = Awaited>; type Session = Parameters[0]; @@ -187,7 +188,10 @@ export async function createLimrunIosRunner( `Limrun XCTest launch failed (${result.status})`, { status: result.status, - response: await awaitWithSignal(result.text(), launchSignal).catch(() => undefined), + response: await awaitWithSignal( + readLimrunControlText(result, launchSignal), + launchSignal, + ).catch(() => undefined), }, ); if (result.status === 409) lastConflict = failure; diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index c25317eeb27..de5c147e0e8 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -911,6 +911,12 @@ These reasons can come from more than one command. | `exit-timeout` | SIGKILL was sent and nothing proved the process exited within the budget it was given. | | `identity-unverified` | Nothing confirmed the pid names the recorded process, so signalling it was refused. | +### Provider response + +| Reason | Meaning | +| --- | --- | +| `provider_response_too_large` | A provider answered with more bytes than the response budget allows. | + ### Proxy RPC ingress | Reason | Meaning | From f5ccf09ea6be229a72aa656a9ad04db3ad511854 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 15:05:01 +0100 Subject: [PATCH 12/15] chore: update managed browser for session security fixes (#5273) * chore: update managed browser for session security fixes * fix: preserve literal double dash in web ref fill * test(web): expect batch fill separator * test(web): decode batch stdin from supported buffer input * chore(web): format batch fill expectation --- .../agent-browser-provider-text-entry.test.ts | 31 +++++++++++++++++++ .../src/agent-browser-provider.test.ts | 8 +++-- .../src/agent-browser-provider.ts | 2 +- .../src/agent-browser-tool.test.ts | 8 ++--- .../platform-web/src/agent-browser-tool.ts | 2 +- .../test-kit/src/web-managed-agent-browser.ts | 2 +- .../provider-scenarios/web-provider.test.ts | 5 +-- 7 files changed, 47 insertions(+), 11 deletions(-) create mode 100644 packages/platform-web/src/__tests__/agent-browser-provider-text-entry.test.ts 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/agent-browser-provider.test.ts b/packages/platform-web/src/agent-browser-provider.test.ts index dd394df9a56..44a0b1ab4f6 100644 --- a/packages/platform-web/src/agent-browser-provider.test.ts +++ b/packages/platform-web/src/agent-browser-provider.test.ts @@ -146,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']], + ], ); }); }); @@ -626,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 7b47bf3d204..c5e40d5b433 100644 --- a/packages/platform-web/src/agent-browser-provider.ts +++ b/packages/platform-web/src/agent-browser-provider.ts @@ -141,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]); 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 59113431d30..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; 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/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 { From 1e513dda9f31a5c5b2d65be0381fd03d7c505de1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 15:15:05 +0100 Subject: [PATCH 13/15] fix(proxy): preserve HTTP responses after body cancellation --- .../http-server-rpc-admission.test.ts | 21 +++++++++---- packages/proxy/src/node-http.test.ts | 31 +++++++++++++++++++ packages/proxy/src/node-http.ts | 11 +++++-- 3 files changed, 54 insertions(+), 9 deletions(-) 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 3ff99a18171..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 @@ -12,7 +12,6 @@ import { skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; import { postRpcCommand, startRpcServer } from './http-server-rpc.fixtures.ts'; -import { getRequestSignal } from '@agent-device/host-kit/request'; const DAEMON_TOKEN = 'admission-daemon-secret'; const HOOK_CALLS_ENV = 'AGENT_DEVICE_TEST_HOOK_CALLS'; @@ -104,9 +103,19 @@ test('a disconnected rpc caller cancels a nonresolving auth hook and releases re __rpcAuthHookSignal?: AbortSignal; }; const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK; + let dispatches = 0; const { port, server } = await startWithAuthHook( - 'export default ({ signal }) => { globalThis.__rpcAuthHookSignal = signal; return new Promise(() => {}); };', - async () => ({ ok: true, data: {} }), + `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({ @@ -134,9 +143,9 @@ test('a disconnected rpc caller cancels a nonresolving auth hook and releases re assert.ok(signal); request.destroy(); await vi.waitFor(() => assert.equal(signal.aborted, true), { timeout: 1_000 }); - await vi.waitFor(() => assert.equal(getRequestSignal('stalled-auth-hook'), undefined), { - 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); 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 } : {}), }); } From 623966b66402f8d8f4a6269bbf8f0b36e3ab27f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 15:15:05 +0100 Subject: [PATCH 14/15] refactor(web): move address classification to its first consumer --- .../src/public-network-addresses.test.ts | 154 ------------- .../src/public-network-addresses.ts | 206 ------------------ 2 files changed, 360 deletions(-) delete mode 100644 packages/platform-web/src/public-network-addresses.test.ts delete mode 100644 packages/platform-web/src/public-network-addresses.ts diff --git a/packages/platform-web/src/public-network-addresses.test.ts b/packages/platform-web/src/public-network-addresses.test.ts deleted file mode 100644 index c370794d2b2..00000000000 --- a/packages/platform-web/src/public-network-addresses.test.ts +++ /dev/null @@ -1,154 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'vitest'; -import { admitPublicDestinationAddress, type ResolvedAddress } from './public-network-addresses.ts'; - -const noInterfaces = {}; - -function literal(hostname: string) { - return admitPublicDestinationAddress(hostname, [], noInterfaces); -} - -test('admits public numeric IPv4 and IPv6 destinations after canonicalization', () => { - assert.deepEqual(literal('8.8.8.8'), { - ok: true, - hostname: '8.8.8.8', - address: '8.8.8.8', - family: 4, - }); - assert.deepEqual(literal('2001:4860:4860::8888'), { - ok: true, - hostname: '2001:4860:4860::8888', - address: '2001:4860:4860::8888', - family: 6, - }); - assert.deepEqual(literal('2606:4700:4700::1111'), { - ok: true, - hostname: '2606:4700:4700::1111', - address: '2606:4700:4700::1111', - family: 6, - }); - assert.deepEqual(literal('::ffff:8.8.8.8'), { - ok: true, - hostname: '::ffff:808:808', - address: '8.8.8.8', - family: 4, - }); -}); - -test('refuses reserved and host-local numeric destinations, including IPv4 URL variants', () => { - for (const hostname of [ - '0.0.0.0', - '10.1.2.3', - '100.100.100.200', - '127.0.0.1', - '127.1', - '0177.0.0.1', - '0x7f000001', - '2130706433', - '169.254.169.254', - '172.16.0.1', - '192.0.0.1', - '192.0.2.1', - '192.88.99.1', - '192.168.1.1', - '198.18.0.1', - '198.51.100.1', - '203.0.113.1', - '224.0.0.1', - '255.255.255.255', - '::', - '::1', - '::ffff:127.0.0.1', - '64:ff9b::1', - '2001::1', - '2001:db8::1', - '2002::1', - '2d00::1', - '3000::1', - '3ffe::1', - '3fff::1', - 'fc00::1', - 'fe80::1', - 'ff02::1', - ]) { - assert.deepEqual(literal(hostname), { ok: false, reason: 'non_public_address' }, hostname); - } -}); - -test('refuses malformed destinations and mixed or invalid DNS answer sets', () => { - for (const hostname of ['', 'user@host.test', 'host.test/path', 'host.test:80', 'fe80::1%en0']) { - assert.deepEqual(literal(hostname), { ok: false, reason: 'invalid_destination' }, hostname); - } - assert.deepEqual(admitPublicDestinationAddress('public.test', [], noInterfaces), { - ok: false, - reason: 'invalid_destination', - }); - const mixed: ResolvedAddress[] = [ - { address: '8.8.8.8', family: 4 }, - { address: '127.0.0.1', family: 4 }, - ]; - assert.deepEqual(admitPublicDestinationAddress('public.test', mixed, noInterfaces), { - ok: false, - reason: 'non_public_address', - }); - assert.deepEqual( - admitPublicDestinationAddress('public.test', [...mixed].reverse(), noInterfaces), - { - ok: false, - reason: 'non_public_address', - }, - ); - assert.deepEqual( - admitPublicDestinationAddress('public.test', [{ address: '8.8.8.8', family: 6 }], noInterfaces), - { ok: false, reason: 'invalid_destination' }, - ); - assert.deepEqual( - admitPublicDestinationAddress( - 'public.test', - [{ address: '::ffff:127.0.0.1', family: 6 }], - noInterfaces, - ), - { ok: false, reason: 'non_public_address' }, - ); - assert.deepEqual( - admitPublicDestinationAddress( - 'public.test', - [{ address: '::ffff:8.8.8.8', family: 6 }], - noInterfaces, - ), - { ok: true, hostname: 'public.test', address: '8.8.8.8', family: 4 }, - ); -}); - -test('refuses public addresses assigned to the daemon host, including mapped IPv4', () => { - const interfaces = { - en0: [{ address: '8.8.8.8' }, { address: '2001:4860:4860::8888' }], - }; - assert.deepEqual(admitPublicDestinationAddress('8.8.8.8', [], interfaces), { - ok: false, - reason: 'local_interface_address', - }); - assert.deepEqual(admitPublicDestinationAddress('::ffff:8.8.8.8', [], interfaces), { - ok: false, - reason: 'local_interface_address', - }); - assert.deepEqual(admitPublicDestinationAddress('2001:4860:4860::8888', [], interfaces), { - ok: false, - reason: 'local_interface_address', - }); - assert.deepEqual( - admitPublicDestinationAddress('public.test', [{ address: '1.1.1.1', family: 4 }], interfaces), - { ok: true, hostname: 'public.test', address: '1.1.1.1', family: 4 }, - ); - assert.deepEqual( - admitPublicDestinationAddress( - 'public.test', - [ - { address: '1.1.1.1', family: 4 }, - { address: '8.8.8.8', family: 4 }, - ], - interfaces, - ), - { ok: false, reason: 'local_interface_address' }, - ); -}); diff --git a/packages/platform-web/src/public-network-addresses.ts b/packages/platform-web/src/public-network-addresses.ts deleted file mode 100644 index f8ed8c5cacf..00000000000 --- a/packages/platform-web/src/public-network-addresses.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { BlockList, isIP } from 'node:net'; - -export type ResolvedAddress = Readonly<{ address: string; family: 4 | 6 }>; - -type InterfaceAddresses = Readonly< - Record[] | undefined> ->; - -type AdmittedAddress = Readonly<{ - ok: true; - hostname: string; - address: string; - family: 4 | 6; -}>; - -type RefusedAddress = Readonly<{ - ok: false; - reason: 'invalid_destination' | 'non_public_address' | 'local_interface_address'; -}>; - -export type PublicDestinationAddress = AdmittedAddress | RefusedAddress; -type CandidateDecision = Readonly<{ ok: true; candidate: ResolvedAddress }> | RefusedAddress; - -const deniedIpv4 = new BlockList(); -for (const [subnet, prefix] of [ - ['0.0.0.0', 8], - ['10.0.0.0', 8], - ['100.64.0.0', 10], - ['127.0.0.0', 8], - ['169.254.0.0', 16], - ['172.16.0.0', 12], - ['192.0.0.0', 24], - ['192.0.2.0', 24], - ['192.88.99.0', 24], - ['192.168.0.0', 16], - ['198.18.0.0', 15], - ['198.51.100.0', 24], - ['203.0.113.0', 24], - ['224.0.0.0', 4], - ['240.0.0.0', 4], -] as const) { - deniedIpv4.addSubnet(subnet, prefix, 'ipv4'); -} - -// IANA IPv6 Global Unicast Address Space (2025-10-10): unlisted 2000::/3 ranges are reserved. -const allocatedIpv6 = new BlockList(); -for (const [subnet, prefix] of [ - ['2001:200::', 23], - ['2001:400::', 23], - ['2001:600::', 23], - ['2001:800::', 22], - ['2001:c00::', 23], - ['2001:e00::', 23], - ['2001:1200::', 23], - ['2001:1400::', 22], - ['2001:1800::', 23], - ['2001:1a00::', 23], - ['2001:1c00::', 22], - ['2001:2000::', 19], - ['2001:4000::', 23], - ['2001:4200::', 23], - ['2001:4400::', 23], - ['2001:4600::', 23], - ['2001:4800::', 23], - ['2001:4a00::', 23], - ['2001:4c00::', 23], - ['2001:5000::', 20], - ['2001:8000::', 19], - ['2001:a000::', 20], - ['2001:b000::', 20], - ['2003::', 18], - ['2400::', 12], - ['2410::', 12], - ['2600::', 12], - ['2610::', 23], - ['2620::', 23], - ['2630::', 12], - ['2800::', 12], - ['2a00::', 12], - ['2a10::', 12], - ['2c00::', 12], -] as const) { - allocatedIpv6.addSubnet(subnet, prefix, 'ipv6'); -} -const deniedIpv6 = new BlockList(); -deniedIpv6.addSubnet('2001:db8::', 32, 'ipv6'); - -// Classifies one connection's complete DNS answer set. The proxy must call it again for each new connection. -export function admitPublicDestinationAddress( - rawHostname: string, - answers: readonly ResolvedAddress[], - interfaces: InterfaceAddresses, -): PublicDestinationAddress { - const hostname = normalizeHostname(rawHostname); - if (hostname === undefined) return { ok: false, reason: 'invalid_destination' }; - - const literal = parseAddress(hostname); - const candidates = literal === undefined ? answers : [literal]; - if (candidates.length === 0) return { ok: false, reason: 'invalid_destination' }; - - const localAddresses = collectLocalAddresses(interfaces); - if (localAddresses === undefined) return { ok: false, reason: 'invalid_destination' }; - const decision = selectAdmittedCandidate(candidates, localAddresses); - if (!decision.ok) return decision; - return { ok: true, hostname, ...decision.candidate }; -} - -function collectLocalAddresses(interfaces: InterfaceAddresses): ReadonlySet | undefined { - const localAddresses = new Set(); - for (const group of Object.values(interfaces)) { - for (const entry of group ?? []) { - const local = parseAddress(entry.address.split('%', 1)[0] ?? ''); - if (local === undefined) return undefined; - localAddresses.add(`${local.family}:${local.address}`); - } - } - return localAddresses; -} - -function selectAdmittedCandidate( - candidates: readonly ResolvedAddress[], - localAddresses: ReadonlySet, -): CandidateDecision { - let selected: ResolvedAddress | undefined; - for (const candidate of candidates) { - const decision = classifyCandidate(candidate, localAddresses); - if (!decision.ok) return decision; - selected ??= decision.candidate; - } - return selected === undefined - ? { ok: false, reason: 'invalid_destination' } - : { ok: true, candidate: selected }; -} - -function classifyCandidate( - candidate: ResolvedAddress, - localAddresses: ReadonlySet, -): CandidateDecision { - const parsed = parseAddress(candidate.address); - const mappedIpv4 = - candidate.family === 6 && parsed?.family === 4 && isIP(candidate.address) === 6; - if (parsed === undefined || (parsed.family !== candidate.family && !mappedIpv4)) { - return { ok: false, reason: 'invalid_destination' }; - } - if (!isGlobalAddress(parsed)) return { ok: false, reason: 'non_public_address' }; - if (localAddresses.has(`${parsed.family}:${parsed.address}`)) { - return { ok: false, reason: 'local_interface_address' }; - } - return { ok: true, candidate: parsed }; -} - -function normalizeHostname(raw: string): string | undefined { - if (!raw || /[\s@/?#%\\]/u.test(raw)) return undefined; - const ipv6 = isIP(raw) === 6; - if (!ipv6 && raw.includes(':') && !(raw.startsWith('[') && raw.endsWith(']'))) { - return undefined; - } - const authority = ipv6 ? `[${raw}]` : raw; - try { - const url = new URL(`http://${authority}/`); - if ( - url.username || - url.password || - url.port || - url.pathname !== '/' || - url.search || - url.hash - ) { - return undefined; - } - return url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname; - } catch { - return undefined; - } -} - -function parseAddress(address: string): ResolvedAddress | undefined { - if (address.includes('%')) return undefined; - const family = isIP(address); - if (family === 4) return { address, family }; - if (family !== 6) return undefined; - let normalized: string; - try { - normalized = new URL(`http://[${address}]/`).hostname.slice(1, -1); - } catch { - return undefined; - } - const mapped = /^::ffff:([0-9a-f]+):([0-9a-f]+)$/u.exec(normalized); - if (mapped) { - const high = Number.parseInt(mapped[1] ?? '', 16); - const low = Number.parseInt(mapped[2] ?? '', 16); - if (high > 0xffff || low > 0xffff) return undefined; - return { - address: `${high >>> 8}.${high & 255}.${low >>> 8}.${low & 255}`, - family: 4, - }; - } - return { address: normalized, family: 6 }; -} - -function isGlobalAddress(candidate: ResolvedAddress): boolean { - if (candidate.family === 4) return !deniedIpv4.check(candidate.address, 'ipv4'); - return ( - allocatedIpv6.check(candidate.address, 'ipv6') && !deniedIpv6.check(candidate.address, 'ipv6') - ); -} From 61f0e4de9a5820dd84f2107bfc8c3f09af23f3cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 08:23:16 +0100 Subject: [PATCH 15/15] docs(web): document managed browser upgrade setup --- website/docs/docs/commands.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index f822e2f9eb8..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