From 9ad1e0a66ad3b1dd2cffccc8b106b812b062078e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 17:16:26 +0100 Subject: [PATCH 01/17] fix: bound rpc preauth without blocking admitted callers --- .../http-server-rpc-validation.test.ts | 4 +- ...ttp-authorization-script-admission.test.ts | 21 ++++ .../src/server/http/http-authorization.ts | 3 +- .../http-server-rpc-ingress-budget.test.ts | 11 ++- .../daemon/src/server/http/http-server.ts | 99 ++++++++++++------- .../src/daemon-proxy-cancellation.test.ts | 29 +++++- packages/proxy/src/daemon-proxy.test.ts | 54 +++++----- packages/proxy/src/daemon-proxy.ts | 22 ++++- packages/proxy/src/node-http.test.ts | 36 +++++++ packages/proxy/src/rpc-body-budget.ts | 14 +-- packages/proxy/src/rpc-preauth-deadline.ts | 37 +++++++ website/docs/docs/error-reasons.md | 3 +- website/docs/docs/security-trust.md | 2 +- 13 files changed, 242 insertions(+), 93 deletions(-) create mode 100644 packages/proxy/src/rpc-preauth-deadline.ts 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 4174f8d81ad..78fedb0b9e8 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 @@ -454,7 +454,7 @@ test('only local command RPC keeps the client developer dir', async (t) => { } }); -test('only local lease allocation RPC keeps the provider credential fingerprint', async (t) => { +test('tenant-scoped lease allocation RPC strips the provider credential fingerprint', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const root = mkdtempForTestSync('agent-device-http-provider-credentials-'); const fingerprintSeenBy = async (env: NodeJS.ProcessEnv): Promise => { @@ -493,7 +493,7 @@ test('only local lease allocation RPC keeps the provider credential fingerprint' }; try { - assert.equal(await fingerprintSeenBy(localHttpEnvironment()), 'v1:0123456789abcdef'); + assert.equal(await fingerprintSeenBy(localHttpEnvironment()), undefined); assert.equal( await fingerprintSeenBy(remoteHttpEnvironment(writeAllowingAuthHook(root))), undefined, diff --git a/packages/daemon/src/server/http/http-authorization-script-admission.test.ts b/packages/daemon/src/server/http/http-authorization-script-admission.test.ts index 071a5a84837..bbff67d83fd 100644 --- a/packages/daemon/src/server/http/http-authorization-script-admission.test.ts +++ b/packages/daemon/src/server/http/http-authorization-script-admission.test.ts @@ -60,3 +60,24 @@ test.each([ }), ); }); + +test('a directly admitted tenant receives remote restrictions without a proxy marker', () => { + const request: DaemonRequest = { + token: 'test', + session: 'owned', + command: 'open', + positionals: [], + flags: { saveScript: '/host/a.ad' }, + meta: { tenantId: 'tenant-a', scriptPublicationId: PUBLICATION_ID }, + }; + expect(() => restrictRemoteHttpRequest(request, false, undefined)).toThrowError( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ reason: 'REMOTE_HOST_INPUT_DENIED' }), + }), + ); + expect( + restrictRemoteHttpRequest({ ...request, meta: {} }, false, undefined).internal + ?.publicNetworkOnly, + ).not.toBe(true); +}); diff --git a/packages/daemon/src/server/http/http-authorization.ts b/packages/daemon/src/server/http/http-authorization.ts index abd5c61318f..37fc6ac1748 100644 --- a/packages/daemon/src/server/http/http-authorization.ts +++ b/packages/daemon/src/server/http/http-authorization.ts @@ -65,7 +65,8 @@ function restrictRemoteHttpRequest( ) { throw new AppError('INVALID_ARGS', 'Invalid daemon HTTP network access marker'); } - if (!authHookConfigured && networkAccessMarker === undefined) return request; + if (!authHookConfigured && networkAccessMarker === undefined && !request.meta?.tenantId) + return request; // A developer dir is a host path whose tools the daemon would run, and a credential fingerprint // would let a remote caller probe the daemon's credentials. A daemon with an auth hook serves // remote callers and runs on its operator's credentials, so it treats every caller as remote. 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 index 60299ead9d3..5b6ec47e08f 100644 --- 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 @@ -4,7 +4,7 @@ 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) => { +test('unfinished unauthenticated RPC bodies do not block authenticated dispatch', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; let dispatched = 0; const { port, server } = await startRpcServer('budget-token', async () => { @@ -34,12 +34,13 @@ test('unfinished RPC bodies exhaust a bounded ingress budget without dispatch', 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); + const admitted = await postRpcCommand(port, 'budget-token', 'admitted'); + assert.equal(admitted.status, 200); + assert.equal(dispatched, 1); } finally { for (const request of held) request.destroy(); + const afterDisconnect = await postRpcCommand(port, 'budget-token', 'after-disconnect'); + assert.equal(afterDisconnect.status, 200); await closeLoopbackServer(server); } }); diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 82cc6551f6e..a7784351f27 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -11,12 +11,8 @@ 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, - ReasonTable, -} from '@agent-device/kernel/errors'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import type { DiagnosticsRecordRef, NormalizedError } from '@agent-device/kernel/errors'; +import { 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'; @@ -96,14 +92,8 @@ import { } from './http-checked-rpc.ts'; const MAX_HTTP_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; -const MAX_IN_FLIGHT_RPC_BODIES = 32; const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; -const RPC_INGRESS_REASONS = { - // Too many daemon RPC requests are in flight through dispatch. The daemon closes a request - // that exceeds its aggregate body-byte limit. - capacityExceeded: { reason: 'RPC_BODY_CAPACITY_EXCEEDED' }, -} as const satisfies ReasonTable<'RPC ingress'>; -type RpcBodyBudget = { active: number; bytes: number }; +type RpcBodyBudget = { bytes: number }; /** What this daemon serves over HTTP beyond the base RPC contract, as `/health` advertises it. */ const DAEMON_HTTP_CAPABILITIES = [ 'script-artifacts', @@ -157,7 +147,7 @@ export async function createDaemonHttpServer(options: { resolveRequestDiagnosticsPath, onUnownedRequestFailure, } = options; - const rpcBodyBudget: RpcBodyBudget = { active: 0, bytes: 0 }; + const rpcBodyBudget: RpcBodyBudget = { 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) { @@ -264,7 +254,7 @@ export async function createDaemonHttpServer(options: { return; } - readRpcRequestBody(req, res, rpcBodyBudget, (body, release) => { + readRpcRequestBody(req, res, rpcBodyBudget, (body, release, preauthSignal, finishPreauth) => { // 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 @@ -278,6 +268,8 @@ export async function createDaemonHttpServer(options: { instanceId, handleRequest, checked, + preauthSignal, + finishPreauth, }) .catch((error: unknown) => { sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); @@ -311,20 +303,25 @@ function readRpcRequestBody( req: http.IncomingMessage, res: http.ServerResponse, budget: RpcBodyBudget, - onBody: (body: string, release: () => void) => void, + onBody: ( + body: string, + release: () => void, + preauthSignal: AbortSignal, + finishPreauth: () => 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; + const preauth = new AbortController(); + const deadline = setTimeout(() => { + preauth.abort(new Error('RPC ingress deadline exceeded')); + release(); + if (!res.headersSent && !res.writableEnded) { + res.once('finish', () => req.destroy()); + sendRpcRefusal(res, rpcRefusal(null, -32000, 'RPC ingress deadline exceeded', 408)); + } else { + req.destroy(); + } + }, 5_000); + const finishPreauth = () => clearTimeout(deadline); let body = ''; let bodyBytes = 0; let released = false; @@ -336,11 +333,12 @@ function readRpcRequestBody( if (released) return; released = true; req.off('aborted', onAborted); - budget.active -= 1; + clearTimeout(deadline); budget.bytes -= bodyBytes; }; req.setEncoding('utf8'); req.on('data', (chunk: string) => { + if (released) return; const bytes = Buffer.byteLength(chunk, 'utf8'); if ( bodyBytes + bytes > MAX_HTTP_RPC_BODY_BYTES || @@ -356,7 +354,7 @@ function readRpcRequestBody( req.on('error', () => { if (!bodyComplete) release(); - if (!res.headersSent) { + if (!res.headersSent && !res.writableEnded) { sendRpcRefusal(res, rpcParseErrorRefusal()); } }); @@ -365,8 +363,9 @@ function readRpcRequestBody( req.on( 'end', AsyncResource.bind(() => { + if (released) return; bodyComplete = true; - onBody(body, release); + onBody(body, release, preauth.signal, finishPreauth); }), ); } @@ -387,8 +386,21 @@ async function handleRpcRequest(params: { handleRequest: DaemonInvokeFn; /** The call came on the checked route, so its protocol is checked before dispatch. */ checked: boolean; + preauthSignal: AbortSignal; + finishPreauth: () => void; }): Promise { - const { req, res, body, authHook, expectedToken, instanceId, handleRequest, checked } = params; + const { + req, + res, + body, + authHook, + expectedToken, + instanceId, + handleRequest, + checked, + preauthSignal, + finishPreauth, + } = params; // A checked call proves its credential before anything reads its protocol or method. One on // another protocol then takes the `/rpc` flow and is refused only once every auth gate passed. if (checked && refuseCheckedRpcCredential(req, res, body, expectedToken)) return; @@ -416,7 +428,9 @@ async function handleRpcRequest(params: { params: validated.params, lifetime, protocolRefusal, + preauthSignal, }); + finishPreauth(); if (admission.outcome !== 'admitted') { if (admission.outcome === 'rejected') { sendRpcRefusal(res, admission.refusal); @@ -424,6 +438,8 @@ async function handleRpcRequest(params: { return; } + preauthSignal.throwIfAborted(); + lifetime.watchForClientDisconnect(); await invokeAdmittedRpcRequest({ res, @@ -437,8 +453,10 @@ async function handleRpcRequest(params: { // or a duplicate tracking id. The failure answer is on its way, so a socket closing // after it is not a client walking out on work still in flight. lifetime.markHandlerCompleted(); - sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); + if (!res.writableEnded) + sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); } finally { + finishPreauth(); lifetime.release(); } } @@ -663,8 +681,19 @@ async function admitRpcRequest(params: { lifetime: RpcRequestLifetime; /** A checked call's protocol refusal, answered once the caller passes the auth gates. */ protocolRefusal: CheckedRpcProtocolRefusal | undefined; + preauthSignal: AbortSignal; }): Promise { - const { req, res, authHook, expectedToken, instanceId, rpcRequest, method, lifetime } = params; + const { + req, + res, + authHook, + expectedToken, + instanceId, + rpcRequest, + method, + lifetime, + preauthSignal, + } = params; const { protocolRefusal } = params; const wireRequest = methodToDaemonRequest(method, params.params, req.headers); // A command call naming no command is params the router cannot route. @@ -692,7 +721,7 @@ async function admitRpcRequest(params: { headers: req.headers, rpcRequest, daemonRequest, - signal: lifetime.signal, + signal: AbortSignal.any([lifetime.signal, preauthSignal]), }); if (!authResult.ok) { return { diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts index 07761e6c716..f7cfe805703 100644 --- a/packages/proxy/src/daemon-proxy-cancellation.test.ts +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -69,7 +69,7 @@ function rpcRequest(body: unknown, init: RequestInit = {}): Request { }); } -test('a disconnected RPC stops waiting for authentication and releases its body slot', async () => { +test('a pending RPC authentication does not block another caller', async () => { let authenticating = 0; const proxy = createDaemonProxy({ upstreamBaseUrl: 'http://daemon.internal:4310', @@ -90,21 +90,40 @@ test('a disconnected RPC stops waiting for authentication and releases its body ), ); await vi.waitFor(() => expect(authenticating).toBe(32)); - const full = await proxy.handle( + const admitted = await proxy.handle( rpcRequest({ jsonrpc: '2.0', id: 33, method: 'agent-device.command' }), ); - expect(full.status).toBe(503); + expect(admitted.status).toBe(200); controllers[0]!.abort(); await pending[0]; - const admitted = await proxy.handle( + const afterDisconnect = await proxy.handle( rpcRequest({ jsonrpc: '2.0', id: 34, method: 'agent-device.command' }), ); - expect(admitted.status).toBe(200); + expect(afterDisconnect.status).toBe(200); for (const controller of controllers.slice(1)) controller.abort(); await Promise.all(pending); }); +test('an RPC authentication that never settles reaches the ingress deadline', async () => { + vi.useFakeTimers(); + try { + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: async () => Response.json({ ok: true }), + authenticate: () => new Promise(() => {}), + }); + const pending = proxy.handle( + rpcRequest({ jsonrpc: '2.0', id: 1, method: 'agent-device.command' }), + ); + await vi.advanceTimersByTimeAsync(5_001); + expect((await pending).status).toBeGreaterThanOrEqual(400); + } finally { + vi.useRealTimers(); + } +}); + test.each([ { route: 'rpc', diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index 1615e1fcf8c..6041295f161 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -210,7 +210,27 @@ 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 () => { +test('a stalled body cancellation does not delay a size refusal', async () => { + const proxy = proxyWith(async () => Response.json({ ok: true }), 16); + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(17)); + }, + cancel() { + return new Promise(() => {}); + }, + }); + const response = await proxy.handle( + new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { + method: 'POST', + body, + duplex: 'half', + } as RequestInit & { duplex: 'half' }), + ); + expect(response.status).toBe(400); +}); + +test('unread unauthenticated RPC bodies do not block an authenticated caller', async () => { const upstream = recordingUpstream(() => Response.json({ ok: true })); const proxy = proxyWith(upstream.fetch); const bodies: ReadableStreamDefaultController[] = []; @@ -229,35 +249,17 @@ 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( - new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { - method: 'POST', - body: refusedBody, - duplex: 'half', - } as RequestInit & { duplex: 'half' }), - ); - expect(refused.status).toBe(503); - await vi.waitFor(() => expect(refusedBodyCanceled).toBe(true)); - expect(await refused.json()).toMatchObject({ - error: { data: { details: { reason: 'PROXY_RPC_BODY_CAPACITY_EXCEEDED' } } }, - }); - expect(upstream.requests).toHaveLength(0); - - for (const body of bodies) body.close(); - await Promise.all(pending); const admitted = await proxy.handle( rpcRequest({ jsonrpc: '2.0', id: 34, method: 'agent-device.command' }), ); expect(admitted.status).toBe(200); + expect(upstream.requests).toHaveLength(1); + + for (const body of bodies) body.close(); + await Promise.all(pending); }); -test('aborting an unread RPC body releases its proxy budget slot', async () => { +test('aborting an unread RPC body does not affect another caller', async () => { const upstream = recordingUpstream(() => Response.json({ ok: true })); const proxy = proxyWith(upstream.fetch); const controllers = Array.from({ length: 32 }, () => new AbortController()); @@ -271,10 +273,10 @@ test('aborting an unread RPC body releases its proxy budget slot', async () => { } as RequestInit & { duplex: 'half' }), ), ); - const full = await proxy.handle( + const first = await proxy.handle( rpcRequest({ jsonrpc: '2.0', id: 33, method: 'agent-device.command' }), ); - expect(full.status).toBe(503); + expect(first.status).toBe(200); controllers[0]!.abort(); await pending[0]; diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 9268ace2675..1938079cca4 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -31,6 +31,7 @@ import { hostPathInstallSourceRefusedResponse, } from './install-source-admission.ts'; import type { createRpcBodyBudget } from './rpc-body-budget.ts'; +import { beginRpcPreauth } from './rpc-preauth-deadline.ts'; /** * Carries one request to the upstream daemon and resolves with its response. Without `upstreamFetch` @@ -133,7 +134,6 @@ type ProxyCaller = { tenantId?: string; uploadHeaders: Record }; /** The client request headers an upload ticket repeats when `authenticate` names none. */ const DEFAULT_UPLOAD_CREDENTIAL_HEADERS = Object.keys(buildDaemonHttpAuthHeaders('client')); - const DEFAULT_MAX_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; /** `/health` answers quickly or not at all; its probe never waits on `upstreamTimeoutMs`. */ const UPSTREAM_HEALTH_TIMEOUT_MS = 5_000; @@ -207,11 +207,15 @@ async function handleProxyRequest( } if (!isRpcRoute(route)) return await handleDaemonRoute(request, route, options, instanceId); - + let preauth!: ReturnType; let ingress: { body: string; release: () => void }; try { - ingress = await (await options.getRpcBodyBudget()).read(request, options.maxRpcBodyBytes); + preauth = beginRpcPreauth(request); + ingress = await ( + await options.getRpcBodyBudget() + ).read(preauth.request, options.maxRpcBodyBytes); } catch (error) { + preauth?.finish(); return rpcErrorResponse(null, error); } try { @@ -222,11 +226,15 @@ async function handleProxyRequest( route === DAEMON_HTTP_CHECKED_RPC_ROUTE ? null : refuseInvalidRpcEnvelope(rpcBody); if (envelopeRefusal) return envelopeRefusal; try { - return await handleDaemonRoute(request, route, options, instanceId, rpcBody); + const caller = await authenticateCaller(preauth.request, options, rpcBody); + preauth.signal.throwIfAborted(); + preauth.finish(); + return await handleDaemonRoute(request, route, options, instanceId, rpcBody, caller); } catch (error) { return rpcErrorResponse(readJsonRpcId(rpcBody), error); } } finally { + preauth.finish(); ingress.release(); } } @@ -237,8 +245,12 @@ async function handleDaemonRoute( options: NormalizedProxyOptions, instanceId: string, rpcBody?: string, + admittedCaller?: ProxyCaller | null, ): Promise { - const caller = await authenticateCaller(request, options, rpcBody); + const caller = + admittedCaller === undefined + ? await authenticateCaller(request, options, rpcBody) + : admittedCaller; if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } diff --git a/packages/proxy/src/node-http.test.ts b/packages/proxy/src/node-http.test.ts index 26378bb976b..de38829986d 100644 --- a/packages/proxy/src/node-http.test.ts +++ b/packages/proxy/src/node-http.test.ts @@ -130,6 +130,42 @@ test('a handler can cancel an unread body and still answer the request', async ( } }); +test('cancelling an unfinished body still writes a capacity refusal', async () => { + const proxy: DaemonProxy = { + instanceId: 'test', + handle: async (request) => { + await request.body?.cancel(); + return new Response(null, { status: 503 }); + }, + }; + 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 status = await new Promise((resolve, reject) => { + const client = http.request( + { + port, + host: '127.0.0.1', + method: 'POST', + path: '/agent-device/rpc', + headers: { 'content-length': '100' }, + }, + (response) => { + response.resume(); + resolve(response.statusCode); + }, + ); + client.on('error', reject); + client.write('partial'); + }); + expect(status).toBe(503); + } finally { + server.closeAllConnections(); + 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/rpc-body-budget.ts b/packages/proxy/src/rpc-body-budget.ts index bca4dc51e72..b04bacad03a 100644 --- a/packages/proxy/src/rpc-body-budget.ts +++ b/packages/proxy/src/rpc-body-budget.ts @@ -5,10 +5,9 @@ import { } from '@agent-device/kernel/errors'; import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; -const MAX_IN_FLIGHT_RPC_BODIES = 32; const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; const RPC_INGRESS_REASONS = { - // Too many proxy RPC requests or aggregate body bytes are in flight through dispatch. + // Aggregate RPC body bytes are in flight through dispatch. capacityExceeded: { reason: 'PROXY_RPC_BODY_CAPACITY_EXCEEDED' }, } as const satisfies ReasonTable<'proxy RPC ingress'>; @@ -23,21 +22,14 @@ function capacityError(): AppError { export function createRpcBodyBudget(): { read(request: Request, maxBodyBytes: number): Promise<{ body: string; release: () => void }>; } { - let active = 0; let totalBytes = 0; return { async read(request, maxBodyBytes) { - if (active >= MAX_IN_FLIGHT_RPC_BODIES) { - void request.body?.cancel().catch(() => {}); - throw capacityError(); - } - active += 1; let ownedBytes = 0; let released = false; const release = () => { if (released) return; released = true; - active -= 1; totalBytes -= ownedBytes; }; try { @@ -51,11 +43,11 @@ export function createRpcBodyBudget(): { }); if (done) break; if (ownedBytes + value.byteLength > maxBodyBytes) { - await reader.cancel(); + void reader.cancel().catch(() => {}); throw new AppError('INVALID_ARGS', 'Proxy request body is too large.'); } if (totalBytes + value.byteLength > MAX_IN_FLIGHT_RPC_BODY_BYTES) { - await reader.cancel(); + void reader.cancel().catch(() => {}); throw capacityError(); } ownedBytes += value.byteLength; diff --git a/packages/proxy/src/rpc-preauth-deadline.ts b/packages/proxy/src/rpc-preauth-deadline.ts new file mode 100644 index 00000000000..4c53e53e725 --- /dev/null +++ b/packages/proxy/src/rpc-preauth-deadline.ts @@ -0,0 +1,37 @@ +const RPC_PREAUTH_TIMEOUT_MS = 5_000; + +/** Bounds an RPC body read and its authentication without shortening dispatch. */ +export function beginRpcPreauth(request: Request): { + request: Request; + signal: AbortSignal; + finish: () => void; +} { + const preauth = new AbortController(); + const deadline = setTimeout( + () => preauth.abort(new Error('RPC ingress deadline exceeded')), + RPC_PREAUTH_TIMEOUT_MS, + ); + const onClientAbort = () => preauth.abort(request.signal.reason); + const finish = () => { + clearTimeout(deadline); + request.signal.removeEventListener('abort', onClientAbort); + }; + request.signal.addEventListener('abort', onClientAbort, { once: true }); + if (request.signal.aborted) onClientAbort(); + try { + return { + request: new Request(request.url, { + method: request.method, + headers: request.headers, + body: request.body, + duplex: 'half', + signal: preauth.signal, + } as RequestInit & { duplex: 'half' }), + signal: preauth.signal, + finish, + }; + } catch (error) { + finish(); + throw error; + } +} diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 297cc732aff..c4ca8693ff1 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -460,7 +460,6 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `RPC_BODY_CAPACITY_EXCEEDED` | Too many daemon RPC requests are in flight through dispatch. The daemon closes a request that exceeds its aggregate body-byte limit. | ### Swift helper cache @@ -928,7 +927,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `PROXY_RPC_BODY_CAPACITY_EXCEEDED` | Too many proxy RPC requests or aggregate body bytes are in flight through dispatch. | +| `PROXY_RPC_BODY_CAPACITY_EXCEEDED` | Proxy RPC request bodies exceed the aggregate buffered-byte limit. | ### Ref frames diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 70dd11af602..b566a176813 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 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. +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 accumulated RPC request bodies to 128 MiB. A body and its authentication must finish within five seconds. Buffered body bytes remain reserved through dispatch. When the aggregate byte limit is reached, the daemon closes the request and the proxy returns 503 with reason `PROXY_RPC_BODY_CAPACITY_EXCEEDED`. Direct daemon HTTP calls that declare a tenant receive the remote input restrictions even through a local tunnel. ## Remote access From dbc9931589f089083cd1e5a0d3a3f87b00e65232 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 17:49:48 +0100 Subject: [PATCH 02/17] chore(gates): regenerate RPC reason reference --- packages/proxy/src/rpc-body-budget.ts | 2 +- website/docs/docs/error-reasons.md | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/packages/proxy/src/rpc-body-budget.ts b/packages/proxy/src/rpc-body-budget.ts index b04bacad03a..88ef8ce1b1f 100644 --- a/packages/proxy/src/rpc-body-budget.ts +++ b/packages/proxy/src/rpc-body-budget.ts @@ -7,7 +7,7 @@ import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; const RPC_INGRESS_REASONS = { - // Aggregate RPC body bytes are in flight through dispatch. + // Proxy RPC request bodies exceed the aggregate buffered-byte limit. capacityExceeded: { reason: 'PROXY_RPC_BODY_CAPACITY_EXCEEDED' }, } as const satisfies ReasonTable<'proxy RPC ingress'>; diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index c4ca8693ff1..384370fad71 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -456,11 +456,6 @@ 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 | -| --- | --- | - ### Swift helper cache | Reason | Meaning | From b1ab3c2a41bd0f809a62259fcc4b4e5025ee6c30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:11:08 +0100 Subject: [PATCH 03/17] fix: preserve local tenant RPC provenance --- .../__tests__/http-server-rpc-validation.test.ts | 4 ++-- .../http-authorization-script-admission.test.ts | 13 ++----------- .../daemon/src/server/http/http-authorization.ts | 3 +-- packages/proxy/src/daemon-proxy.ts | 3 ++- website/docs/docs/security-trust.md | 2 +- 5 files changed, 8 insertions(+), 17 deletions(-) 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 78fedb0b9e8..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 @@ -454,7 +454,7 @@ test('only local command RPC keeps the client developer dir', async (t) => { } }); -test('tenant-scoped lease allocation RPC strips the provider credential fingerprint', async (t) => { +test('only local lease allocation RPC keeps the provider credential fingerprint', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const root = mkdtempForTestSync('agent-device-http-provider-credentials-'); const fingerprintSeenBy = async (env: NodeJS.ProcessEnv): Promise => { @@ -493,7 +493,7 @@ test('tenant-scoped lease allocation RPC strips the provider credential fingerpr }; try { - assert.equal(await fingerprintSeenBy(localHttpEnvironment()), undefined); + assert.equal(await fingerprintSeenBy(localHttpEnvironment()), 'v1:0123456789abcdef'); assert.equal( await fingerprintSeenBy(remoteHttpEnvironment(writeAllowingAuthHook(root))), undefined, diff --git a/packages/daemon/src/server/http/http-authorization-script-admission.test.ts b/packages/daemon/src/server/http/http-authorization-script-admission.test.ts index bbff67d83fd..2d32d8133e9 100644 --- a/packages/daemon/src/server/http/http-authorization-script-admission.test.ts +++ b/packages/daemon/src/server/http/http-authorization-script-admission.test.ts @@ -61,7 +61,7 @@ test.each([ ); }); -test('a directly admitted tenant receives remote restrictions without a proxy marker', () => { +test('a client-declared tenant does not make a local request remote', () => { const request: DaemonRequest = { token: 'test', session: 'owned', @@ -70,14 +70,5 @@ test('a directly admitted tenant receives remote restrictions without a proxy ma flags: { saveScript: '/host/a.ad' }, meta: { tenantId: 'tenant-a', scriptPublicationId: PUBLICATION_ID }, }; - expect(() => restrictRemoteHttpRequest(request, false, undefined)).toThrowError( - expect.objectContaining({ - code: 'INVALID_ARGS', - details: expect.objectContaining({ reason: 'REMOTE_HOST_INPUT_DENIED' }), - }), - ); - expect( - restrictRemoteHttpRequest({ ...request, meta: {} }, false, undefined).internal - ?.publicNetworkOnly, - ).not.toBe(true); + expect(restrictRemoteHttpRequest(request, false, undefined)).toBe(request); }); diff --git a/packages/daemon/src/server/http/http-authorization.ts b/packages/daemon/src/server/http/http-authorization.ts index 37fc6ac1748..abd5c61318f 100644 --- a/packages/daemon/src/server/http/http-authorization.ts +++ b/packages/daemon/src/server/http/http-authorization.ts @@ -65,8 +65,7 @@ function restrictRemoteHttpRequest( ) { throw new AppError('INVALID_ARGS', 'Invalid daemon HTTP network access marker'); } - if (!authHookConfigured && networkAccessMarker === undefined && !request.meta?.tenantId) - return request; + if (!authHookConfigured && networkAccessMarker === undefined) return request; // A developer dir is a host path whose tools the daemon would run, and a credential fingerprint // would let a remote caller probe the daemon's credentials. A daemon with an auth hook serves // remote callers and runs on its operator's credentials, so it treats every caller as remote. diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 1938079cca4..4e1fe54b840 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -31,7 +31,7 @@ import { hostPathInstallSourceRefusedResponse, } from './install-source-admission.ts'; import type { createRpcBodyBudget } from './rpc-body-budget.ts'; -import { beginRpcPreauth } from './rpc-preauth-deadline.ts'; +import type { beginRpcPreauth } from './rpc-preauth-deadline.ts'; /** * Carries one request to the upstream daemon and resolves with its response. Without `upstreamFetch` @@ -210,6 +210,7 @@ async function handleProxyRequest( let preauth!: ReturnType; let ingress: { body: string; release: () => void }; try { + const { beginRpcPreauth } = await import('./rpc-preauth-deadline.ts'); preauth = beginRpcPreauth(request); ingress = await ( await options.getRpcBodyBudget() diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index b566a176813..a1ed0b825a8 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 limit accumulated RPC request bodies to 128 MiB. A body and its authentication must finish within five seconds. Buffered body bytes remain reserved through dispatch. When the aggregate byte limit is reached, the daemon closes the request and the proxy returns 503 with reason `PROXY_RPC_BODY_CAPACITY_EXCEEDED`. Direct daemon HTTP calls that declare a tenant receive the remote input restrictions even through a local tunnel. +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 accumulated RPC request bodies to 128 MiB. A body and its authentication must finish within five seconds. Buffered body bytes remain reserved through dispatch. When the aggregate byte limit is reached, the daemon closes the request and the proxy returns 503 with reason `PROXY_RPC_BODY_CAPACITY_EXCEEDED`. ## Remote access From e462e75c53e94bab432e1da87f0d08af28dbb725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 21:20:24 +0100 Subject: [PATCH 04/17] fix: type RPC preauth deadline refusal --- .../http-server-rpc-ingress-budget.test.ts | 48 ++++++++++++++++++- .../daemon/src/server/http/http-server.ts | 20 ++++++-- website/docs/docs/error-reasons.md | 6 +++ 3 files changed, 70 insertions(+), 4 deletions(-) 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 index 5b6ec47e08f..66581e57b89 100644 --- 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 @@ -1,9 +1,55 @@ import http from 'node:http'; import assert from 'node:assert/strict'; -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; import { postRpcCommand, startRpcServer } from '../__tests__/http-server-rpc.fixtures.ts'; +test('preauthorization body deadline answers with a typed reason before 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: {} }; + }); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const reached = new Promise((resolve) => server.once('request', () => resolve())); + let request!: http.ClientRequest; + const response = new Promise<{ status: number; body: string }>((resolve, reject) => { + request = http.request({ + host: '127.0.0.1', + port, + method: 'POST', + path: '/rpc', + headers: { 'content-type': 'application/json' }, + }); + request.on('response', (res) => { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => + resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') }), + ); + }); + request.on('error', reject); + request.flushHeaders(); + }); + try { + await reached; + await vi.advanceTimersByTimeAsync(5_000); + const answered = await response; + const body = JSON.parse(answered.body) as { + error?: { data?: { details?: { reason?: string; dispatched?: string } } }; + }; + assert.equal(answered.status, 408); + assert.equal(body.error?.data?.details?.reason, 'RPC_PREAUTH_DEADLINE_EXCEEDED'); + assert.equal(body.error?.data?.details?.dispatched, 'no'); + assert.equal(dispatched, 0); + } finally { + vi.useRealTimers(); + request.destroy(); + await closeLoopbackServer(server); + } +}); + test('unfinished unauthenticated RPC bodies do not block authenticated dispatch', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; let dispatched = 0; diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index a7784351f27..a8d9ef03a35 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'; @@ -93,6 +97,10 @@ import { const MAX_HTTP_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; +const DAEMON_RPC_INGRESS_REASONS = { + // The RPC body did not complete before its preauthorization deadline, so nothing was dispatched. + preauthDeadlineExceeded: { reason: 'RPC_PREAUTH_DEADLINE_EXCEEDED' }, +} as const satisfies ReasonTable<'daemon RPC ingress'>; type RpcBodyBudget = { bytes: number }; /** What this daemon serves over HTTP beyond the base RPC contract, as `/health` advertises it. */ const DAEMON_HTTP_CAPABILITIES = [ @@ -316,7 +324,13 @@ function readRpcRequestBody( release(); if (!res.headersSent && !res.writableEnded) { res.once('finish', () => req.destroy()); - sendRpcRefusal(res, rpcRefusal(null, -32000, 'RPC ingress deadline exceeded', 408)); + const error = normalizeError( + new AppError('COMMAND_FAILED', 'RPC ingress deadline exceeded', { + reason: DAEMON_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason, + dispatched: 'no', + }), + ); + sendRpcRefusal(res, rpcRefusal(null, -32000, error.message, 408, error)); } else { req.destroy(); } diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 384370fad71..16232d0c50c 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -599,6 +599,12 @@ These reasons can come from more than one command. | --- | --- | | `coordinate_unit_density_unknown` | No density is known before dispatch: the device answered no density read and no `coordinateDensity` came with the request, so its dp geometry cannot be converted. Nothing was dispatched. | +### Daemon RPC ingress + +| Reason | Meaning | +| --- | --- | +| `RPC_PREAUTH_DEADLINE_EXCEEDED` | The RPC body did not complete before its preauthorization deadline, so nothing was dispatched. | + ### Daemon lifecycle | Reason | Meaning | From 197496ae68f50f8058a0d12d80a3c25fe92c768f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 21:58:46 +0100 Subject: [PATCH 05/17] fix: type proxy RPC preauth deadline refusal --- .../src/daemon-proxy-cancellation.test.ts | 73 ++++++++++++++++++- packages/proxy/src/daemon-proxy.ts | 7 +- packages/proxy/src/rpc-preauth-deadline.ts | 28 +++++-- website/docs/docs/error-reasons.md | 1 + 4 files changed, 100 insertions(+), 9 deletions(-) diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts index f7cfe805703..03203162d1d 100644 --- a/packages/proxy/src/daemon-proxy-cancellation.test.ts +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -3,6 +3,7 @@ import type { AddressInfo } from 'node:net'; import { setFlagsFromString } from 'node:v8'; import { runInNewContext } from 'node:vm'; import { expect, onTestFinished, test, vi } from 'vitest'; +import { AppError } from '@agent-device/kernel/errors'; import { createDaemonProxy, createDaemonProxyServer, @@ -118,12 +119,82 @@ test('an RPC authentication that never settles reaches the ingress deadline', as rpcRequest({ jsonrpc: '2.0', id: 1, method: 'agent-device.command' }), ); await vi.advanceTimersByTimeAsync(5_001); - expect((await pending).status).toBeGreaterThanOrEqual(400); + const response = await pending; + const body = (await response.json()) as { + error?: { data?: { details?: { reason?: string; dispatched?: string } } }; + }; + expect(response.status).toBe(408); + expect(body.error?.data?.details).toMatchObject({ + reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', + dispatched: 'no', + }); + } finally { + vi.useRealTimers(); + } +}); + +test('an unfinished RPC body receives the same typed preauth deadline refusal', async () => { + vi.useFakeTimers(); + try { + const upstreamFetch = vi.fn(async () => Response.json({ ok: true })); + const proxy = proxyWith(upstreamFetch); + const request = new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { + method: 'POST', + headers: { authorization: 'Bearer client-secret', 'content-type': 'application/json' }, + body: new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('{')); + }, + }), + duplex: 'half', + } as RequestInit & { duplex: 'half' }); + const pending = proxy.handle(request); + await vi.advanceTimersByTimeAsync(5_001); + const response = await pending; + const body = (await response.json()) as { + error?: { data?: { details?: { reason?: string; dispatched?: string } } }; + }; + expect(response.status).toBe(408); + expect(body.error?.data?.details).toMatchObject({ + reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', + dispatched: 'no', + }); + expect(upstreamFetch).not.toHaveBeenCalled(); } finally { vi.useRealTimers(); } }); +test('a caller abort cannot claim the proxy-owned preauth deadline', async () => { + const entered = signalled(); + const controller = new AbortController(); + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: async () => Response.json({ ok: true }), + authenticate: () => { + entered.resolve(); + return new Promise(() => {}); + }, + }); + const pending = proxy.handle( + rpcRequest( + { jsonrpc: '2.0', id: 1, method: 'agent-device.command' }, + { signal: controller.signal }, + ), + ); + await entered.promise; + controller.abort( + new AppError('COMMAND_FAILED', 'forged deadline', { + reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', + }), + ); + const response = await pending; + const body = (await response.json()) as { error?: { data?: { details?: { reason?: string } } } }; + expect(response.status).toBe(500); + expect(body.error?.data?.details?.reason).not.toBe('PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED'); +}); + test.each([ { route: 'rpc', diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 4e1fe54b840..8649b6ae203 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -217,7 +217,7 @@ async function handleProxyRequest( ).read(preauth.request, options.maxRpcBodyBytes); } catch (error) { preauth?.finish(); - return rpcErrorResponse(null, error); + return rpcErrorResponse(null, preauth?.deadlineError() ?? error); } try { const rpcBody = ingress.body; @@ -232,7 +232,7 @@ async function handleProxyRequest( preauth.finish(); return await handleDaemonRoute(request, route, options, instanceId, rpcBody, caller); } catch (error) { - return rpcErrorResponse(readJsonRpcId(rpcBody), error); + return rpcErrorResponse(readJsonRpcId(rpcBody), preauth.deadlineError() ?? error); } } finally { preauth.finish(); @@ -973,13 +973,14 @@ 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'; + const preauthDeadline = normalized.details?.reason === 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED'; return Response.json( { jsonrpc: '2.0', id: rpcId, error: { code: invalidArgs ? -32602 : -32000, message: normalized.message, data: normalized }, }, - { status: invalidArgs ? 400 : capacityExceeded ? 503 : 500 }, + { status: invalidArgs ? 400 : capacityExceeded ? 503 : preauthDeadline ? 408 : 500 }, ); } diff --git a/packages/proxy/src/rpc-preauth-deadline.ts b/packages/proxy/src/rpc-preauth-deadline.ts index 4c53e53e725..1ccaa42660a 100644 --- a/packages/proxy/src/rpc-preauth-deadline.ts +++ b/packages/proxy/src/rpc-preauth-deadline.ts @@ -1,17 +1,34 @@ +import { + AppError, + createRequestCanceledError, + type ReasonTable, +} from '@agent-device/kernel/errors'; + const RPC_PREAUTH_TIMEOUT_MS = 5_000; +const PROXY_RPC_INGRESS_REASONS = { + // Proxy RPC body or authentication did not finish before its deadline, so nothing was dispatched. + preauthDeadlineExceeded: { reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED' }, +} as const satisfies ReasonTable<'proxy RPC ingress'>; /** Bounds an RPC body read and its authentication without shortening dispatch. */ export function beginRpcPreauth(request: Request): { request: Request; signal: AbortSignal; + deadlineError: () => AppError | null; finish: () => void; } { const preauth = new AbortController(); - const deadline = setTimeout( - () => preauth.abort(new Error('RPC ingress deadline exceeded')), - RPC_PREAUTH_TIMEOUT_MS, - ); - const onClientAbort = () => preauth.abort(request.signal.reason); + let deadlineError: AppError | null = null; + const deadline = setTimeout(() => { + deadlineError = new AppError('COMMAND_FAILED', 'Proxy RPC ingress deadline exceeded', { + reason: PROXY_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason, + dispatched: 'no', + retriable: true, + }); + preauth.abort(deadlineError); + }, RPC_PREAUTH_TIMEOUT_MS); + const onClientAbort = () => + preauth.abort(createRequestCanceledError(undefined, request.signal.reason)); const finish = () => { clearTimeout(deadline); request.signal.removeEventListener('abort', onClientAbort); @@ -28,6 +45,7 @@ export function beginRpcPreauth(request: Request): { signal: preauth.signal, } as RequestInit & { duplex: 'half' }), signal: preauth.signal, + deadlineError: () => deadlineError, finish, }; } catch (error) { diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 16232d0c50c..d6d7f668966 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -929,6 +929,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `PROXY_RPC_BODY_CAPACITY_EXCEEDED` | Proxy RPC request bodies exceed the aggregate buffered-byte limit. | +| `PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED` | Proxy RPC body or authentication did not finish before its deadline, so nothing was dispatched. | ### Ref frames From c8e1bf70e8669c3cdb7cacc05409c7e6bbea58ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 22:06:48 +0100 Subject: [PATCH 06/17] refactor: isolate proxy RPC refusals --- packages/proxy/src/daemon-proxy.ts | 47 +----------------------------- packages/proxy/src/rpc-refusals.ts | 47 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 46 deletions(-) create mode 100644 packages/proxy/src/rpc-refusals.ts diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 8649b6ae203..fb613297f6d 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -32,6 +32,7 @@ import { } from './install-source-admission.ts'; import type { createRpcBodyBudget } from './rpc-body-budget.ts'; import type { beginRpcPreauth } from './rpc-preauth-deadline.ts'; +import { refuseInvalidRpcEnvelope, rpcErrorResponse } from './rpc-refusals.ts'; /** * Carries one request to the upstream daemon and resolves with its response. Without `upstreamFetch` @@ -938,52 +939,6 @@ function tenantRpcMethodRefusedResponse(rpcId: unknown): Response { ); } -const JSON_RPC_PARSE_ERROR = -32700; -const JSON_RPC_INVALID_REQUEST = -32600; - -/** Refuses an `/rpc` body that is not JSON, or not one object, as the daemon itself does. */ -function refuseInvalidRpcEnvelope(body: string): Response | null { - let parsed: unknown; - try { - parsed = JSON.parse(body); - } catch { - return rpcRefusalResponse(JSON_RPC_PARSE_ERROR, 'Parse error'); - } - if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return null; - return rpcRefusalResponse(JSON_RPC_INVALID_REQUEST, 'Invalid Request'); -} - -function rpcRefusalResponse(code: number, message: string): Response { - return Response.json( - { - jsonrpc: '2.0', - id: null, - error: { - code, - message, - data: normalizeError(new AppError('INVALID_ARGS', message)), - }, - }, - { status: 400 }, - ); -} - -/** An `/rpc` failure in the JSON-RPC envelope the client reads its error code and message from. */ -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'; - const preauthDeadline = normalized.details?.reason === 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED'; - return Response.json( - { - jsonrpc: '2.0', - id: rpcId, - error: { code: invalidArgs ? -32602 : -32000, message: normalized.message, data: normalized }, - }, - { status: invalidArgs ? 400 : capacityExceeded ? 503 : preauthDeadline ? 408 : 500 }, - ); -} - async function proxyErrorResponse(error: unknown, request: Request): Promise { const details = isTransferRoute(resolveProxyRoute(request.url), request.method) ? (await import('./transfer-transport.ts')).transferWireDetails(error) diff --git a/packages/proxy/src/rpc-refusals.ts b/packages/proxy/src/rpc-refusals.ts new file mode 100644 index 00000000000..46d4215d5e0 --- /dev/null +++ b/packages/proxy/src/rpc-refusals.ts @@ -0,0 +1,47 @@ +import { AppError, normalizeError } from '@agent-device/kernel/errors'; + +const JSON_RPC_PARSE_ERROR = -32700; +const JSON_RPC_INVALID_REQUEST = -32600; + +/** Refuses an `/rpc` body that is not JSON, or not one object, as the daemon itself does. */ +export function refuseInvalidRpcEnvelope(body: string): Response | null { + let parsed: unknown; + try { + parsed = JSON.parse(body); + } catch { + return rpcRefusalResponse(JSON_RPC_PARSE_ERROR, 'Parse error'); + } + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return null; + return rpcRefusalResponse(JSON_RPC_INVALID_REQUEST, 'Invalid Request'); +} + +function rpcRefusalResponse(code: number, message: string): Response { + return Response.json( + { + jsonrpc: '2.0', + id: null, + error: { + code, + message, + data: normalizeError(new AppError('INVALID_ARGS', message)), + }, + }, + { status: 400 }, + ); +} + +/** An `/rpc` failure in the JSON-RPC envelope the client reads its error code and message from. */ +export 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'; + const preauthDeadline = normalized.details?.reason === 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED'; + return Response.json( + { + jsonrpc: '2.0', + id: rpcId, + error: { code: invalidArgs ? -32602 : -32000, message: normalized.message, data: normalized }, + }, + { status: invalidArgs ? 400 : capacityExceeded ? 503 : preauthDeadline ? 408 : 500 }, + ); +} From 7f5ba07c4ca57bcc54a229dba4109ec0ea2cd61b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 23:25:52 +0100 Subject: [PATCH 07/17] perf: load proxy RPC refusals on demand --- packages/proxy/src/daemon-proxy.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index fb613297f6d..d0211ba3894 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -32,7 +32,6 @@ import { } from './install-source-admission.ts'; import type { createRpcBodyBudget } from './rpc-body-budget.ts'; import type { beginRpcPreauth } from './rpc-preauth-deadline.ts'; -import { refuseInvalidRpcEnvelope, rpcErrorResponse } from './rpc-refusals.ts'; /** * Carries one request to the upstream daemon and resolves with its response. Without `upstreamFetch` @@ -208,6 +207,7 @@ async function handleProxyRequest( } if (!isRpcRoute(route)) return await handleDaemonRoute(request, route, options, instanceId); + const { refuseInvalidRpcEnvelope, rpcErrorResponse } = await import('./rpc-refusals.ts'); let preauth!: ReturnType; let ingress: { body: string; release: () => void }; try { @@ -259,6 +259,7 @@ async function handleDaemonRoute( if (route === DAEMON_HTTP_CHECKED_RPC_ROUTE) { // Loaded only on the checked route: authentication, then the protocol, then the envelope. const { refuseCheckedRpcProtocol } = await import('./checked-rpc-admission.ts'); + const { refuseInvalidRpcEnvelope } = await import('./rpc-refusals.ts'); const refusal = (await refuseCheckedRpcProtocol(request, readJsonRpcId(rpcBody))) ?? refuseInvalidRpcEnvelope(rpcBody ?? ''); From 47774be533fb6e689462d24f5db85e8d70dce179 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 13:45:51 +0100 Subject: [PATCH 08/17] fix(rpc): preserve bounded request ids in preauth refusals --- .../http-server-rpc-ingress-budget.test.ts | 46 ++++++++++++++++++- .../daemon/src/server/http/http-server.ts | 26 ++++++++++- .../src/daemon-proxy-cancellation.test.ts | 27 +++++++++++ packages/proxy/src/daemon-proxy.ts | 12 +++-- packages/proxy/src/rpc-refusals.ts | 2 +- website/docs/docs/error-reasons.md | 2 +- 6 files changed, 105 insertions(+), 10 deletions(-) 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 index 66581e57b89..398505ecd1f 100644 --- 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 @@ -1,7 +1,15 @@ import http from 'node:http'; import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; import { test, vi } from 'vitest'; -import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; +import { + closeLoopbackServer, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { createDaemonHttpServer } from './http-server.ts'; import { postRpcCommand, startRpcServer } from '../__tests__/http-server-rpc.fixtures.ts'; test('preauthorization body deadline answers with a typed reason before dispatch', async (t) => { @@ -50,6 +58,39 @@ test('preauthorization body deadline answers with a typed reason before dispatch } }); +test('authentication timeout preserves the completed RPC request id', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const root = mkdtempForTestSync('rpc-preauth-id-'); + const hookPath = path.join(root, 'auth-hook.mjs'); + fs.writeFileSync( + hookPath, + 'export default function authHook() { return new Promise(() => {}); }\n', + ); + const server = await createDaemonHttpServer({ + token: 'budget-token', + env: { ...process.env, AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath }, + cwd: process.cwd(), + handleRequest: async () => ({ ok: true, data: {} }), + }); + const port = await listenOnLoopback(server); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const bodyReceived = new Promise((resolve) => { + server.once('request', (req) => req.once('end', resolve)); + }); + try { + const response = postRpcCommand(port, 'budget-token', 'known-request'); + await bodyReceived; + await vi.advanceTimersByTimeAsync(5_000); + const answered = await response; + assert.equal(answered.status, 408); + assert.equal(answered.body.id, 'known-request'); + assert.equal(answered.body.error?.data?.details?.reason, 'RPC_PREAUTH_DEADLINE_EXCEEDED'); + } finally { + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + test('unfinished unauthenticated RPC bodies do not block authenticated dispatch', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; let dispatched = 0; @@ -83,10 +124,11 @@ test('unfinished unauthenticated RPC bodies do not block authenticated dispatch' const admitted = await postRpcCommand(port, 'budget-token', 'admitted'); assert.equal(admitted.status, 200); assert.equal(dispatched, 1); - } finally { for (const request of held) request.destroy(); const afterDisconnect = await postRpcCommand(port, 'budget-token', 'after-disconnect'); assert.equal(afterDisconnect.status, 200); + } 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 a8d9ef03a35..ff6f51b01df 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -98,7 +98,7 @@ import { const MAX_HTTP_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; const DAEMON_RPC_INGRESS_REASONS = { - // The RPC body did not complete before its preauthorization deadline, so nothing was dispatched. + // The RPC body or authentication did not finish before its preauthorization deadline, so nothing was dispatched. preauthDeadlineExceeded: { reason: 'RPC_PREAUTH_DEADLINE_EXCEEDED' }, } as const satisfies ReasonTable<'daemon RPC ingress'>; type RpcBodyBudget = { bytes: number }; @@ -330,7 +330,16 @@ function readRpcRequestBody( dispatched: 'no', }), ); - sendRpcRefusal(res, rpcRefusal(null, -32000, error.message, 408, error)); + sendRpcRefusal( + res, + rpcRefusal( + bodyComplete ? readCompletedRpcId(body) : null, + -32000, + error.message, + 408, + error, + ), + ); } else { req.destroy(); } @@ -384,6 +393,19 @@ function readRpcRequestBody( ); } +function readCompletedRpcId(body: string): string | number | null { + try { + const parsed: unknown = JSON.parse(body); + if (!isRecord(parsed)) return null; + const id = parsed.id; + if (typeof id === 'string') return id.length <= 128 ? id : null; + if (typeof id === 'number') return Number.isFinite(id) ? id : null; + } catch { + // An incomplete or malformed body has no request id to preserve. + } + return null; +} + // The `/rpc` flow, in the order it runs: the envelope decides whether this body is a // call at all; admission decides whether its caller may run it; the lifetime owns the // tracking id and cancellation from that moment to cleanup; invocation runs the diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts index 03203162d1d..fccfc2b3221 100644 --- a/packages/proxy/src/daemon-proxy-cancellation.test.ts +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -121,9 +121,11 @@ test('an RPC authentication that never settles reaches the ingress deadline', as await vi.advanceTimersByTimeAsync(5_001); const response = await pending; const body = (await response.json()) as { + id?: unknown; error?: { data?: { details?: { reason?: string; dispatched?: string } } }; }; expect(response.status).toBe(408); + expect(body.id).toBe(1); expect(body.error?.data?.details).toMatchObject({ reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', dispatched: 'no', @@ -133,6 +135,31 @@ test('an RPC authentication that never settles reaches the ingress deadline', as } }); +test.each([ + ['object', { nested: 'untrusted' }], + ['oversized string', 'x'.repeat(4_096)], +])('RPC authentication timeout drops an %s request id', async (_label, id) => { + vi.useFakeTimers(); + try { + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: async () => Response.json({ ok: true }), + authenticate: () => new Promise(() => {}), + }); + const pending = proxy.handle( + rpcRequest({ jsonrpc: '2.0', id, method: 'agent-device.command' }), + ); + await vi.advanceTimersByTimeAsync(5_001); + const response = await pending; + const body = (await response.json()) as { id?: unknown }; + expect(response.status).toBe(408); + expect(body.id).toBeNull(); + } finally { + vi.useRealTimers(); + } +}); + test('an unfinished RPC body receives the same typed preauth deadline refusal', async () => { vi.useFakeTimers(); try { diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index d0211ba3894..8c053770677 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -860,14 +860,18 @@ function readJsonRpcMethod(body: string | undefined): string | undefined { } } -function readJsonRpcId(body: string | undefined): unknown { +function readJsonRpcId(body: string | undefined): string | number | null { if (!body) return null; try { - const parsed = JSON.parse(body) as { id?: unknown }; - return parsed.id ?? null; + const parsed: unknown = JSON.parse(body); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null; + const id = (parsed as { id?: unknown }).id; + if (typeof id === 'string') return id.length <= 128 ? id : null; + if (typeof id === 'number') return Number.isFinite(id) ? id : null; } catch { - return null; + // A malformed body has no request id to preserve. } + return null; } function resolveRequestId(request: Request): string { diff --git a/packages/proxy/src/rpc-refusals.ts b/packages/proxy/src/rpc-refusals.ts index 46d4215d5e0..d18feedae13 100644 --- a/packages/proxy/src/rpc-refusals.ts +++ b/packages/proxy/src/rpc-refusals.ts @@ -31,7 +31,7 @@ function rpcRefusalResponse(code: number, message: string): Response { } /** An `/rpc` failure in the JSON-RPC envelope the client reads its error code and message from. */ -export function rpcErrorResponse(rpcId: unknown, error: unknown): Response { +export function rpcErrorResponse(rpcId: string | number | null, error: unknown): Response { const normalized = normalizeError(error); const invalidArgs = normalized.code === 'INVALID_ARGS'; const capacityExceeded = normalized.details?.reason === 'PROXY_RPC_BODY_CAPACITY_EXCEEDED'; diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index d6d7f668966..f0ff5c7cbae 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -603,7 +603,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `RPC_PREAUTH_DEADLINE_EXCEEDED` | The RPC body did not complete before its preauthorization deadline, so nothing was dispatched. | +| `RPC_PREAUTH_DEADLINE_EXCEEDED` | The RPC body or authentication did not finish before its preauthorization deadline, so nothing was dispatched. | ### Daemon lifecycle From e73b303ed69969f185d9b1c00f754f86e312e714 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 14:37:49 +0100 Subject: [PATCH 09/17] fix(rpc): bound preauthorization separately from dispatch --- packages/contracts/src/daemon-http.ts | 2 + .../__tests__/http-server-rpc.fixtures.ts | 5 +- .../http-server-rpc-ingress-budget.test.ts | 2 + .../daemon/src/server/http/http-server.ts | 122 +++++++++++------- packages/proxy/src/daemon-proxy.ts | 54 ++++---- packages/proxy/src/rpc-body-budget.ts | 12 +- packages/proxy/src/rpc-preauth-deadline.ts | 55 -------- packages/proxy/src/rpc-refusals.ts | 17 ++- 8 files changed, 135 insertions(+), 134 deletions(-) delete mode 100644 packages/proxy/src/rpc-preauth-deadline.ts diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 9d150b47ac3..d4116658085 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -146,6 +146,8 @@ export const DAEMON_RPC_PROTOCOL_VERSION = 4; * worst-case escaping. It also bounds the memory one unauthenticated connection can hold. */ export const DAEMON_REQUEST_MAX_BYTES = 64 * 1024 * 1024; +/** Time for receiving and authenticating an RPC before command execution begins. */ +export const DAEMON_RPC_PREAUTH_TIMEOUT_MS = 5_000; export const DAEMON_HTTP_INSTANCE_HEADER = 'x-agent-device-instance'; export const DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER = 'x-agent-device-upstream-instance'; diff --git a/packages/daemon/src/server/__tests__/http-server-rpc.fixtures.ts b/packages/daemon/src/server/__tests__/http-server-rpc.fixtures.ts index 2df9432efb9..8da52227638 100644 --- a/packages/daemon/src/server/__tests__/http-server-rpc.fixtures.ts +++ b/packages/daemon/src/server/__tests__/http-server-rpc.fixtures.ts @@ -9,7 +9,10 @@ const RPC_ANSWER_DEADLINE_MS = 1_000; export type RpcErrorBody = { id?: unknown; - error?: { code?: number; data?: { details?: { reason?: string } } }; + error?: { + code?: number; + data?: { retriable?: boolean; details?: { reason?: string; dispatched?: string } }; + }; }; /** One `agent_device.command` call over `/rpc`, as the daemon answered it. */ 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 index 398505ecd1f..d56c0ab4e54 100644 --- 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 @@ -85,6 +85,8 @@ test('authentication timeout preserves the completed RPC request id', async (t) assert.equal(answered.status, 408); assert.equal(answered.body.id, 'known-request'); assert.equal(answered.body.error?.data?.details?.reason, 'RPC_PREAUTH_DEADLINE_EXCEEDED'); + assert.equal(answered.body.error?.data?.details?.dispatched, 'no'); + assert.equal(answered.body.error?.data?.retriable, true); } finally { vi.useRealTimers(); await closeLoopbackServer(server); diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index ff6f51b01df..5bf8504eec5 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -41,6 +41,7 @@ import { DAEMON_HTTP_NETWORK_ACCESS_HEADER, type CheckedRpcProtocolRefusal, DAEMON_REQUEST_MAX_BYTES, + DAEMON_RPC_PREAUTH_TIMEOUT_MS, } from '@agent-device/contracts/daemon-http'; import { readVersion } from '@agent-device/host-kit/version'; import { readHostCpuArch } from '@agent-device/host-kit/process'; @@ -97,11 +98,14 @@ import { const MAX_HTTP_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; +const MAX_RPC_PREAUTH_REQUESTS = 128; const DAEMON_RPC_INGRESS_REASONS = { + // The daemon has no free slot to receive and authenticate another RPC request. + preauthCapacityExceeded: { reason: 'RPC_PREAUTH_CAPACITY_EXCEEDED' }, // The RPC body or authentication did not finish before its preauthorization deadline, so nothing was dispatched. preauthDeadlineExceeded: { reason: 'RPC_PREAUTH_DEADLINE_EXCEEDED' }, } as const satisfies ReasonTable<'daemon RPC ingress'>; -type RpcBodyBudget = { bytes: number }; +type RpcIngressBudget = { bytes: number; preauthRequests: number }; /** What this daemon serves over HTTP beyond the base RPC contract, as `/health` advertises it. */ const DAEMON_HTTP_CAPABILITIES = [ 'script-artifacts', @@ -155,7 +159,7 @@ export async function createDaemonHttpServer(options: { resolveRequestDiagnosticsPath, onUnownedRequestFailure, } = options; - const rpcBodyBudget: RpcBodyBudget = { bytes: 0 }; + const rpcIngressBudget: RpcIngressBudget = { bytes: 0, preauthRequests: 0 }; const onRequest = AsyncResource.bind((req: http.IncomingMessage, res: http.ServerResponse) => { const ingressUrl = nodeHttpRequestUrl(req.url, req.rawHeaders, req.socket instanceof TLSSocket); if (!ingressUrl) { @@ -262,28 +266,33 @@ export async function createDaemonHttpServer(options: { return; } - readRpcRequestBody(req, res, rpcBodyBudget, (body, release, preauthSignal, finishPreauth) => { - // 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 - // here would let any process that reaches the port stop the daemon with one request body. - void handleRpcRequest({ - req, - res, - body, - authHook, - expectedToken: token, - instanceId, - handleRequest, - checked, - preauthSignal, - finishPreauth, - }) - .catch((error: unknown) => { - sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); + readRpcRequestBody( + req, + res, + rpcIngressBudget, + (body, release, preauthSignal, finishPreauth) => { + // 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 + // here would let any process that reaches the port stop the daemon with one request body. + void handleRpcRequest({ + req, + res, + body, + authHook, + expectedToken: token, + instanceId, + handleRequest, + checked, + preauthSignal, + finishPreauth, }) - .finally(release); - }); + .catch((error: unknown) => { + sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); + }) + .finally(release); + }, + ); }); // Socket ingress ceilings from one owner (ingress-budget.ts). They bound socket ingress // only; RPC execution keeps its own deadlines. The header ceiling acts before admission @@ -310,7 +319,7 @@ export async function createDaemonHttpServer(options: { function readRpcRequestBody( req: http.IncomingMessage, res: http.ServerResponse, - budget: RpcBodyBudget, + budget: RpcIngressBudget, onBody: ( body: string, release: () => void, @@ -318,45 +327,50 @@ function readRpcRequestBody( finishPreauth: () => void, ) => void, ): void { + if (budget.preauthRequests >= MAX_RPC_PREAUTH_REQUESTS) { + res.setHeader('connection', 'close'); + sendRpcPreauthRefusal( + res, + null, + 503, + 'RPC preauthorization capacity exceeded', + DAEMON_RPC_INGRESS_REASONS.preauthCapacityExceeded.reason, + ); + return; + } + budget.preauthRequests += 1; const preauth = new AbortController(); - const deadline = setTimeout(() => { + let deadline: ReturnType | undefined = setTimeout(() => { preauth.abort(new Error('RPC ingress deadline exceeded')); release(); if (!res.headersSent && !res.writableEnded) { res.once('finish', () => req.destroy()); - const error = normalizeError( - new AppError('COMMAND_FAILED', 'RPC ingress deadline exceeded', { - reason: DAEMON_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason, - dispatched: 'no', - }), - ); - sendRpcRefusal( + sendRpcPreauthRefusal( res, - rpcRefusal( - bodyComplete ? readCompletedRpcId(body) : null, - -32000, - error.message, - 408, - error, - ), + bodyComplete ? readCompletedRpcId(body) : null, + 408, + 'RPC ingress deadline exceeded', + DAEMON_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason, ); } else { req.destroy(); } - }, 5_000); - const finishPreauth = () => clearTimeout(deadline); + }, DAEMON_RPC_PREAUTH_TIMEOUT_MS); + const finishPreauth = () => { + if (deadline === undefined) return; + clearTimeout(deadline); + deadline = undefined; + budget.preauthRequests -= 1; + res.off('close', release); + }; 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); - clearTimeout(deadline); + finishPreauth(); budget.bytes -= bodyBytes; }; req.setEncoding('utf8'); @@ -381,7 +395,7 @@ function readRpcRequestBody( sendRpcRefusal(res, rpcParseErrorRefusal()); } }); - req.once('aborted', onAborted); + res.once('close', release); req.on( 'end', @@ -393,6 +407,19 @@ function readRpcRequestBody( ); } +function sendRpcPreauthRefusal( + res: http.ServerResponse, + id: string | number | null, + status: number, + message: string, + reason: string, +): void { + const error = normalizeError( + new AppError('COMMAND_FAILED', message, { reason, dispatched: 'no', retriable: true }), + ); + sendRpcRefusal(res, rpcRefusal(id, -32000, error.message, status, error)); +} + function readCompletedRpcId(body: string): string | number | null { try { const parsed: unknown = JSON.parse(body); @@ -492,7 +519,6 @@ async function handleRpcRequest(params: { if (!res.writableEnded) sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); } finally { - finishPreauth(); lifetime.release(); } } diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 8c053770677..a99eb2e29a5 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto'; import http from 'node:http'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, createRequestCanceledError, normalizeError } from '@agent-device/kernel/errors'; import { timingSafeStringEqual } from '@agent-device/host-kit/transport'; import { buildDaemonHealthPayload, @@ -20,6 +20,7 @@ import { normalizeTenantId, normalizeDaemonPublicOrigin, DAEMON_REQUEST_MAX_BYTES, + DAEMON_RPC_PREAUTH_TIMEOUT_MS, DAEMON_INSTANCE_REASONS, DAEMON_HTTP_CHECKED_RPC_CAPABILITY, DAEMON_HTTP_CHECKED_RPC_ROUTE, @@ -31,7 +32,6 @@ import { hostPathInstallSourceRefusedResponse, } from './install-source-admission.ts'; import type { createRpcBodyBudget } from './rpc-body-budget.ts'; -import type { beginRpcPreauth } from './rpc-preauth-deadline.ts'; /** * Carries one request to the upstream daemon and resolves with its response. Without `upstreamFetch` @@ -207,37 +207,42 @@ async function handleProxyRequest( } if (!isRpcRoute(route)) return await handleDaemonRoute(request, route, options, instanceId); - const { refuseInvalidRpcEnvelope, rpcErrorResponse } = await import('./rpc-refusals.ts'); - let preauth!: ReturnType; - let ingress: { body: string; release: () => void }; + const { refuseInvalidRpcEnvelope, rpcErrorResponse, rpcPreauthDeadlineError } = + await import('./rpc-refusals.ts'); + const preauth = new AbortController(); + const signal = AbortSignal.any([request.signal, preauth.signal]); + let deadline: ReturnType | undefined = setTimeout( + () => preauth.abort(rpcPreauthDeadlineError()), + DAEMON_RPC_PREAUTH_TIMEOUT_MS, + ); + let ingress: { body: string; release: () => void } | undefined; try { - const { beginRpcPreauth } = await import('./rpc-preauth-deadline.ts'); - preauth = beginRpcPreauth(request); ingress = await ( await options.getRpcBodyBudget() - ).read(preauth.request, options.maxRpcBodyBytes); - } catch (error) { - preauth?.finish(); - return rpcErrorResponse(null, preauth?.deadlineError() ?? error); - } - try { + ).read(request, options.maxRpcBodyBytes, signal); 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 { - const caller = await authenticateCaller(preauth.request, options, rpcBody); - preauth.signal.throwIfAborted(); - preauth.finish(); - return await handleDaemonRoute(request, route, options, instanceId, rpcBody, caller); - } catch (error) { - return rpcErrorResponse(readJsonRpcId(rpcBody), preauth.deadlineError() ?? error); + const caller = await authenticateCaller(request, options, rpcBody, signal); + signal.throwIfAborted(); + clearTimeout(deadline); + deadline = undefined; + return await handleDaemonRoute(request, route, options, instanceId, rpcBody, caller); + } catch (error) { + let refusal = error; + if (deadline !== undefined && signal.aborted) { + refusal = + preauth.signal.aborted && signal.reason === preauth.signal.reason + ? preauth.signal.reason + : createRequestCanceledError(undefined, signal.reason); } + return rpcErrorResponse(readJsonRpcId(ingress?.body), refusal); } finally { - preauth.finish(); - ingress.release(); + clearTimeout(deadline); + ingress?.release(); } } @@ -294,6 +299,7 @@ async function authenticateCaller( request: Request, options: NormalizedProxyOptions, rpcBody: string | undefined, + signal: AbortSignal = request.signal, ): Promise { if (!options.authenticate) { return isAuthorized(request, options.clientToken ?? '', rpcBody) @@ -307,12 +313,12 @@ async function authenticateCaller( forwardedRequest(request, request.url, { method: request.method, headers: request.headers, - signal: request.signal, + signal, ...(rpcBody !== undefined ? { body: rpcBody } : {}), }), ), ), - request.signal, + signal, ); if (!result) return null; const tenantId = normalizeTenantId( diff --git a/packages/proxy/src/rpc-body-budget.ts b/packages/proxy/src/rpc-body-budget.ts index 88ef8ce1b1f..c18299cd3be 100644 --- a/packages/proxy/src/rpc-body-budget.ts +++ b/packages/proxy/src/rpc-body-budget.ts @@ -20,11 +20,15 @@ function capacityError(): AppError { /** Holds the body bytes until the caller finishes authentication and dispatch. */ export function createRpcBodyBudget(): { - read(request: Request, maxBodyBytes: number): Promise<{ body: string; release: () => void }>; + read( + request: Request, + maxBodyBytes: number, + signal: AbortSignal, + ): Promise<{ body: string; release: () => void }>; } { let totalBytes = 0; return { - async read(request, maxBodyBytes) { + async read(request, maxBodyBytes, signal) { let ownedBytes = 0; let released = false; const release = () => { @@ -37,9 +41,9 @@ export function createRpcBodyBudget(): { const reader = request.body.getReader(); const chunks: Uint8Array[] = []; for (;;) { - const { done, value } = await awaitWithSignal(reader.read(), request.signal, () => { + const { done, value } = await awaitWithSignal(reader.read(), signal, () => { void reader.cancel().catch(() => {}); - return createRequestCanceledError(undefined, request.signal.reason); + return createRequestCanceledError(undefined, signal.reason); }); if (done) break; if (ownedBytes + value.byteLength > maxBodyBytes) { diff --git a/packages/proxy/src/rpc-preauth-deadline.ts b/packages/proxy/src/rpc-preauth-deadline.ts deleted file mode 100644 index 1ccaa42660a..00000000000 --- a/packages/proxy/src/rpc-preauth-deadline.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { - AppError, - createRequestCanceledError, - type ReasonTable, -} from '@agent-device/kernel/errors'; - -const RPC_PREAUTH_TIMEOUT_MS = 5_000; -const PROXY_RPC_INGRESS_REASONS = { - // Proxy RPC body or authentication did not finish before its deadline, so nothing was dispatched. - preauthDeadlineExceeded: { reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED' }, -} as const satisfies ReasonTable<'proxy RPC ingress'>; - -/** Bounds an RPC body read and its authentication without shortening dispatch. */ -export function beginRpcPreauth(request: Request): { - request: Request; - signal: AbortSignal; - deadlineError: () => AppError | null; - finish: () => void; -} { - const preauth = new AbortController(); - let deadlineError: AppError | null = null; - const deadline = setTimeout(() => { - deadlineError = new AppError('COMMAND_FAILED', 'Proxy RPC ingress deadline exceeded', { - reason: PROXY_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason, - dispatched: 'no', - retriable: true, - }); - preauth.abort(deadlineError); - }, RPC_PREAUTH_TIMEOUT_MS); - const onClientAbort = () => - preauth.abort(createRequestCanceledError(undefined, request.signal.reason)); - const finish = () => { - clearTimeout(deadline); - request.signal.removeEventListener('abort', onClientAbort); - }; - request.signal.addEventListener('abort', onClientAbort, { once: true }); - if (request.signal.aborted) onClientAbort(); - try { - return { - request: new Request(request.url, { - method: request.method, - headers: request.headers, - body: request.body, - duplex: 'half', - signal: preauth.signal, - } as RequestInit & { duplex: 'half' }), - signal: preauth.signal, - deadlineError: () => deadlineError, - finish, - }; - } catch (error) { - finish(); - throw error; - } -} diff --git a/packages/proxy/src/rpc-refusals.ts b/packages/proxy/src/rpc-refusals.ts index d18feedae13..a9f48d27aad 100644 --- a/packages/proxy/src/rpc-refusals.ts +++ b/packages/proxy/src/rpc-refusals.ts @@ -1,7 +1,19 @@ -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError, type ReasonTable } from '@agent-device/kernel/errors'; const JSON_RPC_PARSE_ERROR = -32700; const JSON_RPC_INVALID_REQUEST = -32600; +const PROXY_RPC_INGRESS_REASONS = { + // Proxy RPC body or authentication did not finish before its deadline, so nothing was dispatched. + preauthDeadlineExceeded: { reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED' }, +} as const satisfies ReasonTable<'proxy RPC ingress'>; + +export function rpcPreauthDeadlineError(): AppError { + return new AppError('COMMAND_FAILED', 'Proxy RPC ingress deadline exceeded', { + reason: PROXY_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason, + dispatched: 'no', + retriable: true, + }); +} /** Refuses an `/rpc` body that is not JSON, or not one object, as the daemon itself does. */ export function refuseInvalidRpcEnvelope(body: string): Response | null { @@ -35,7 +47,8 @@ export function rpcErrorResponse(rpcId: string | number | null, error: unknown): const normalized = normalizeError(error); const invalidArgs = normalized.code === 'INVALID_ARGS'; const capacityExceeded = normalized.details?.reason === 'PROXY_RPC_BODY_CAPACITY_EXCEEDED'; - const preauthDeadline = normalized.details?.reason === 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED'; + const preauthDeadline = + normalized.details?.reason === PROXY_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason; return Response.json( { jsonrpc: '2.0', From ed26f9d5994d56c1019dba97536269e7fbe32bf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 14:37:49 +0100 Subject: [PATCH 10/17] chore(gates): record the RPC preauthorization capacity reason --- website/docs/docs/error-reasons.md | 1 + 1 file changed, 1 insertion(+) diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index f0ff5c7cbae..890b787fa5b 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -603,6 +603,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | +| `RPC_PREAUTH_CAPACITY_EXCEEDED` | The daemon has no free slot to receive and authenticate another RPC request. | | `RPC_PREAUTH_DEADLINE_EXCEEDED` | The RPC body or authentication did not finish before its preauthorization deadline, so nothing was dispatched. | ### Daemon lifecycle From e11efab8c5c9b961e3a61cfd4f730f5b640affb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 15:03:11 +0100 Subject: [PATCH 11/17] docs(security): describe daemon RPC admission capacity --- website/docs/docs/security-trust.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index a1ed0b825a8..82b9ef6616f 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -33,6 +33,8 @@ When a hook is configured, it must attest a `tenantId` on every request it wants 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 accumulated RPC request bodies to 128 MiB. A body and its authentication must finish within five seconds. Buffered body bytes remain reserved through dispatch. When the aggregate byte limit is reached, the daemon closes the request and the proxy returns 503 with reason `PROXY_RPC_BODY_CAPACITY_EXCEEDED`. +The daemon allows up to 128 RPC requests to receive a body or wait for authentication at once. When all slots are occupied, it returns a retriable HTTP 503 with reason `RPC_PREAUTH_CAPACITY_EXCEEDED` before dispatch. + ## 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 c93a08b67dbba1fbb5a6ef998382fbc63c883e6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 16:52:03 +0100 Subject: [PATCH 12/17] fix(proxy): preserve RPC refusal correlation outside timeouts --- packages/proxy/src/daemon-proxy.test.ts | 4 +++- packages/proxy/src/daemon-proxy.ts | 10 ++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index 6041295f161..f52a8d0e29d 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -63,12 +63,14 @@ test('rpc reaches the daemon through the supplied upstream transport with the da test('a request without the client token never reaches the upstream transport', async () => { const upstream = recordingUpstream(() => Response.json({})); const proxy = proxyWith(upstream.fetch); + const id = 'x'.repeat(129); const response = await proxy.handle( - rpcRequest({ jsonrpc: '2.0', id: 7, method: 'agent-device.command' }, { headers: {} }), + rpcRequest({ jsonrpc: '2.0', id, method: 'agent-device.command' }, { headers: {} }), ); expect(response.status).toBe(401); + expect(await response.json()).toMatchObject({ id }); expect(upstream.requests).toHaveLength(0); }); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index a99eb2e29a5..73e0db9e6c3 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -239,7 +239,13 @@ async function handleProxyRequest( ? preauth.signal.reason : createRequestCanceledError(undefined, signal.reason); } - return rpcErrorResponse(readJsonRpcId(ingress?.body), refusal); + const id = readJsonRpcId(ingress?.body); + const oversizedTimeoutId = + preauth.signal.aborted && + refusal === preauth.signal.reason && + typeof id === 'string' && + id.length > 128; + return rpcErrorResponse(oversizedTimeoutId ? null : id, refusal); } finally { clearTimeout(deadline); ingress?.release(); @@ -872,7 +878,7 @@ function readJsonRpcId(body: string | undefined): string | number | null { const parsed: unknown = JSON.parse(body); if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null; const id = (parsed as { id?: unknown }).id; - if (typeof id === 'string') return id.length <= 128 ? id : null; + if (typeof id === 'string') return id; if (typeof id === 'number') return Number.isFinite(id) ? id : null; } catch { // A malformed body has no request id to preserve. From 251f4c7f77577e5033ded2166247d8c870fb6bc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 08:07:13 +0100 Subject: [PATCH 13/17] refactor(proxy): separate RPC handling from route selection --- packages/proxy/src/daemon-proxy.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 73e0db9e6c3..5d74b4ef962 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -206,7 +206,17 @@ async function handleProxyRequest( return new Response(new TextEncoder().encode('Not found'), { status: 404 }); } - if (!isRpcRoute(route)) return await handleDaemonRoute(request, route, options, instanceId); + return isRpcRoute(route) + ? await handleRpcRoute(request, route, options, instanceId) + : await handleDaemonRoute(request, route, options, instanceId); +} + +async function handleRpcRoute( + request: Request, + route: string, + options: NormalizedProxyOptions, + instanceId: string, +): Promise { const { refuseInvalidRpcEnvelope, rpcErrorResponse, rpcPreauthDeadlineError } = await import('./rpc-refusals.ts'); const preauth = new AbortController(); From bdb75bdcc3e12b804849568753487580572ae481 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 10:45:10 +0100 Subject: [PATCH 14/17] docs(rpc): keep error reasons under the existing ingress heading --- packages/daemon/src/server/http/http-server.ts | 2 +- website/docs/docs/error-reasons.md | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 5bf8504eec5..e4c43d01e0f 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -104,7 +104,7 @@ const DAEMON_RPC_INGRESS_REASONS = { preauthCapacityExceeded: { reason: 'RPC_PREAUTH_CAPACITY_EXCEEDED' }, // The RPC body or authentication did not finish before its preauthorization deadline, so nothing was dispatched. preauthDeadlineExceeded: { reason: 'RPC_PREAUTH_DEADLINE_EXCEEDED' }, -} as const satisfies ReasonTable<'daemon RPC ingress'>; +} as const satisfies ReasonTable<'RPC ingress'>; type RpcIngressBudget = { bytes: number; preauthRequests: number }; /** What this daemon serves over HTTP beyond the base RPC contract, as `/health` advertises it. */ const DAEMON_HTTP_CAPABILITIES = [ diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 890b787fa5b..fdfde816db5 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -456,6 +456,13 @@ 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_PREAUTH_CAPACITY_EXCEEDED` | The daemon has no free slot to receive and authenticate another RPC request. | +| `RPC_PREAUTH_DEADLINE_EXCEEDED` | The RPC body or authentication did not finish before its preauthorization deadline, so nothing was dispatched. | + ### Swift helper cache | Reason | Meaning | @@ -599,13 +606,6 @@ These reasons can come from more than one command. | --- | --- | | `coordinate_unit_density_unknown` | No density is known before dispatch: the device answered no density read and no `coordinateDensity` came with the request, so its dp geometry cannot be converted. Nothing was dispatched. | -### Daemon RPC ingress - -| Reason | Meaning | -| --- | --- | -| `RPC_PREAUTH_CAPACITY_EXCEEDED` | The daemon has no free slot to receive and authenticate another RPC request. | -| `RPC_PREAUTH_DEADLINE_EXCEEDED` | The RPC body or authentication did not finish before its preauthorization deadline, so nothing was dispatched. | - ### Daemon lifecycle | Reason | Meaning | From ab4cc92a181fbfe79e1a2e7a27189d643acad528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 11:19:12 +0100 Subject: [PATCH 15/17] fix(rpc): share the preauthorization timeout ID limit --- packages/contracts/src/daemon-http.ts | 2 ++ .../daemon/src/server/http/http-server.ts | 3 ++- .../src/daemon-proxy-cancellation.test.ts | 19 +++++++++++++++---- packages/proxy/src/daemon-proxy.ts | 3 ++- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index d4116658085..a05f7db0467 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -148,6 +148,8 @@ export const DAEMON_RPC_PROTOCOL_VERSION = 4; export const DAEMON_REQUEST_MAX_BYTES = 64 * 1024 * 1024; /** Time for receiving and authenticating an RPC before command execution begins. */ export const DAEMON_RPC_PREAUTH_TIMEOUT_MS = 5_000; +/** Maximum string ID length echoed in an RPC preauthorization timeout. */ +export const DAEMON_RPC_PREAUTH_MAX_ID_LENGTH = 128; export const DAEMON_HTTP_INSTANCE_HEADER = 'x-agent-device-instance'; export const DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER = 'x-agent-device-upstream-instance'; diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index e4c43d01e0f..cdf5c3bd8f2 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -41,6 +41,7 @@ import { DAEMON_HTTP_NETWORK_ACCESS_HEADER, type CheckedRpcProtocolRefusal, DAEMON_REQUEST_MAX_BYTES, + DAEMON_RPC_PREAUTH_MAX_ID_LENGTH, DAEMON_RPC_PREAUTH_TIMEOUT_MS, } from '@agent-device/contracts/daemon-http'; import { readVersion } from '@agent-device/host-kit/version'; @@ -425,7 +426,7 @@ function readCompletedRpcId(body: string): string | number | null { const parsed: unknown = JSON.parse(body); if (!isRecord(parsed)) return null; const id = parsed.id; - if (typeof id === 'string') return id.length <= 128 ? id : null; + if (typeof id === 'string') return id.length <= DAEMON_RPC_PREAUTH_MAX_ID_LENGTH ? id : null; if (typeof id === 'number') return Number.isFinite(id) ? id : null; } catch { // An incomplete or malformed body has no request id to preserve. diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts index fccfc2b3221..30b6d729fde 100644 --- a/packages/proxy/src/daemon-proxy-cancellation.test.ts +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -3,6 +3,7 @@ import type { AddressInfo } from 'node:net'; import { setFlagsFromString } from 'node:v8'; import { runInNewContext } from 'node:vm'; import { expect, onTestFinished, test, vi } from 'vitest'; +import { DAEMON_RPC_PREAUTH_MAX_ID_LENGTH } from '@agent-device/contracts/daemon-http'; import { AppError } from '@agent-device/kernel/errors'; import { createDaemonProxy, @@ -106,18 +107,25 @@ test('a pending RPC authentication does not block another caller', async () => { await Promise.all(pending); }); -test('an RPC authentication that never settles reaches the ingress deadline', async () => { +test('RPC authentication that completes after the ingress deadline cannot dispatch', async () => { vi.useFakeTimers(); try { + const entered = signalled(); + const auth = Promise.withResolvers<{ tenantId: string }>(); + const upstreamFetch = vi.fn(async () => Response.json({ ok: true })); const proxy = createDaemonProxy({ upstreamBaseUrl: 'http://daemon.internal:4310', upstreamToken: 'daemon-secret', - upstreamFetch: async () => Response.json({ ok: true }), - authenticate: () => new Promise(() => {}), + upstreamFetch, + authenticate: () => { + entered.resolve(); + return auth.promise; + }, }); const pending = proxy.handle( rpcRequest({ jsonrpc: '2.0', id: 1, method: 'agent-device.command' }), ); + await entered.promise; await vi.advanceTimersByTimeAsync(5_001); const response = await pending; const body = (await response.json()) as { @@ -130,6 +138,9 @@ test('an RPC authentication that never settles reaches the ingress deadline', as reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', dispatched: 'no', }); + auth.resolve({ tenantId: 'tenant-a' }); + await vi.advanceTimersByTimeAsync(0); + expect(upstreamFetch).not.toHaveBeenCalled(); } finally { vi.useRealTimers(); } @@ -137,7 +148,7 @@ test('an RPC authentication that never settles reaches the ingress deadline', as test.each([ ['object', { nested: 'untrusted' }], - ['oversized string', 'x'.repeat(4_096)], + ['oversized string', 'x'.repeat(DAEMON_RPC_PREAUTH_MAX_ID_LENGTH + 1)], ])('RPC authentication timeout drops an %s request id', async (_label, id) => { vi.useFakeTimers(); try { diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 5d74b4ef962..80061d7ac4e 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -20,6 +20,7 @@ import { normalizeTenantId, normalizeDaemonPublicOrigin, DAEMON_REQUEST_MAX_BYTES, + DAEMON_RPC_PREAUTH_MAX_ID_LENGTH, DAEMON_RPC_PREAUTH_TIMEOUT_MS, DAEMON_INSTANCE_REASONS, DAEMON_HTTP_CHECKED_RPC_CAPABILITY, @@ -254,7 +255,7 @@ async function handleRpcRoute( preauth.signal.aborted && refusal === preauth.signal.reason && typeof id === 'string' && - id.length > 128; + id.length > DAEMON_RPC_PREAUTH_MAX_ID_LENGTH; return rpcErrorResponse(oversizedTimeoutId ? null : id, refusal); } finally { clearTimeout(deadline); From 101a1715011837283a3496cd543d5090d9613b59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 11:49:35 +0100 Subject: [PATCH 16/17] test(daemon): assert local request tenant scope --- .../server/http/http-authorization-script-admission.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/daemon/src/server/http/http-authorization-script-admission.test.ts b/packages/daemon/src/server/http/http-authorization-script-admission.test.ts index 2d32d8133e9..8ab763785be 100644 --- a/packages/daemon/src/server/http/http-authorization-script-admission.test.ts +++ b/packages/daemon/src/server/http/http-authorization-script-admission.test.ts @@ -70,5 +70,9 @@ test('a client-declared tenant does not make a local request remote', () => { flags: { saveScript: '/host/a.ad' }, meta: { tenantId: 'tenant-a', scriptPublicationId: PUBLICATION_ID }, }; - expect(restrictRemoteHttpRequest(request, false, undefined)).toBe(request); + const result = restrictRemoteHttpRequest(request, false, undefined); + + expect(result.meta?.tenantId).toBe('tenant-a'); + expect(result.flags?.saveScript).toBe('/host/a.ad'); + expect(result.internal?.publicNetworkOnly).toBeUndefined(); }); From 2eedab287a0f25baa77a6602bc615fd73332e4a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 17:16:32 +0100 Subject: [PATCH 17/17] test(daemon): verify preauth deadlines through HTTP listeners --- .../http-server-rpc-ingress-budget.test.ts | 143 ++++++++++++++---- 1 file changed, 110 insertions(+), 33 deletions(-) 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 index d56c0ab4e54..86d0cec1108 100644 --- 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 @@ -2,7 +2,9 @@ import http from 'node:http'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; +import { pathToFileURL } from 'node:url'; import { test, vi } from 'vitest'; +import { createDaemonProxyServer } from '@agent-device/proxy'; import { closeLoopbackServer, listenOnLoopback, @@ -10,7 +12,11 @@ import { skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; import { createDaemonHttpServer } from './http-server.ts'; -import { postRpcCommand, startRpcServer } from '../__tests__/http-server-rpc.fixtures.ts'; +import { + postRpcCommand, + startRpcServer, + type RpcErrorBody, +} from '../__tests__/http-server-rpc.fixtures.ts'; test('preauthorization body deadline answers with a typed reason before dispatch', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; @@ -58,40 +64,111 @@ test('preauthorization body deadline answers with a typed reason before dispatch } }); -test('authentication timeout preserves the completed RPC request id', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - const root = mkdtempForTestSync('rpc-preauth-id-'); - const hookPath = path.join(root, 'auth-hook.mjs'); - fs.writeFileSync( - hookPath, - 'export default function authHook() { return new Promise(() => {}); }\n', - ); - const server = await createDaemonHttpServer({ - token: 'budget-token', - env: { ...process.env, AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath }, - cwd: process.cwd(), - handleRequest: async () => ({ ok: true, data: {} }), - }); - const port = await listenOnLoopback(server); - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); - const bodyReceived = new Promise((resolve) => { - server.once('request', (req) => req.once('end', resolve)); - }); - try { - const response = postRpcCommand(port, 'budget-token', 'known-request'); - await bodyReceived; +test.for([ + ['proxy', 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', 0], + ['daemon', 'RPC_PREAUTH_DEADLINE_EXCEEDED', 1], +] as const)( + 'the %s auth deadline answers through the proxy and allows a fresh call', + async ([origin, reason, expectedDaemonCalls], t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const root = mkdtempForTestSync('rpc-preauth-id-'); + const hookPath = path.join(root, 'auth-hook.mjs'); + fs.writeFileSync( + hookPath, + `const entered = Promise.withResolvers(); +const held = Promise.withResolvers(); +export const authEntered = entered.promise; +export const releaseAuth = () => held.resolve({ tenantId: 'budget-tenant' }); +export function holdAuth() { + entered.resolve(); + return held.promise; +} +export default function authHook({ rpcRequest }) { + return rpcRequest.id === 'daemon-timeout' ? holdAuth() : { tenantId: 'budget-tenant' }; +} +`, + ); + const auth = (await import(pathToFileURL(hookPath).href)) as { + authEntered: Promise; + holdAuth: () => Promise<{ tenantId: string }>; + releaseAuth: () => void; + }; + let daemonCalls = 0; + let dispatched = 0; + const daemon = await createDaemonHttpServer({ + token: 'budget-token', + env: { AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath }, + cwd: process.cwd(), + handleRequest: async () => { + dispatched += 1; + return { ok: true, data: { reached: 'daemon-handler' } }; + }, + }); + t.onTestFinished(() => closeLoopbackServer(daemon)); + daemon.on('request', () => { + daemonCalls += 1; + }); + const daemonPort = await listenOnLoopback(daemon); + const proxy = createDaemonProxyServer({ + upstreamBaseUrl: `http://127.0.0.1:${daemonPort}`, + upstreamToken: 'budget-token', + authenticate: (request) => + request.headers.get('x-request-id') === 'proxy-timeout' + ? auth.holdAuth() + : { tenantId: 'budget-tenant' }, + }); + t.onTestFinished(() => closeLoopbackServer(proxy)); + const proxyPort = await listenOnLoopback(proxy); + const post = (id: string) => + fetch(`http://127.0.0.1:${proxyPort}/agent-device/rpc`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-request-id': id }, + body: JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'agent_device.command', + params: { command: 'session_list' }, + }), + signal: AbortSignal.timeout(2_000), + }); + + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + t.onTestFinished(() => { + vi.useRealTimers(); + auth.releaseAuth(); + }); + const id = `${origin}-timeout`; + const pending = post(id); + await Promise.race([ + auth.authEntered, + pending.then((response) => + assert.fail(`HTTP ${response.status} before entering ${origin} auth`), + ), + ]); await vi.advanceTimersByTimeAsync(5_000); - const answered = await response; - assert.equal(answered.status, 408); - assert.equal(answered.body.id, 'known-request'); - assert.equal(answered.body.error?.data?.details?.reason, 'RPC_PREAUTH_DEADLINE_EXCEEDED'); - assert.equal(answered.body.error?.data?.details?.dispatched, 'no'); - assert.equal(answered.body.error?.data?.retriable, true); - } finally { + const response = await pending; + assert.equal(response.status, 408); + const body = (await response.json()) as RpcErrorBody; + assert.equal(body.id, id); + assert.equal(body.error?.data?.details?.reason, reason); + assert.equal(body.error?.data?.details?.dispatched, 'no'); + assert.equal(body.error?.data?.retriable, true); + assert.equal(daemonCalls, expectedDaemonCalls); + assert.equal(dispatched, 0); + vi.useRealTimers(); - await closeLoopbackServer(server); - } -}); + auth.releaseAuth(); + const fresh = await post(`${origin}-fresh`); + assert.equal(fresh.status, 200); + assert.deepEqual(await fresh.json(), { + jsonrpc: '2.0', + id: `${origin}-fresh`, + result: { ok: true, data: { reached: 'daemon-handler' } }, + }); + assert.equal(daemonCalls, expectedDaemonCalls + 1); + assert.equal(dispatched, 1); + }, +); test('unfinished unauthenticated RPC bodies do not block authenticated dispatch', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return;