From de09902de158ae9a01882287468b83ae72b5a8e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 08:38:07 +0100 Subject: [PATCH 01/11] fix(rpc): authenticate before request-id registration and bound pre-auth ingress --- packages/contracts/src/daemon-http.ts | 5 ++ .../http-server-rpc-admission.test.ts | 19 +++---- .../http-server-rpc-preauth-deadline.test.ts | 48 ++++++++++++++++ .../daemon/src/server/http/http-server.ts | 53 +++++++++++++---- .../proxy/src/daemon-proxy-preauth.test.ts | 57 +++++++++++++++++++ packages/proxy/src/daemon-proxy.ts | 56 ++++++++++++++---- .../__tests__/script-source.test.ts | 31 ++++++++++ .../daemon-port/replay-plugin-admission.ts | 2 + .../src/daemon-port/script-source.ts | 2 +- .../replay-port/src/script-source-bundle.ts | 30 ++++++++++ website/docs/docs/remote-proxy.md | 2 + 11 files changed, 270 insertions(+), 35 deletions(-) create mode 100644 packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts create mode 100644 packages/proxy/src/daemon-proxy-preauth.test.ts diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index a1eb9a90ac9..9d27905df79 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -134,6 +134,11 @@ export const DAEMON_RPC_PROTOCOL_VERSION = 3; * worst-case escaping. It also bounds the memory one unauthenticated connection can hold. */ export const DAEMON_REQUEST_MAX_BYTES = 64 * 1024 * 1024; +/** + * How long an `/rpc` caller that has not authenticated yet may hold its connection, on the daemon + * and on the proxy: its body and its authentication must both finish inside this window. + */ +export const DAEMON_RPC_PREAUTH_TIMEOUT_MS = 30_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-admission.test.ts b/packages/daemon/src/server/__tests__/http-server-rpc-admission.test.ts index c78d61d6c11..0aa5c0ef61f 100644 --- a/packages/daemon/src/server/__tests__/http-server-rpc-admission.test.ts +++ b/packages/daemon/src/server/__tests__/http-server-rpc-admission.test.ts @@ -50,10 +50,10 @@ test('the rpc admission asks the auth hook before it compares the token', async } }); -// The tracking id is registered ahead of the gate, so the loser of a duplicate-id race is -// refused by the registration and the operator's hook never sees it. The hook runs in this -// process, so it can count its own invocations and say so. -test('the rpc admission registers the tracking id before consulting the auth hook', async (t) => { +// Only an authenticated call registers its tracking id, so an unauthenticated caller can neither +// hold a tenant's id nor learn that it is in flight. The hook runs in this process, so it can +// count its own invocations and say so. +test('the rpc admission authenticates before it registers the tracking id', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK; const previousCalls = process.env[HOOK_CALLS_ENV]; @@ -75,16 +75,15 @@ test('the rpc admission registers the tracking id before consulting the auth hoo try { const first = postRpcCommand(port, DAEMON_TOKEN, 'req-admission'); await started; - assert.equal(hookCalls(), 1, 'the admitted call consulted the hook'); + + const unauthenticated = await postRpcCommand(port, 'wrong-token', 'req-admission'); + assert.equal(unauthenticated.status, 401, 'an unauthenticated caller never meets the id'); + assert.equal(unauthenticated.body.error?.code, -32000); const duplicate = await postRpcCommand(port, DAEMON_TOKEN, 'req-admission'); assert.equal(duplicate.status, 400); assert.equal(duplicate.body.error?.data?.details?.reason, 'duplicate_request_id'); - assert.equal( - hookCalls(), - 1, - 'the auth hook must not see a call the tracking-id registration already refused', - ); + assert.equal(hookCalls(), 3, 'every call authenticates before the id is registered'); release(); assert.equal((await first).status, 200); diff --git a/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts new file mode 100644 index 00000000000..00eaacd944f --- /dev/null +++ b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts @@ -0,0 +1,48 @@ +import { test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import net from 'node:net'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { + closeLoopbackServer, + listenOnLoopback, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; + +// The real deadline, scaled down: the daemon's own timer runs on real time. +vi.mock('@agent-device/contracts/daemon-http', async (importOriginal) => ({ + ...(await importOriginal()), + DAEMON_RPC_PREAUTH_TIMEOUT_MS: 200, +})); + +test('an unauthenticated rpc caller that stalls its body is closed at the pre-auth deadline', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { createDaemonHttpServer } = await import('./http-server.ts'); + let handlerCalls = 0; + const server = await createDaemonHttpServer({ + token: 'daemon-secret', + handleRequest: async (): Promise => { + handlerCalls += 1; + return { ok: true, data: {} }; + }, + env: process.env, + cwd: process.cwd(), + }); + const port = await listenOnLoopback(server); + const socket = net.connect(port, '127.0.0.1'); + socket.on('error', () => {}); + try { + const closed = new Promise((resolve) => socket.once('close', () => resolve())); + const startedAt = Date.now(); + // No token header, so the token can only be in a body that never finishes. + socket.write( + 'POST /rpc HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n' + + 'Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"', + ); + await closed; + assert.ok(Date.now() - startedAt < 5_000, 'the deadline, not a Node ceiling, closed it'); + assert.equal(handlerCalls, 0); + } finally { + socket.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 daae7f1eef0..1c939af0ddd 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -40,6 +40,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'; @@ -245,6 +246,13 @@ export async function createDaemonHttpServer(options: { return; } + // A caller whose header carries the daemon token is authenticated before its body is read. + // Any other caller is unauthenticated until admission, because the token may sit in the body + // and the auth hook reads the body. + const preauthDeadline = + !authHook && (!token || !enforceDaemonToken(resolveToken({}, req.headers), token)) + ? undefined + : startPreauthDeadline(res); readRpcRequestBody(req, res, (body) => { // 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 @@ -259,6 +267,7 @@ export async function createDaemonHttpServer(options: { instanceId, handleRequest, checked, + preauthDeadline, }).catch((error: unknown) => { sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); }); @@ -285,6 +294,21 @@ export async function createDaemonHttpServer(options: { return server; } +/** The window in which an unauthenticated `/rpc` caller must send its body and pass admission. */ +type PreauthDeadline = { signal: AbortSignal; end(): void }; + +/** Closes the connection and stops the auth hook wait when the caller is still unadmitted. */ +function startPreauthDeadline(res: http.ServerResponse): PreauthDeadline { + const controller = new AbortController(); + const timer = setTimeout(() => { + controller.abort(); + res.destroy(); + }, DAEMON_RPC_PREAUTH_TIMEOUT_MS); + const end = () => clearTimeout(timer); + res.once('close', end); + return { signal: controller.signal, end }; +} + /** Accumulates one `/rpc` body and hands it to the flow once the stream ends. */ function readRpcRequestBody( req: http.IncomingMessage, @@ -332,8 +356,11 @@ async function handleRpcRequest(params: { handleRequest: DaemonInvokeFn; /** The call came on the checked route, so its protocol is checked before dispatch. */ checked: boolean; + /** Absent when the caller's header already proved the daemon token. */ + preauthDeadline: PreauthDeadline | undefined; }): Promise { const { req, res, body, authHook, expectedToken, instanceId, handleRequest, checked } = params; + const { preauthDeadline } = 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; @@ -361,7 +388,9 @@ async function handleRpcRequest(params: { params: validated.params, lifetime, protocolRefusal, + preauthSignal: preauthDeadline?.signal, }); + preauthDeadline?.end(); if (admission.outcome !== 'admitted') { if (admission.outcome === 'rejected') { sendRpcRefusal(res, admission.refusal); @@ -378,8 +407,8 @@ async function handleRpcRequest(params: { lifetime, }); } catch (error) { - // Reached only when the call never got as far as an invocation: unsound method params - // or a duplicate tracking id. The failure answer is on its way, so a socket closing + // Reached only when the call never got as far as an invocation: unsound method params, + // an auth hook that outlived the pre-auth deadline, 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)); @@ -496,8 +525,9 @@ function sendRpcRefusal(res: http.ServerResponse, refusal: RpcRefusal): void { type RpcRequestLifetime = { /** * Stamps the daemon's request tracking id into `meta` and registers the request's AbortSignal - * under it. An id already in flight throws `duplicate_request_id` from here, so the caller - * that loses the race never reaches the auth gate with it. + * under it. Only an authenticated call reaches it, so an unauthenticated caller can neither + * hold a tenant's id nor learn that it is in flight. An id already in flight throws + * `duplicate_request_id` from here. */ admit(daemonRequest: DaemonRequest): DaemonRequest; /** @@ -589,9 +619,8 @@ type RpcRequestAdmission = | { outcome: 'answered' }; /** - * Turns a validated call into a request its caller may run. The tracking-id registration runs - * ahead of the gates on purpose, so a request id already in flight is refused as - * `duplicate_request_id` before the operator's hook sees the call. Malformed wire input throws + * Turns a validated call into a request its caller may run. The gates see the tracking id stamped + * but unregistered; only a call that passes every gate registers it. Malformed wire input throws * (`methodToDaemonRequest` validates params as INVALID_ARGS) and never reaches the gates. */ async function admitRpcRequest(params: { @@ -607,6 +636,8 @@ async function admitRpcRequest(params: { lifetime: RpcRequestLifetime; /** A checked call's protocol refusal, answered once the caller passes the auth gates. */ protocolRefusal: CheckedRpcProtocolRefusal | undefined; + /** Aborts when the caller is still unauthenticated at the pre-auth deadline. */ + preauthSignal: AbortSignal | undefined; }): Promise { const { req, res, authHook, expectedToken, instanceId, rpcRequest, method, lifetime } = params; const { protocolRefusal } = params; @@ -623,10 +654,7 @@ async function admitRpcRequest(params: { ), }; } - // A call that will be refused never reserves its tracking id: only a call that can run registers. - const daemonRequest = protocolRefusal - ? withUnregisteredTrackingId(wireRequest, rpcRequest.id) - : lifetime.admit(wireRequest); + const daemonRequest = withUnregisteredTrackingId(wireRequest, rpcRequest.id); // Captured before the hook runs: what the caller claimed is an input to the trust // decision, never an identity. @@ -636,6 +664,7 @@ async function admitRpcRequest(params: { headers: req.headers, rpcRequest, daemonRequest, + signal: params.preauthSignal, }); if (!authResult.ok) { return { @@ -665,7 +694,7 @@ async function admitRpcRequest(params: { return { outcome: 'admitted', - daemonRequest: stampAdmittedIdentity(daemonRequest, tenantTrust, authHook, req), + daemonRequest: lifetime.admit(stampAdmittedIdentity(daemonRequest, tenantTrust, authHook, req)), }; } diff --git a/packages/proxy/src/daemon-proxy-preauth.test.ts b/packages/proxy/src/daemon-proxy-preauth.test.ts new file mode 100644 index 00000000000..b7633a91a12 --- /dev/null +++ b/packages/proxy/src/daemon-proxy-preauth.test.ts @@ -0,0 +1,57 @@ +import { expect, test, vi } from 'vitest'; + +// The real deadline, scaled down: the proxy's own timer runs on real time. +vi.mock('@agent-device/contracts/daemon-http', async (importOriginal) => ({ + ...(await importOriginal()), + DAEMON_RPC_PREAUTH_TIMEOUT_MS: 200, +})); + +const { createDaemonProxy } = await import('./daemon-proxy.ts'); + +function stalledRpcRequest(headers: Record): Request { + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('{"jsonrpc":"2.0"')); + }, + }); + return new Request('https://gateway.example.test/agent-device/rpc', { + method: 'POST', + headers: { 'content-type': 'application/json', ...headers }, + body, + duplex: 'half', + } as RequestInit); +} + +const UPSTREAM = { + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: async (): Promise => { + throw new Error('an unauthenticated call must not reach the daemon'); + }, +}; + +function proxyWith(options: { clientToken: string } | { authenticate: () => Promise }) { + return createDaemonProxy({ ...UPSTREAM, ...options }); +} + +test('a wrong header token is refused before the proxy reads the body', async () => { + const response = await proxyWith({ clientToken: 'client-secret' }).handle( + stalledRpcRequest({ authorization: 'Bearer wrong-token' }), + ); + expect(response.status).toBe(401); +}); + +test('a caller with no header token that stalls its body is refused at the pre-auth deadline', async () => { + const response = await proxyWith({ clientToken: 'client-secret' }).handle(stalledRpcRequest({})); + expect(response.status).toBe(401); +}); + +test('an authenticate hook that never answers is refused at the pre-auth deadline', async () => { + const proxy = proxyWith({ authenticate: () => new Promise(() => {}) }); + const request = new Request('https://gateway.example.test/agent-device/rpc', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent_device.command', params: {} }), + }); + expect((await proxy.handle(request)).status).toBe(401); +}); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 6ab4e8788d5..3db5aa0b87c 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -19,6 +19,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, @@ -206,14 +207,27 @@ async function handleProxyRequest( if (!isRpcRoute(route)) return await handleDaemonRoute(request, route, options, instanceId); + // A header token outranks a body token, so without `authenticate` it decides the call before + // the proxy buffers any body. Any other caller must finish its body and its authentication + // inside the pre-auth deadline. + const headerAuthenticated = + !options.authenticate && resolveRequestToken(request, undefined) !== ''; + if (headerAuthenticated && !isAuthorized(request, options.clientToken ?? '', undefined)) { + return unauthorizedResponse(route, null); + } + const preauthSignal = headerAuthenticated + ? undefined + : AbortSignal.any([request.signal, AbortSignal.timeout(DAEMON_RPC_PREAUTH_TIMEOUT_MS)]); let rpcBody: string; try { rpcBody = await readRequestText( request, options.maxRpcBodyBytes, 'Proxy request body is too large.', + preauthSignal, ); } catch (error) { + if (preauthSignal?.aborted) return unauthorizedResponse(route, null); return rpcErrorResponse(null, error); } // The checked route checks its envelope after authentication and the protocol: a caller on @@ -222,7 +236,7 @@ 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); + return await handleDaemonRoute(request, route, options, instanceId, rpcBody, preauthSignal); } catch (error) { return rpcErrorResponse(readJsonRpcId(rpcBody), error); } @@ -234,8 +248,9 @@ async function handleDaemonRoute( options: NormalizedProxyOptions, instanceId: string, rpcBody?: string, + preauthSignal?: AbortSignal, ): Promise { - const caller = await authenticateCaller(request, options, rpcBody); + const caller = await authenticateCaller(request, options, rpcBody, preauthSignal); if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } @@ -276,20 +291,29 @@ async function authenticateCaller( request: Request, options: NormalizedProxyOptions, rpcBody: string | undefined, + preauthSignal: AbortSignal | undefined, ): Promise { if (!options.authenticate) { return isAuthorized(request, options.clientToken ?? '', rpcBody) ? { uploadHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } : null; } - const result = await options.authenticate( + const authentication = options.authenticate( forwardedRequest(request, request.url, { method: request.method, headers: request.headers, - signal: request.signal, + signal: preauthSignal ?? request.signal, ...(rpcBody !== undefined ? { body: rpcBody } : {}), }), ); + const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); + const result = await awaitWithSignal(Promise.resolve(authentication), preauthSignal).catch( + (error: unknown) => { + // A caller still unauthenticated at the deadline is refused as unauthenticated. + if (preauthSignal?.aborted) return null; + throw error; + }, + ); if (!result) return null; const tenantId = normalizeTenantId( typeof result.tenantId === 'string' ? result.tenantId : undefined, @@ -761,20 +785,28 @@ async function readRequestText( request: Request, maxBodyBytes: number, tooLargeMessage: string, + signal: AbortSignal | undefined, ): Promise { if (!request.body) return ''; const reader = request.body.getReader(); + const cancel = () => void reader.cancel().catch(() => {}); + signal?.addEventListener('abort', cancel, { once: true }); const chunks: Uint8Array[] = []; let bodyBytes = 0; - for (;;) { - const { done, value } = await reader.read(); - if (done) break; - bodyBytes += value.byteLength; - if (bodyBytes > maxBodyBytes) { - await reader.cancel(); - throw new AppError('INVALID_ARGS', tooLargeMessage); + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + bodyBytes += value.byteLength; + if (bodyBytes > maxBodyBytes) { + await reader.cancel(); + throw new AppError('INVALID_ARGS', tooLargeMessage); + } + chunks.push(value); } - chunks.push(value); + signal?.throwIfAborted(); + } finally { + signal?.removeEventListener('abort', cancel); } return Buffer.concat(chunks).toString('utf8'); } diff --git a/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts b/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts index e7d35f20840..10e5f20264c 100644 --- a/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts +++ b/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts @@ -1,6 +1,37 @@ import { expect, test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; import { readReplayScriptSourceFile } from '../script-source.ts'; +import { + assertReplayRequestScriptSources, + REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, +} from '../../script-source-bundle.ts'; + +test('a path the bundle does not own is missing, even when the prototype names it', () => { + const bundle = { entry: '/flows/login.ad', files: { '/flows/login.ad': 'back\n' } }; + for (const inherited of ['__proto__', 'constructor', 'toString']) { + expect(() => readReplayScriptSourceFile(bundle, inherited)).toThrow(AppError); + } +}); + +test('a suite may carry bundles whose total is over the per-bundle limit', () => { + const script = 'a'.repeat(REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES - 1024); + const bundle = (entry: string) => ({ entry, files: { [entry]: script } }); + expect(() => + assertReplayRequestScriptSources({ + replayScriptSources: [bundle('/flows/a.ad'), bundle('/flows/b.ad')], + }), + ).not.toThrow(); + expect(() => + assertReplayRequestScriptSources({ + replayScriptSource: { entry: '/flows/c.ad', files: { '/flows/c.ad': `${script}${script}` } }, + }), + ).toThrow(/over the 2097152-byte limit/); + expect(() => + assertReplayRequestScriptSources({ + replayScriptSources: [{ entry: '/flows/d.ad', files: { '/flows/d.ad': 1 } }], + }), + ).toThrow(AppError); +}); test('reading a file the bundle does not carry names the file and the entry', () => { const bundle = { entry: '/flows/login.yaml', files: { '/flows/login.yaml': '---\n- back\n' } }; diff --git a/packages/replay-port/src/daemon-port/replay-plugin-admission.ts b/packages/replay-port/src/daemon-port/replay-plugin-admission.ts index 6ae7eed784f..190c2e802a5 100644 --- a/packages/replay-port/src/daemon-port/replay-plugin-admission.ts +++ b/packages/replay-port/src/daemon-port/replay-plugin-admission.ts @@ -10,6 +10,8 @@ export async function requireReplayPlugins(request: DaemonWireRequest): Promise< const backend = request.flags?.replayBackend; if (backend !== undefined && !isReplayBackendId(backend)) throw new AppError('INVALID_ARGS', unsupportedReplayBackendMessage(backend)); + const { assertReplayRequestScriptSources } = await import('../script-source-bundle.ts'); + assertReplayRequestScriptSources(request.flags); if (request.command === 'test') await requireReplayTestPlugins(request, backend); else if (request.command === 'replay') await requireReplayEntryPlugin(request, backend); } diff --git a/packages/replay-port/src/daemon-port/script-source.ts b/packages/replay-port/src/daemon-port/script-source.ts index 717008434cb..8ca58e3a22f 100644 --- a/packages/replay-port/src/daemon-port/script-source.ts +++ b/packages/replay-port/src/daemon-port/script-source.ts @@ -8,7 +8,7 @@ export function readReplayScriptSourceFile( bundle: ReplayScriptSourceBundle, resolvedPath: string, ): string { - const script = bundle.files[resolvedPath]; + const script = Object.hasOwn(bundle.files, resolvedPath) ? bundle.files[resolvedPath] : undefined; if (script === undefined) { throw new AppError( 'INVALID_ARGS', diff --git a/packages/replay-port/src/script-source-bundle.ts b/packages/replay-port/src/script-source-bundle.ts index 2c1152d6821..53e158a3cdb 100644 --- a/packages/replay-port/src/script-source-bundle.ts +++ b/packages/replay-port/src/script-source-bundle.ts @@ -1,6 +1,7 @@ import fs from 'node:fs'; import type { ReplayBackendResolver } from '@agent-device/contracts/replay-backend'; import { AppError } from '@agent-device/kernel/errors'; +import { isRecord } from '@agent-device/kernel/record'; import type { ReplayScriptSourceBundle } from '@agent-device/contracts/replay'; import { resolveUserPath } from '@agent-device/host-kit/path-resolution'; import { resolveReplayFormat } from '@agent-device/ad-script'; @@ -54,6 +55,35 @@ function finishBundle( return { entry, files }; } +/** + * The daemon's check of the script sources a client sent: each bundle is an entry plus text files + * and stays within the per-bundle limit. A suite may carry any number of bundles. + */ +export function assertReplayRequestScriptSources( + flags: { replayScriptSource?: unknown; replayScriptSources?: unknown } | undefined, +): void { + const { replayScriptSource: single, replayScriptSources: suite = [] } = flags ?? {}; + if (!Array.isArray(suite)) throw invalidScriptSourceBundle(); + for (const bundle of single === undefined ? suite : [single, ...suite]) { + if ( + !isRecord(bundle) || + typeof bundle.entry !== 'string' || + !isRecord(bundle.files) || + !Object.values(bundle.files).every((script) => typeof script === 'string') + ) { + throw invalidScriptSourceBundle(); + } + assertBundleWithinLimit(bundle.files as Record, bundle.entry); + } +} + +function invalidScriptSourceBundle(): AppError { + return new AppError( + 'INVALID_ARGS', + 'replay script sources must be bundles of an entry path and text files.', + ); +} + function readReplayEntryScript(resolvedPath: string, inputPath: string): string { try { return fs.readFileSync(resolvedPath, 'utf8'); diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index bea0453832d..fd1901503a3 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -365,6 +365,8 @@ them to tell whether the daemon or the proxy answered. The proxy checks the client token and forwards authorized requests with the local daemon token. Remote clients never see the daemon token. +Send the token in the `authorization` or `x-agent-device-token` header. The proxy then refuses a wrong token before it reads the request body. An `/rpc` caller that sends no token header, or a proxy with `authenticate`, must finish the body and authentication within 30 seconds. Otherwise the request fails with `401`. The daemon closes an `/rpc` connection that has not passed authentication after 30 seconds. A daemon without an auth hook skips this limit when the header carries the daemon token. + The proxy does not forward `/admin/*`, including human-control holds. A caller on the device host must use the daemon's loopback port and local daemon token. From e6fe748efffcc598d66025f819f5d0bed6278dcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 09:21:47 +0100 Subject: [PATCH 02/11] fix(daemon,proxy): bound unauthenticated rpc callers with pre-auth slots Abort the daemon auth hook wait when the caller leaves, never register a tracking id after that abort, and end the pre-auth window on every admission exit. Hold at most 4 unauthenticated /rpc callers per daemon and per proxy; refuse more with a retryable 503 (remote_preauth_busy). The Node proxy adapter closes a connection answered before its body was read. Map only the deadline to 401, load awaitWithSignal before the hook runs, and move the replay bundle guard into the daemon-safe module. --- packages/contracts/src/daemon-http.ts | 9 ++ .../http-server-rpc-preauth-deadline.test.ts | 87 +++++++++++ .../daemon/src/server/http/http-server.ts | 119 +++++++++++---- .../proxy/src/daemon-proxy-preauth.test.ts | 61 +++++++- packages/proxy/src/daemon-proxy.ts | 127 ++++++---------- packages/proxy/src/node-http.ts | 3 + packages/proxy/src/rpc-ingress.ts | 138 ++++++++++++++++++ .../__tests__/script-source-bundle.test.ts | 6 +- .../__tests__/script-source.test.ts | 4 +- .../daemon-port/replay-plugin-admission.ts | 2 +- .../src/daemon-port/script-source.ts | 41 ++++++ .../replay-port/src/script-source-bundle.ts | 52 +------ website/docs/docs/error-reasons.md | 1 + website/docs/docs/remote-proxy.md | 2 +- 14 files changed, 484 insertions(+), 168 deletions(-) create mode 100644 packages/proxy/src/rpc-ingress.ts diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 9d27905df79..c485f6d89d8 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -139,6 +139,15 @@ export const DAEMON_REQUEST_MAX_BYTES = 64 * 1024 * 1024; * and on the proxy: its body and its authentication must both finish inside this window. */ export const DAEMON_RPC_PREAUTH_TIMEOUT_MS = 30_000; +/** How many unauthenticated `/rpc` callers one daemon or one proxy holds at once. */ +export const DAEMON_RPC_PREAUTH_SLOTS = 4; + +/** Why a daemon or proxy refused an `/rpc` caller before it read the request body. */ +export const DAEMON_RPC_PREAUTH_REASONS = { + // The daemon or proxy already holds its limit of callers that have not authenticated yet, so it + // answered HTTP 503 and closed the connection before it read the body. Retry after a short delay. + preauthBusy: { reason: 'remote_preauth_busy' }, +} as const satisfies ReasonTable<'remote connection'>; 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-rpc-preauth-deadline.test.ts b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts index 00eaacd944f..fb7f3999564 100644 --- a/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts +++ b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts @@ -1,10 +1,13 @@ import { test, vi } from 'vitest'; import assert from 'node:assert/strict'; +import fs from 'node:fs'; import net from 'node:net'; +import path from 'node:path'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { closeLoopbackServer, listenOnLoopback, + mkdtempForTestSync, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; @@ -12,8 +15,28 @@ import { vi.mock('@agent-device/contracts/daemon-http', async (importOriginal) => ({ ...(await importOriginal()), DAEMON_RPC_PREAUTH_TIMEOUT_MS: 200, + DAEMON_RPC_PREAUTH_SLOTS: 1, })); +const RPC_HEAD = 'POST /rpc HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n'; + +async function startDaemon(env: NodeJS.ProcessEnv = process.env) { + const { createDaemonHttpServer } = await import('./http-server.ts'); + const server = await createDaemonHttpServer({ + token: 'daemon-secret', + handleRequest: async (): Promise => ({ ok: true, data: {} }), + env, + cwd: process.cwd(), + }); + return { server, port: await listenOnLoopback(server) }; +} + +function connect(port: number): net.Socket { + const socket = net.connect(port, '127.0.0.1'); + socket.on('error', () => {}); + return socket; +} + test('an unauthenticated rpc caller that stalls its body is closed at the pre-auth deadline', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const { createDaemonHttpServer } = await import('./http-server.ts'); @@ -46,3 +69,67 @@ test('an unauthenticated rpc caller that stalls its body is closed at the pre-au await closeLoopbackServer(server); } }); + +test('a caller over the pre-auth slot limit gets a retryable 503 and a closed connection', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startDaemon(); + const holder = connect(port); + const excess = connect(port); + try { + const held = new Promise((resolve) => server.once('request', resolve)); + holder.write(`${RPC_HEAD}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`); + await held; + let received = ''; + excess.on('data', (chunk) => (received += chunk.toString('utf8'))); + const closed = new Promise((resolve) => excess.once('close', () => resolve())); + excess.write(`${RPC_HEAD}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`); + await closed; + assert.match(received, /^HTTP\/1\.1 503 /); + assert.match(received, /"reason":"remote_preauth_busy"/); + assert.match(received, /"retriable":true/); + } finally { + holder.destroy(); + excess.destroy(); + await closeLoopbackServer(server); + } +}); + +test('a caller that leaves while the auth hook runs aborts the hook signal', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const dir = mkdtempForTestSync('preauth-hook-'); + const hookPath = path.join(dir, 'hook.mjs'); + fs.writeFileSync( + hookPath, + `export default ({ signal }) => new Promise(() => { + globalThis.__preauthHook.started(); + signal.addEventListener('abort', () => globalThis.__preauthHook.aborted()); + });`, + ); + const started = Promise.withResolvers(); + const aborted = Promise.withResolvers(); + Object.assign(globalThis, { + __preauthHook: { started: started.resolve, aborted: aborted.resolve }, + }); + const { server, port } = await startDaemon({ + ...process.env, + AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath, + }); + const socket = connect(port); + try { + const body = JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'agent_device.command', + params: { command: 'devices' }, + }); + socket.write(`${RPC_HEAD}Content-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`); + await started.promise; + socket.destroy(); + await aborted.promise; + } finally { + socket.destroy(); + await closeLoopbackServer(server); + fs.rmSync(dir, { recursive: true, force: true }); + Reflect.deleteProperty(globalThis, '__preauthHook'); + } +}); diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 1c939af0ddd..022699b2099 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -13,7 +13,7 @@ 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 { 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'; @@ -41,6 +41,8 @@ import { type CheckedRpcProtocolRefusal, DAEMON_REQUEST_MAX_BYTES, DAEMON_RPC_PREAUTH_TIMEOUT_MS, + DAEMON_RPC_PREAUTH_SLOTS, + DAEMON_RPC_PREAUTH_REASONS, } from '@agent-device/contracts/daemon-http'; import { readVersion } from '@agent-device/host-kit/version'; import { readHostCpuArch } from '@agent-device/host-kit/process'; @@ -163,6 +165,7 @@ export async function createDaemonHttpServer(options: { resolveRequestDiagnosticsPath, onUnownedRequestFailure, } = options; + const acquirePreauth = createPreauthSlots(DAEMON_RPC_PREAUTH_SLOTS); const onRequest = AsyncResource.bind((req: http.IncomingMessage, res: http.ServerResponse) => { const ingressUrl = nodeHttpRequestUrl(req.url, req.rawHeaders, req.socket instanceof TLSSocket); if (!ingressUrl) { @@ -246,13 +249,13 @@ export async function createDaemonHttpServer(options: { return; } - // A caller whose header carries the daemon token is authenticated before its body is read. - // Any other caller is unauthenticated until admission, because the token may sit in the body - // and the auth hook reads the body. - const preauthDeadline = - !authHook && (!token || !enforceDaemonToken(resolveToken({}, req.headers), token)) - ? undefined - : startPreauthDeadline(res); + const preauthDeadline = headerProvesDaemonToken(req, authHook, token) + ? undefined + : acquirePreauth(res); + if (preauthDeadline === null) { + refusePreauthBusy(res); + return; + } readRpcRequestBody(req, res, (body) => { // 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 @@ -294,19 +297,79 @@ export async function createDaemonHttpServer(options: { return server; } +/** + * A caller whose header carries the daemon token is authenticated before its body is read. Any + * other caller is unauthenticated until admission, because the token may sit in the body and the + * auth hook reads the body. + */ +function headerProvesDaemonToken( + req: http.IncomingMessage, + authHook: HttpAuthHook | null, + token: string | undefined, +): boolean { + return !authHook && (!token || !enforceDaemonToken(resolveToken({}, req.headers), token)); +} + /** The window in which an unauthenticated `/rpc` caller must send its body and pass admission. */ -type PreauthDeadline = { signal: AbortSignal; end(): void }; - -/** Closes the connection and stops the auth hook wait when the caller is still unadmitted. */ -function startPreauthDeadline(res: http.ServerResponse): PreauthDeadline { - const controller = new AbortController(); - const timer = setTimeout(() => { - controller.abort(); - res.destroy(); - }, DAEMON_RPC_PREAUTH_TIMEOUT_MS); - const end = () => clearTimeout(timer); - res.once('close', end); - return { signal: controller.signal, end }; +type PreauthDeadline = { + /** Aborts at the deadline or when the connection closes before admission ends. */ + signal: AbortSignal; + /** Ends the window when admission ends, however it ends. */ + end(): void; + /** The hook as admission calls it: the slot stays held until each call settles. */ + holdDuring(authHook: HttpAuthHook | null): HttpAuthHook | null; +}; + +/** + * One daemon's pre-auth slots. A caller holds one from before its body is read until admission + * ends and no auth hook that got its body still runs. `null` when every slot is held. + */ +function createPreauthSlots(slots: number): (res: http.ServerResponse) => PreauthDeadline | null { + let free = slots; + return (res) => { + if (free === 0) return null; + free -= 1; + let holds = 1; + const release = () => { + holds -= 1; + if (holds === 0) free += 1; + }; + const controller = new AbortController(); + const timer = setTimeout(() => { + controller.abort(); + res.destroy(); + }, DAEMON_RPC_PREAUTH_TIMEOUT_MS); + let ended = false; + const end = () => { + if (ended) return; + ended = true; + clearTimeout(timer); + release(); + }; + res.once('close', () => { + if (!ended) controller.abort(); + end(); + }); + const holdDuring = (authHook: HttpAuthHook | null): HttpAuthHook | null => + authHook && + ((context) => { + holds += 1; + const pending = Promise.resolve().then(() => authHook(context)); + void pending.then(release, release); + return pending; + }); + return { signal: controller.signal, end, holdDuring }; + }; +} + +/** Refuses an `/rpc` caller when every pre-auth slot is held, before its body is read. */ +function refusePreauthBusy(res: http.ServerResponse): void { + const error = new AppError('COMMAND_FAILED', 'Too many unauthenticated requests', { + reason: DAEMON_RPC_PREAUTH_REASONS.preauthBusy.reason, + retriable: true, + }); + res.setHeader('connection', 'close'); + sendRpcRefusal(res, rpcRefusal(null, -32000, error.message, 503, normalizeError(error))); } /** Accumulates one `/rpc` body and hands it to the flow once the stream ends. */ @@ -388,9 +451,8 @@ async function handleRpcRequest(params: { params: validated.params, lifetime, protocolRefusal, - preauthSignal: preauthDeadline?.signal, - }); - preauthDeadline?.end(); + preauth: preauthDeadline, + }).finally(() => preauthDeadline?.end()); if (admission.outcome !== 'admitted') { if (admission.outcome === 'rejected') { sendRpcRefusal(res, admission.refusal); @@ -636,8 +698,8 @@ async function admitRpcRequest(params: { lifetime: RpcRequestLifetime; /** A checked call's protocol refusal, answered once the caller passes the auth gates. */ protocolRefusal: CheckedRpcProtocolRefusal | undefined; - /** Aborts when the caller is still unauthenticated at the pre-auth deadline. */ - preauthSignal: AbortSignal | undefined; + /** Absent when the caller's header already proved the daemon token. */ + preauth: PreauthDeadline | undefined; }): Promise { const { req, res, authHook, expectedToken, instanceId, rpcRequest, method, lifetime } = params; const { protocolRefusal } = params; @@ -660,11 +722,12 @@ async function admitRpcRequest(params: { // decision, never an identity. const clientDeclaredTenant = daemonRequest.meta?.tenantId ?? daemonRequest.flags?.tenant; - const authResult = await runHttpAuthHook(authHook, { + const { preauth } = params; + const authResult = await runHttpAuthHook(preauth ? preauth.holdDuring(authHook) : authHook, { headers: req.headers, rpcRequest, daemonRequest, - signal: params.preauthSignal, + signal: preauth?.signal, }); if (!authResult.ok) { return { @@ -692,6 +755,8 @@ async function admitRpcRequest(params: { return { outcome: 'answered' }; } + // A caller that left or ran out its window never registers its tracking id. + preauth?.signal.throwIfAborted(); return { outcome: 'admitted', daemonRequest: lifetime.admit(stampAdmittedIdentity(daemonRequest, tenantTrust, authHook, req)), diff --git a/packages/proxy/src/daemon-proxy-preauth.test.ts b/packages/proxy/src/daemon-proxy-preauth.test.ts index b7633a91a12..a4fa4b11470 100644 --- a/packages/proxy/src/daemon-proxy-preauth.test.ts +++ b/packages/proxy/src/daemon-proxy-preauth.test.ts @@ -1,12 +1,15 @@ +import net from 'node:net'; +import type http from 'node:http'; import { expect, test, vi } from 'vitest'; // The real deadline, scaled down: the proxy's own timer runs on real time. vi.mock('@agent-device/contracts/daemon-http', async (importOriginal) => ({ ...(await importOriginal()), DAEMON_RPC_PREAUTH_TIMEOUT_MS: 200, + DAEMON_RPC_PREAUTH_SLOTS: 1, })); -const { createDaemonProxy } = await import('./daemon-proxy.ts'); +const { createDaemonProxy, createDaemonProxyServer } = await import('./daemon-proxy.ts'); function stalledRpcRequest(headers: Record): Request { const body = new ReadableStream({ @@ -55,3 +58,59 @@ test('an authenticate hook that never answers is refused at the pre-auth deadlin }); expect((await proxy.handle(request)).status).toBe(401); }); + +test('a second unauthenticated caller is refused with a retryable 503 while the slot is held', async () => { + const proxy = proxyWith({ clientToken: 'client-secret' }); + const first = proxy.handle(stalledRpcRequest({})); + const response = await proxy.handle(stalledRpcRequest({})); + expect(response.status).toBe(503); + const body = (await response.json()) as { error: { data: Record } }; + expect(body.error.data).toMatchObject({ + retriable: true, + details: { reason: 'remote_preauth_busy' }, + }); + expect((await first).status).toBe(401); +}); + +/** Sends the head and part of a 1 KiB `/rpc` body, then collects what the proxy writes until it closes. */ +async function stalledNodeExchange(server: http.Server, headers: string): Promise { + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as net.AddressInfo; + const socket = net.connect(port, '127.0.0.1'); + socket.on('error', () => {}); + let received = ''; + socket.on('data', (chunk) => (received += chunk.toString('utf8'))); + try { + socket.write( + `POST /agent-device/rpc HTTP/1.1\r\nHost: 127.0.0.1\r\n${headers}` + + 'Content-Type: application/json\r\nContent-Length: 1024\r\n\r\n{"jsonrpc":"2.0"', + ); + const closed = await new Promise((resolve) => { + socket.once('close', () => resolve(true)); + setTimeout(() => resolve(false), 2_000); + }); + expect(closed, 'the proxy closed the connection').toBe(true); + return received; + } finally { + socket.destroy(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +test('over node:http a wrong header token is answered 401 and the connection is closed', async () => { + const received = await stalledNodeExchange( + createDaemonProxyServer({ ...UPSTREAM, clientToken: 'client-secret' }), + 'Authorization: Bearer wrong-token\r\n', + ); + expect(received).toMatch(/^HTTP\/1\.1 401 /); + expect(received.toLowerCase()).toContain('connection: close'); +}); + +test('over node:http a body that stalls past the pre-auth deadline is answered 401 and closed', async () => { + const received = await stalledNodeExchange( + createDaemonProxyServer({ ...UPSTREAM, clientToken: 'client-secret' }), + '', + ); + expect(received).toMatch(/^HTTP\/1\.1 401 /); + expect(received.toLowerCase()).toContain('connection: close'); +}); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 3db5aa0b87c..f5edaa7b95c 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -19,7 +19,7 @@ import { normalizeTenantId, normalizeDaemonPublicOrigin, DAEMON_REQUEST_MAX_BYTES, - DAEMON_RPC_PREAUTH_TIMEOUT_MS, + DAEMON_RPC_PREAUTH_SLOTS, DAEMON_INSTANCE_REASONS, DAEMON_HTTP_CHECKED_RPC_CAPABILITY, DAEMON_HTTP_CHECKED_RPC_ROUTE, @@ -30,6 +30,13 @@ import { carriesUnbackedHostPathInstallSource, hostPathInstallSourceRefusedResponse, } from './install-source-admission.ts'; +import { + createRpcPreauthSlots, + preauthBusyResponse, + readRequestText, + refuseInvalidRpcEnvelope, + type RpcPreauth, +} from './rpc-ingress.ts'; /** * Carries one request to the upstream daemon and resolves with its response. Without `upstreamFetch` @@ -160,11 +167,12 @@ const FORWARDED_ARTIFACT_DOWNLOAD_RESPONSE_HEADERS = ['content-length']; export function createDaemonProxy(options: DaemonProxyOptions): DaemonProxy { const normalized = normalizeProxyOptions(options); const instanceId = randomUUID(); + const acquirePreauth = createRpcPreauthSlots(DAEMON_RPC_PREAUTH_SLOTS); return { instanceId, handle: async (request) => { try { - return await handleProxyRequest(request, normalized, instanceId); + return await handleProxyRequest(request, normalized, instanceId, acquirePreauth); } catch (error) { return proxyErrorResponse(error, request); } @@ -195,6 +203,7 @@ async function handleProxyRequest( request: Request, options: NormalizedProxyOptions, instanceId: string, + acquirePreauth: (clientSignal: AbortSignal) => RpcPreauth | null, ): Promise { const route = resolveProxyRoute(request.url); if (request.method === 'GET' && route === '/health') { @@ -215,19 +224,30 @@ async function handleProxyRequest( if (headerAuthenticated && !isAuthorized(request, options.clientToken ?? '', undefined)) { return unauthorizedResponse(route, null); } - const preauthSignal = headerAuthenticated - ? undefined - : AbortSignal.any([request.signal, AbortSignal.timeout(DAEMON_RPC_PREAUTH_TIMEOUT_MS)]); + const preauth = headerAuthenticated ? undefined : acquirePreauth(request.signal); + if (preauth === null) return preauthBusyResponse(); + return await handleRpcRoute(request, route, options, instanceId, preauth).finally(() => + preauth?.end(), + ); +} + +async function handleRpcRoute( + request: Request, + route: string, + options: NormalizedProxyOptions, + instanceId: string, + preauth: RpcPreauth | undefined, +): Promise { let rpcBody: string; try { rpcBody = await readRequestText( request, options.maxRpcBodyBytes, 'Proxy request body is too large.', - preauthSignal, + preauth?.signal, ); } catch (error) { - if (preauthSignal?.aborted) return unauthorizedResponse(route, null); + if (preauth?.deadline.aborted) return unauthorizedResponse(route, null); return rpcErrorResponse(null, error); } // The checked route checks its envelope after authentication and the protocol: a caller on @@ -236,7 +256,7 @@ 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, preauthSignal); + return await handleDaemonRoute(request, route, options, instanceId, rpcBody, preauth); } catch (error) { return rpcErrorResponse(readJsonRpcId(rpcBody), error); } @@ -248,9 +268,9 @@ async function handleDaemonRoute( options: NormalizedProxyOptions, instanceId: string, rpcBody?: string, - preauthSignal?: AbortSignal, + preauth?: RpcPreauth, ): Promise { - const caller = await authenticateCaller(request, options, rpcBody, preauthSignal); + const caller = await authenticateCaller(request, options, rpcBody, preauth); if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } @@ -291,29 +311,24 @@ async function authenticateCaller( request: Request, options: NormalizedProxyOptions, rpcBody: string | undefined, - preauthSignal: AbortSignal | undefined, + preauth: RpcPreauth | undefined, ): Promise { if (!options.authenticate) { return isAuthorized(request, options.clientToken ?? '', rpcBody) ? { uploadHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } : null; } - const authentication = options.authenticate( - forwardedRequest(request, request.url, { - method: request.method, - headers: request.headers, - signal: preauthSignal ?? request.signal, - ...(rpcBody !== undefined ? { body: rpcBody } : {}), - }), - ); - const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); - const result = await awaitWithSignal(Promise.resolve(authentication), preauthSignal).catch( - (error: unknown) => { - // A caller still unauthenticated at the deadline is refused as unauthenticated. - if (preauthSignal?.aborted) return null; - throw error; - }, + const authentication = Promise.resolve( + options.authenticate( + forwardedRequest(request, request.url, { + method: request.method, + headers: request.headers, + signal: preauth?.signal ?? request.signal, + ...(rpcBody !== undefined ? { body: rpcBody } : {}), + }), + ), ); + const result = preauth ? await preauth.authenticate(authentication) : await authentication; if (!result) return null; const tenantId = normalizeTenantId( typeof result.tenantId === 'string' ? result.tenantId : undefined, @@ -781,36 +796,6 @@ function resolveUpstreamBody( return request.body; } -async function readRequestText( - request: Request, - maxBodyBytes: number, - tooLargeMessage: string, - signal: AbortSignal | undefined, -): Promise { - if (!request.body) return ''; - const reader = request.body.getReader(); - const cancel = () => void reader.cancel().catch(() => {}); - signal?.addEventListener('abort', cancel, { once: true }); - const chunks: Uint8Array[] = []; - let bodyBytes = 0; - try { - for (;;) { - const { done, value } = await reader.read(); - if (done) break; - bodyBytes += value.byteLength; - if (bodyBytes > maxBodyBytes) { - await reader.cancel(); - throw new AppError('INVALID_ARGS', tooLargeMessage); - } - chunks.push(value); - } - signal?.throwIfAborted(); - } finally { - signal?.removeEventListener('abort', cancel); - } - return Buffer.concat(chunks).toString('utf8'); -} - function isAuthorized(request: Request, expectedToken: string, rpcBody: string | undefined) { const requestToken = resolveRequestToken(request, rpcBody); return requestToken.length > 0 && timingSafeStringEqual(requestToken, expectedToken); @@ -957,36 +942,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 = publicProxyError(error); diff --git a/packages/proxy/src/node-http.ts b/packages/proxy/src/node-http.ts index b5b8ed60866..cc432d78403 100644 --- a/packages/proxy/src/node-http.ts +++ b/packages/proxy/src/node-http.ts @@ -23,6 +23,9 @@ export async function serveProxyRequest( const response = await proxy.handle(toWebRequest(url, req, res)); res.statusCode = response.status; for (const [name, value] of response.headers) res.setHeader(name, value); + // An answer sent before the body was read, such as an early refusal, closes the connection + // instead of leaving Node to read and discard the rest of that body. + if (!req.complete) res.setHeader('connection', 'close'); if (!response.body) { res.end(); return; diff --git a/packages/proxy/src/rpc-ingress.ts b/packages/proxy/src/rpc-ingress.ts new file mode 100644 index 00000000000..e977464b0e8 --- /dev/null +++ b/packages/proxy/src/rpc-ingress.ts @@ -0,0 +1,138 @@ +import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { + DAEMON_RPC_PREAUTH_REASONS, + DAEMON_RPC_PREAUTH_TIMEOUT_MS, +} from '@agent-device/contracts/daemon-http'; + +/** The window in which an unauthenticated `/rpc` caller must send its body and authenticate. */ +export type RpcPreauth = { + /** Aborts at the deadline or when the client leaves. */ + signal: AbortSignal; + /** Aborts only at the deadline. */ + deadline: AbortSignal; + /** + * Waits for the `authenticate` call that got the body, then ends the window. `null` when the + * deadline came first. The slot stays held until that call settles. + */ + authenticate(pending: Promise): Promise; + /** Ends the window. The slot is free once the `authenticate` call settled too. */ + end(): void; +}; + +/** + * One proxy's pre-auth slots. A caller holds one from before its body is read until its + * authentication ends. `null` when every slot is held. + */ +export function createRpcPreauthSlots( + slots: number, +): (clientSignal: AbortSignal) => RpcPreauth | null { + let free = slots; + return (clientSignal) => { + if (free === 0) return null; + free -= 1; + let holds = 1; + const release = () => { + holds -= 1; + if (holds === 0) free += 1; + }; + let ended = false; + const end = () => { + if (ended) return; + ended = true; + release(); + }; + const deadline = AbortSignal.timeout(DAEMON_RPC_PREAUTH_TIMEOUT_MS); + const signal = AbortSignal.any([clientSignal, deadline]); + return { + signal, + deadline, + authenticate: async (pending) => { + holds += 1; + void pending.then(release, release); + try { + return await awaitWithSignal(pending, signal); + } catch (error) { + if (deadline.aborted) return null; + throw error; + } finally { + end(); + } + }, + end, + }; + }; +} + +/** The retryable answer to an `/rpc` caller that found every pre-auth slot held. */ +export function preauthBusyResponse(): Response { + const error = new AppError('COMMAND_FAILED', 'Too many unauthenticated requests', { + reason: DAEMON_RPC_PREAUTH_REASONS.preauthBusy.reason, + retriable: true, + }); + return Response.json( + { + jsonrpc: '2.0', + id: null, + error: { code: -32000, message: error.message, data: normalizeError(error) }, + }, + { status: 503 }, + ); +} + +/** + * Reads a request body up to `maxBodyBytes`. When `signal` aborts it stops waiting but leaves the + * stream alone: cancelling it would destroy a Node request before the refusal is written. + */ +export async function readRequestText( + request: Request, + maxBodyBytes: number, + tooLargeMessage: string, + signal: AbortSignal | undefined, +): Promise { + if (!request.body) return ''; + const reader = request.body.getReader(); + const chunks: Uint8Array[] = []; + let bodyBytes = 0; + for (;;) { + const { done, value } = await awaitWithSignal(reader.read(), signal); + if (done) break; + bodyBytes += value.byteLength; + if (bodyBytes > maxBodyBytes) { + await reader.cancel(); + throw new AppError('INVALID_ARGS', tooLargeMessage); + } + chunks.push(value); + } + return Buffer.concat(chunks).toString('utf8'); +} + +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 }, + ); +} diff --git a/packages/replay-port/src/__tests__/script-source-bundle.test.ts b/packages/replay-port/src/__tests__/script-source-bundle.test.ts index 9664ad4d920..cf80022f93c 100644 --- a/packages/replay-port/src/__tests__/script-source-bundle.test.ts +++ b/packages/replay-port/src/__tests__/script-source-bundle.test.ts @@ -1,10 +1,8 @@ import fs from 'node:fs'; import path from 'node:path'; import { expect, test } from 'vitest'; -import { - loadReplayScriptSourceBundle, - REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, -} from '@agent-device/replay-port/script-source-bundle'; +import { loadReplayScriptSourceBundle } from '@agent-device/replay-port/script-source-bundle'; +import { REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES } from '@agent-device/replay-port/script-source'; import { DAEMON_REQUEST_MAX_BYTES } from '@agent-device/contracts/daemon-http'; import { mkdtempForTestSync } from '../tmp-dir.fixtures.ts'; diff --git a/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts b/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts index 10e5f20264c..2b89a5e6035 100644 --- a/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts +++ b/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts @@ -1,10 +1,10 @@ import { expect, test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { readReplayScriptSourceFile } from '../script-source.ts'; import { assertReplayRequestScriptSources, + readReplayScriptSourceFile, REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, -} from '../../script-source-bundle.ts'; +} from '../script-source.ts'; test('a path the bundle does not own is missing, even when the prototype names it', () => { const bundle = { entry: '/flows/login.ad', files: { '/flows/login.ad': 'back\n' } }; diff --git a/packages/replay-port/src/daemon-port/replay-plugin-admission.ts b/packages/replay-port/src/daemon-port/replay-plugin-admission.ts index 190c2e802a5..5c9621fc849 100644 --- a/packages/replay-port/src/daemon-port/replay-plugin-admission.ts +++ b/packages/replay-port/src/daemon-port/replay-plugin-admission.ts @@ -10,7 +10,7 @@ export async function requireReplayPlugins(request: DaemonWireRequest): Promise< const backend = request.flags?.replayBackend; if (backend !== undefined && !isReplayBackendId(backend)) throw new AppError('INVALID_ARGS', unsupportedReplayBackendMessage(backend)); - const { assertReplayRequestScriptSources } = await import('../script-source-bundle.ts'); + const { assertReplayRequestScriptSources } = await import('./script-source.ts'); assertReplayRequestScriptSources(request.flags); if (request.command === 'test') await requireReplayTestPlugins(request, backend); else if (request.command === 'replay') await requireReplayEntryPlugin(request, backend); diff --git a/packages/replay-port/src/daemon-port/script-source.ts b/packages/replay-port/src/daemon-port/script-source.ts index 8ca58e3a22f..73729655b55 100644 --- a/packages/replay-port/src/daemon-port/script-source.ts +++ b/packages/replay-port/src/daemon-port/script-source.ts @@ -1,6 +1,9 @@ import { AppError } from '@agent-device/kernel/errors'; +import { isRecord } from '@agent-device/kernel/record'; import type { ReplayScriptSourceBundle } from '@agent-device/contracts/replay'; +export const REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES = 2 * 1024 * 1024; + export const REPLAY_SCRIPT_SOURCE_REQUIRED_MESSAGE = 'This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.'; @@ -18,3 +21,41 @@ export function readReplayScriptSourceFile( } return script; } + +/** + * The daemon's check of the script sources a client sent: each bundle is an entry plus text files + * and stays within the per-bundle limit. A suite may carry any number of bundles. + */ +export function assertReplayRequestScriptSources( + flags: { replayScriptSource?: unknown; replayScriptSources?: unknown } | undefined, +): void { + const { replayScriptSource: single, replayScriptSources: suite = [] } = flags ?? {}; + if (!Array.isArray(suite)) throw invalidScriptSourceBundle(); + for (const bundle of single === undefined ? suite : [single, ...suite]) { + if (!isRecord(bundle) || typeof bundle.entry !== 'string' || !isRecord(bundle.files)) { + throw invalidScriptSourceBundle(); + } + let totalBytes = 0; + for (const script of Object.values(bundle.files)) { + if (typeof script !== 'string') throw invalidScriptSourceBundle(); + totalBytes += Buffer.byteLength(script, 'utf8'); + } + assertBundleWithinLimit(totalBytes, bundle.entry); + } +} + +function invalidScriptSourceBundle(): AppError { + return new AppError( + 'INVALID_ARGS', + 'replay script sources must be bundles of an entry path and text files.', + ); +} + +export function assertBundleWithinLimit(totalBytes: number, inputPath: string): void { + if (totalBytes <= REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES) return; + throw new AppError( + 'INVALID_ARGS', + `replay script sources for ${inputPath} total ${totalBytes} bytes, over the ${REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES}-byte limit; split the flow or drop unused runFlow includes.`, + { limitBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, totalBytes }, + ); +} diff --git a/packages/replay-port/src/script-source-bundle.ts b/packages/replay-port/src/script-source-bundle.ts index 53e158a3cdb..d151c480770 100644 --- a/packages/replay-port/src/script-source-bundle.ts +++ b/packages/replay-port/src/script-source-bundle.ts @@ -1,12 +1,10 @@ import fs from 'node:fs'; import type { ReplayBackendResolver } from '@agent-device/contracts/replay-backend'; import { AppError } from '@agent-device/kernel/errors'; -import { isRecord } from '@agent-device/kernel/record'; import type { ReplayScriptSourceBundle } from '@agent-device/contracts/replay'; import { resolveUserPath } from '@agent-device/host-kit/path-resolution'; import { resolveReplayFormat } from '@agent-device/ad-script'; - -export const REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES = 2 * 1024 * 1024; +import { assertBundleWithinLimit } from './daemon-port/script-source.ts'; export type ReplayScriptSourceRequest = { inputPath: string; @@ -51,37 +49,12 @@ function finishBundle( files: Record, inputPath: string, ): ReplayScriptSourceBundle { - assertBundleWithinLimit(files, inputPath); - return { entry, files }; -} - -/** - * The daemon's check of the script sources a client sent: each bundle is an entry plus text files - * and stays within the per-bundle limit. A suite may carry any number of bundles. - */ -export function assertReplayRequestScriptSources( - flags: { replayScriptSource?: unknown; replayScriptSources?: unknown } | undefined, -): void { - const { replayScriptSource: single, replayScriptSources: suite = [] } = flags ?? {}; - if (!Array.isArray(suite)) throw invalidScriptSourceBundle(); - for (const bundle of single === undefined ? suite : [single, ...suite]) { - if ( - !isRecord(bundle) || - typeof bundle.entry !== 'string' || - !isRecord(bundle.files) || - !Object.values(bundle.files).every((script) => typeof script === 'string') - ) { - throw invalidScriptSourceBundle(); - } - assertBundleWithinLimit(bundle.files as Record, bundle.entry); - } -} - -function invalidScriptSourceBundle(): AppError { - return new AppError( - 'INVALID_ARGS', - 'replay script sources must be bundles of an entry path and text files.', + const totalBytes = Object.values(files).reduce( + (total, script) => total + Buffer.byteLength(script, 'utf8'), + 0, ); + assertBundleWithinLimit(totalBytes, inputPath); + return { entry, files }; } function readReplayEntryScript(resolvedPath: string, inputPath: string): string { @@ -107,16 +80,3 @@ function tryReadScriptFile(resolvedPath: string): string | undefined { return undefined; } } - -function assertBundleWithinLimit(files: Record, inputPath: string): void { - const totalBytes = Object.values(files).reduce( - (total, script) => total + Buffer.byteLength(script, 'utf8'), - 0, - ); - if (totalBytes <= REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES) return; - throw new AppError( - 'INVALID_ARGS', - `replay script sources for ${inputPath} total ${totalBytes} bytes, over the ${REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES}-byte limit; split the flow or drop unused runFlow includes.`, - { limitBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, totalBytes }, - ); -} diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 33c3d3f084f..bf34ff3b3ba 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -1091,6 +1091,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `insecure_credential_transport` | A first-party credential would go to a configured URL that is neither https nor plain http to a loopback host, and the CLI or SDK environment does not set AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1. The default proxy upstream has no override. | +| `remote_preauth_busy` | The daemon or proxy already holds its limit of callers that have not authenticated yet, so it answered HTTP 503 and closed the connection before it read the body. Retry after a short delay. | | `remote_instance_mismatch` | The daemon or proxy behind the remote URL was replaced since the client last read its health, so it refused a request addressed to the earlier instance. The client refreshes health and resends at most once; this reaches the caller when that resend is refused too. | | `remote_rpc_protocol_missing` | The checked RPC call named no RPC protocol. An intermediary that strips request headers causes this. | | `remote_rpc_protocol_mismatch` | The daemon or proxy speaks a different RPC protocol from the caller. After authentication, `details.service`, `details.version` and `details.rpcProtocolVersion` name the side that refused. | diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index fd1901503a3..3d7df3d673c 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -365,7 +365,7 @@ them to tell whether the daemon or the proxy answered. The proxy checks the client token and forwards authorized requests with the local daemon token. Remote clients never see the daemon token. -Send the token in the `authorization` or `x-agent-device-token` header. The proxy then refuses a wrong token before it reads the request body. An `/rpc` caller that sends no token header, or a proxy with `authenticate`, must finish the body and authentication within 30 seconds. Otherwise the request fails with `401`. The daemon closes an `/rpc` connection that has not passed authentication after 30 seconds. A daemon without an auth hook skips this limit when the header carries the daemon token. +Send the token in the `authorization` or `x-agent-device-token` header. The proxy then refuses a wrong token with `401` before it reads the request body, and closes the connection. An `/rpc` caller that sends no token header, or a proxy with `authenticate`, must finish the body and authentication within 30 seconds. Otherwise the request fails with `401`. If the body is still incomplete at that time, the proxy also closes the connection. The daemon closes an `/rpc` connection that has not passed authentication after 30 seconds. A daemon without an auth hook skips this limit when the header carries the daemon token. The daemon and the proxy each hold at most 4 unauthenticated `/rpc` callers at once. They answer another such caller with `503` and the retryable reason `remote_preauth_busy`, then close the connection. Retry it after a short delay. The proxy does not forward `/admin/*`, including human-control holds. A caller on the device host must use the daemon's loopback port and local daemon token. From 86cf14295e8e38db97798c35508816f9a011f13c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 09:31:34 +0100 Subject: [PATCH 03/11] fix(rpc): allow 16 concurrent pre-auth callers --- packages/contracts/src/daemon-http.ts | 2 +- website/docs/docs/remote-proxy.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index c485f6d89d8..7981c1002f8 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -140,7 +140,7 @@ export const DAEMON_REQUEST_MAX_BYTES = 64 * 1024 * 1024; */ export const DAEMON_RPC_PREAUTH_TIMEOUT_MS = 30_000; /** How many unauthenticated `/rpc` callers one daemon or one proxy holds at once. */ -export const DAEMON_RPC_PREAUTH_SLOTS = 4; +export const DAEMON_RPC_PREAUTH_SLOTS = 16; /** Why a daemon or proxy refused an `/rpc` caller before it read the request body. */ export const DAEMON_RPC_PREAUTH_REASONS = { diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 3d7df3d673c..fc232205333 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -365,7 +365,7 @@ them to tell whether the daemon or the proxy answered. The proxy checks the client token and forwards authorized requests with the local daemon token. Remote clients never see the daemon token. -Send the token in the `authorization` or `x-agent-device-token` header. The proxy then refuses a wrong token with `401` before it reads the request body, and closes the connection. An `/rpc` caller that sends no token header, or a proxy with `authenticate`, must finish the body and authentication within 30 seconds. Otherwise the request fails with `401`. If the body is still incomplete at that time, the proxy also closes the connection. The daemon closes an `/rpc` connection that has not passed authentication after 30 seconds. A daemon without an auth hook skips this limit when the header carries the daemon token. The daemon and the proxy each hold at most 4 unauthenticated `/rpc` callers at once. They answer another such caller with `503` and the retryable reason `remote_preauth_busy`, then close the connection. Retry it after a short delay. +Send the token in the `authorization` or `x-agent-device-token` header. The proxy then refuses a wrong token with `401` before it reads the request body, and closes the connection. An `/rpc` caller that sends no token header, or a proxy with `authenticate`, must finish the body and authentication within 30 seconds. Otherwise the request fails with `401`. If the body is still incomplete at that time, the proxy also closes the connection. The daemon closes an `/rpc` connection that has not passed authentication after 30 seconds. A daemon without an auth hook skips this limit when the header carries the daemon token. The daemon and the proxy each hold at most 16 unauthenticated `/rpc` callers at once. They answer another such caller with `503` and the retryable reason `remote_preauth_busy`, then close the connection. Retry it after a short delay. The proxy does not forward `/admin/*`, including human-control holds. A caller on the device host must use the daemon's loopback port and local daemon token. From bd46c731c19495e7ab98eb990841aa1b0b5e227e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 11:09:56 +0100 Subject: [PATCH 04/11] refactor(rpc): share one pre-auth admission primitive between daemon and proxy The daemon and the proxy each kept their own pre-auth slot counter and deadline. Both now use createRpcPreauthSlots from @agent-device/host-kit/transport: slot acquire and release, the deadline, the abort signal, and a hold that keeps a slot until a late authentication call settles. host-kit/transport is already in both eager closures, and contracts may not own timers. - The proxy ends the pre-auth window right after authentication, so a body-token caller no longer holds a slot while its command runs. - The proxy loads rpc-ingress.ts on demand, so its eager closure does not grow. - script-source-bundle.ts loads the daemon-safe bundle limit on demand, and script-source.ts no longer imports kernel/record, so neither the client closure nor the script-source closure grows. --- .../daemon/src/server/http/http-server.ts | 126 +++++++----------- packages/host-kit/src/internal/transport.ts | 64 +++++++++ packages/host-kit/src/transport.ts | 3 + packages/proxy/src/daemon-proxy.ts | 59 ++++---- packages/proxy/src/rpc-ingress.ts | 74 +--------- .../src/daemon-port/script-source.ts | 8 +- .../replay-port/src/script-source-bundle.ts | 12 +- 7 files changed, 165 insertions(+), 181 deletions(-) diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 022699b2099..91e6ca2d552 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -46,6 +46,11 @@ import { } from '@agent-device/contracts/daemon-http'; import { readVersion } from '@agent-device/host-kit/version'; import { readHostCpuArch } from '@agent-device/host-kit/process'; +import { + createRpcPreauthSlots, + type RpcPreauthSlots, + type RpcPreauthWindow, +} from '@agent-device/host-kit/transport'; import { shouldStreamRequestProgress } from '@agent-device/daemon-contracts/request-progress-protocol'; import type { DaemonCapability } from '@agent-device/daemon-contracts/daemon-resolution'; import { statusCodeForNormalizedError } from '../http-errors.ts'; @@ -165,7 +170,10 @@ export async function createDaemonHttpServer(options: { resolveRequestDiagnosticsPath, onUnownedRequestFailure, } = options; - const acquirePreauth = createPreauthSlots(DAEMON_RPC_PREAUTH_SLOTS); + const acquirePreauth = createRpcPreauthSlots( + DAEMON_RPC_PREAUTH_SLOTS, + DAEMON_RPC_PREAUTH_TIMEOUT_MS, + ); const onRequest = AsyncResource.bind((req: http.IncomingMessage, res: http.ServerResponse) => { const ingressUrl = nodeHttpRequestUrl(req.url, req.rawHeaders, req.socket instanceof TLSSocket); if (!ingressUrl) { @@ -249,13 +257,10 @@ export async function createDaemonHttpServer(options: { return; } - const preauthDeadline = headerProvesDaemonToken(req, authHook, token) + const preauth = headerProvesDaemonToken(req, authHook, token) ? undefined - : acquirePreauth(res); - if (preauthDeadline === null) { - refusePreauthBusy(res); - return; - } + : openPreauthWindow(acquirePreauth, res); + if (preauth === null) return; readRpcRequestBody(req, res, (body) => { // 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 @@ -270,7 +275,7 @@ export async function createDaemonHttpServer(options: { instanceId, handleRequest, checked, - preauthDeadline, + preauth, }).catch((error: unknown) => { sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); }); @@ -298,9 +303,8 @@ export async function createDaemonHttpServer(options: { } /** - * A caller whose header carries the daemon token is authenticated before its body is read. Any - * other caller is unauthenticated until admission, because the token may sit in the body and the - * auth hook reads the body. + * A header that carries the daemon token authenticates the caller before its body is read. Any + * other caller may carry its token in the body, or meets the auth hook, which reads the body. */ function headerProvesDaemonToken( req: http.IncomingMessage, @@ -310,66 +314,30 @@ function headerProvesDaemonToken( return !authHook && (!token || !enforceDaemonToken(resolveToken({}, req.headers), token)); } -/** The window in which an unauthenticated `/rpc` caller must send its body and pass admission. */ -type PreauthDeadline = { - /** Aborts at the deadline or when the connection closes before admission ends. */ - signal: AbortSignal; - /** Ends the window when admission ends, however it ends. */ - end(): void; - /** The hook as admission calls it: the slot stays held until each call settles. */ - holdDuring(authHook: HttpAuthHook | null): HttpAuthHook | null; -}; - /** - * One daemon's pre-auth slots. A caller holds one from before its body is read until admission - * ends and no auth hook that got its body still runs. `null` when every slot is held. + * Opens a pre-auth window whose deadline destroys the connection. When every slot is held, it + * answers a retryable 503 that closes the connection before the body is read, and returns `null`. */ -function createPreauthSlots(slots: number): (res: http.ServerResponse) => PreauthDeadline | null { - let free = slots; - return (res) => { - if (free === 0) return null; - free -= 1; - let holds = 1; - const release = () => { - holds -= 1; - if (holds === 0) free += 1; - }; - const controller = new AbortController(); - const timer = setTimeout(() => { - controller.abort(); - res.destroy(); - }, DAEMON_RPC_PREAUTH_TIMEOUT_MS); - let ended = false; - const end = () => { - if (ended) return; - ended = true; - clearTimeout(timer); - release(); - }; - res.once('close', () => { - if (!ended) controller.abort(); - end(); +function openPreauthWindow( + acquire: RpcPreauthSlots, + res: http.ServerResponse, +): RpcPreauthWindow | null { + const closed = new AbortController(); + const preauth = acquire(closed.signal, () => res.destroy()); + if (!preauth) { + const error = new AppError('COMMAND_FAILED', 'Too many unauthenticated requests', { + reason: DAEMON_RPC_PREAUTH_REASONS.preauthBusy.reason, + retriable: true, }); - const holdDuring = (authHook: HttpAuthHook | null): HttpAuthHook | null => - authHook && - ((context) => { - holds += 1; - const pending = Promise.resolve().then(() => authHook(context)); - void pending.then(release, release); - return pending; - }); - return { signal: controller.signal, end, holdDuring }; - }; -} - -/** Refuses an `/rpc` caller when every pre-auth slot is held, before its body is read. */ -function refusePreauthBusy(res: http.ServerResponse): void { - const error = new AppError('COMMAND_FAILED', 'Too many unauthenticated requests', { - reason: DAEMON_RPC_PREAUTH_REASONS.preauthBusy.reason, - retriable: true, + res.setHeader('connection', 'close'); + sendRpcRefusal(res, rpcRefusal(null, -32000, error.message, 503, normalizeError(error))); + return null; + } + res.once('close', () => { + closed.abort(); + preauth.end(); }); - res.setHeader('connection', 'close'); - sendRpcRefusal(res, rpcRefusal(null, -32000, error.message, 503, normalizeError(error))); + return preauth; } /** Accumulates one `/rpc` body and hands it to the flow once the stream ends. */ @@ -420,10 +388,10 @@ async function handleRpcRequest(params: { /** The call came on the checked route, so its protocol is checked before dispatch. */ checked: boolean; /** Absent when the caller's header already proved the daemon token. */ - preauthDeadline: PreauthDeadline | undefined; + preauth: RpcPreauthWindow | undefined; }): Promise { const { req, res, body, authHook, expectedToken, instanceId, handleRequest, checked } = params; - const { preauthDeadline } = params; + const { preauth } = 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; @@ -451,8 +419,8 @@ async function handleRpcRequest(params: { params: validated.params, lifetime, protocolRefusal, - preauth: preauthDeadline, - }).finally(() => preauthDeadline?.end()); + preauth, + }).finally(() => preauth?.end()); if (admission.outcome !== 'admitted') { if (admission.outcome === 'rejected') { sendRpcRefusal(res, admission.refusal); @@ -469,9 +437,9 @@ async function handleRpcRequest(params: { lifetime, }); } catch (error) { - // Reached only when the call never got as far as an invocation: unsound method params, - // an auth hook that outlived the pre-auth deadline, 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. + // Reached only when the call never got as far as an invocation: unsound method params, a + // pre-auth window that ran out, 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)); } finally { @@ -699,10 +667,10 @@ async function admitRpcRequest(params: { /** A checked call's protocol refusal, answered once the caller passes the auth gates. */ protocolRefusal: CheckedRpcProtocolRefusal | undefined; /** Absent when the caller's header already proved the daemon token. */ - preauth: PreauthDeadline | undefined; + preauth: RpcPreauthWindow | undefined; }): Promise { const { req, res, authHook, expectedToken, instanceId, rpcRequest, method, lifetime } = params; - const { protocolRefusal } = params; + const { protocolRefusal, preauth } = params; const wireRequest = methodToDaemonRequest(method, params.params, req.headers); // A command call naming no command is params the router cannot route. if (namesNoCommand(method, wireRequest)) { @@ -722,8 +690,10 @@ async function admitRpcRequest(params: { // decision, never an identity. const clientDeclaredTenant = daemonRequest.meta?.tenantId ?? daemonRequest.flags?.tenant; - const { preauth } = params; - const authResult = await runHttpAuthHook(preauth ? preauth.holdDuring(authHook) : authHook, { + // The pre-auth slot stays held until each hook call settles. + const heldHook: HttpAuthHook | null = + authHook && preauth ? (context) => preauth.hold(authHook(context)) : authHook; + const authResult = await runHttpAuthHook(heldHook, { headers: req.headers, rpcRequest, daemonRequest, diff --git a/packages/host-kit/src/internal/transport.ts b/packages/host-kit/src/internal/transport.ts index 99ba9455d2b..393a58a74b5 100644 --- a/packages/host-kit/src/internal/transport.ts +++ b/packages/host-kit/src/internal/transport.ts @@ -297,3 +297,67 @@ export function observeClientRequestPhases( }, }; } + +/** One unauthenticated `/rpc` caller's window: it must send its body and authenticate inside it. */ +export type RpcPreauthWindow = { + /** Aborts at the deadline or when the caller leaves. */ + signal: AbortSignal; + /** Aborts only at the deadline. */ + deadline: AbortSignal; + /** Waits for `pending`, but rejects with the abort reason once `signal` aborts. */ + wait(pending: T | PromiseLike): Promise; + /** Waits like `wait`, and keeps the slot held until `pending` settles, even after `end`. */ + hold(pending: T | PromiseLike): Promise; + /** Ends the window. */ + end(): void; +}; + +/** Opens a caller's window, or `null` when every slot is held. `onDeadline` runs at expiry. */ +export type RpcPreauthSlots = ( + callerGone: AbortSignal, + onDeadline?: () => void, +) => RpcPreauthWindow | null; + +/** The pre-auth slots of one daemon or one proxy. */ +export function createRpcPreauthSlots(slots: number, timeoutMs: number): RpcPreauthSlots { + let free = slots; + return (callerGone, onDeadline) => { + if (free === 0) return null; + free -= 1; + let holds = 1; + const release = () => { + holds -= 1; + if (holds === 0) free += 1; + }; + const deadline = new AbortController(); + const timer = setTimeout(() => { + deadline.abort(); + onDeadline?.(); + }, timeoutMs); + const signal = AbortSignal.any([callerGone, deadline.signal]); + const wait = (pending: T | PromiseLike) => + new Promise((resolve, reject) => { + const abort = () => reject(signal.reason); + signal.addEventListener('abort', abort, { once: true }); + if (signal.aborted) abort(); + void Promise.resolve(pending).then(resolve, reject); + }); + let ended = false; + return { + signal, + deadline: deadline.signal, + wait, + hold: (pending) => { + holds += 1; + void Promise.resolve(pending).then(release, release); + return wait(pending); + }, + end: () => { + if (ended) return; + ended = true; + clearTimeout(timer); + release(); + }, + }; + }; +} diff --git a/packages/host-kit/src/transport.ts b/packages/host-kit/src/transport.ts index eefbc20b972..46af8c37ab5 100644 --- a/packages/host-kit/src/transport.ts +++ b/packages/host-kit/src/transport.ts @@ -1,5 +1,6 @@ export { consumeTextLines, + createRpcPreauthSlots, createTransferPhaseWatchdog, isTransferPhaseTimeoutError, loadNodeHttpRequester, @@ -11,6 +12,8 @@ export { TRANSFER_BODY_INACTIVITY_TIMEOUT_MS, TRANSFER_CONNECT_TIMEOUT_MS, TRANSFER_RESPONSE_HEADER_TIMEOUT_MS, + type RpcPreauthSlots, + type RpcPreauthWindow, type TransferPhaseWatchdog, type NodeHttpRequester, } from './internal/transport.ts'; diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index f5edaa7b95c..9ae5d2fb090 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -1,7 +1,12 @@ import { randomUUID } from 'node:crypto'; import http from 'node:http'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; -import { timingSafeStringEqual } from '@agent-device/host-kit/transport'; +import { + createRpcPreauthSlots, + timingSafeStringEqual, + type RpcPreauthSlots, + type RpcPreauthWindow, +} from '@agent-device/host-kit/transport'; import { buildDaemonHealthPayload, buildDaemonInstanceMismatchRpcResponse, @@ -20,6 +25,7 @@ import { normalizeDaemonPublicOrigin, DAEMON_REQUEST_MAX_BYTES, DAEMON_RPC_PREAUTH_SLOTS, + DAEMON_RPC_PREAUTH_TIMEOUT_MS, DAEMON_INSTANCE_REASONS, DAEMON_HTTP_CHECKED_RPC_CAPABILITY, DAEMON_HTTP_CHECKED_RPC_ROUTE, @@ -30,13 +36,6 @@ import { carriesUnbackedHostPathInstallSource, hostPathInstallSourceRefusedResponse, } from './install-source-admission.ts'; -import { - createRpcPreauthSlots, - preauthBusyResponse, - readRequestText, - refuseInvalidRpcEnvelope, - type RpcPreauth, -} from './rpc-ingress.ts'; /** * Carries one request to the upstream daemon and resolves with its response. Without `upstreamFetch` @@ -167,7 +166,10 @@ const FORWARDED_ARTIFACT_DOWNLOAD_RESPONSE_HEADERS = ['content-length']; export function createDaemonProxy(options: DaemonProxyOptions): DaemonProxy { const normalized = normalizeProxyOptions(options); const instanceId = randomUUID(); - const acquirePreauth = createRpcPreauthSlots(DAEMON_RPC_PREAUTH_SLOTS); + const acquirePreauth = createRpcPreauthSlots( + DAEMON_RPC_PREAUTH_SLOTS, + DAEMON_RPC_PREAUTH_TIMEOUT_MS, + ); return { instanceId, handle: async (request) => { @@ -203,7 +205,7 @@ async function handleProxyRequest( request: Request, options: NormalizedProxyOptions, instanceId: string, - acquirePreauth: (clientSignal: AbortSignal) => RpcPreauth | null, + acquirePreauth: RpcPreauthSlots, ): Promise { const route = resolveProxyRoute(request.url); if (request.method === 'GET' && route === '/health') { @@ -225,7 +227,7 @@ async function handleProxyRequest( return unauthorizedResponse(route, null); } const preauth = headerAuthenticated ? undefined : acquirePreauth(request.signal); - if (preauth === null) return preauthBusyResponse(); + if (preauth === null) return (await import('./rpc-ingress.ts')).preauthBusyResponse(); return await handleRpcRoute(request, route, options, instanceId, preauth).finally(() => preauth?.end(), ); @@ -236,15 +238,16 @@ async function handleRpcRoute( route: string, options: NormalizedProxyOptions, instanceId: string, - preauth: RpcPreauth | undefined, + preauth: RpcPreauthWindow | undefined, ): Promise { + const { readRequestText, refuseInvalidRpcEnvelope } = await import('./rpc-ingress.ts'); let rpcBody: string; try { rpcBody = await readRequestText( request, options.maxRpcBodyBytes, 'Proxy request body is too large.', - preauth?.signal, + preauth, ); } catch (error) { if (preauth?.deadline.aborted) return unauthorizedResponse(route, null); @@ -268,15 +271,17 @@ async function handleDaemonRoute( options: NormalizedProxyOptions, instanceId: string, rpcBody?: string, - preauth?: RpcPreauth, + preauth?: RpcPreauthWindow, ): Promise { const caller = await authenticateCaller(request, options, rpcBody, preauth); + preauth?.end(); if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } 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-ingress.ts'); const refusal = (await refuseCheckedRpcProtocol(request, readJsonRpcId(rpcBody))) ?? refuseInvalidRpcEnvelope(rpcBody ?? ''); @@ -311,24 +316,28 @@ async function authenticateCaller( request: Request, options: NormalizedProxyOptions, rpcBody: string | undefined, - preauth: RpcPreauth | undefined, + preauth: RpcPreauthWindow | undefined, ): Promise { if (!options.authenticate) { return isAuthorized(request, options.clientToken ?? '', rpcBody) ? { uploadHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } : null; } - const authentication = Promise.resolve( - options.authenticate( - forwardedRequest(request, request.url, { - method: request.method, - headers: request.headers, - signal: preauth?.signal ?? request.signal, - ...(rpcBody !== undefined ? { body: rpcBody } : {}), - }), - ), + const authentication = options.authenticate( + forwardedRequest(request, request.url, { + method: request.method, + headers: request.headers, + signal: preauth?.signal ?? request.signal, + ...(rpcBody !== undefined ? { body: rpcBody } : {}), + }), ); - const result = preauth ? await preauth.authenticate(authentication) : await authentication; + let result; + try { + result = await (preauth ? preauth.hold(authentication) : authentication); + } catch (error) { + if (preauth?.deadline.aborted) return null; + throw error; + } if (!result) return null; const tenantId = normalizeTenantId( typeof result.tenantId === 'string' ? result.tenantId : undefined, diff --git a/packages/proxy/src/rpc-ingress.ts b/packages/proxy/src/rpc-ingress.ts index e977464b0e8..7c8c0a3d518 100644 --- a/packages/proxy/src/rpc-ingress.ts +++ b/packages/proxy/src/rpc-ingress.ts @@ -1,68 +1,6 @@ -import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; -import { - DAEMON_RPC_PREAUTH_REASONS, - DAEMON_RPC_PREAUTH_TIMEOUT_MS, -} from '@agent-device/contracts/daemon-http'; - -/** The window in which an unauthenticated `/rpc` caller must send its body and authenticate. */ -export type RpcPreauth = { - /** Aborts at the deadline or when the client leaves. */ - signal: AbortSignal; - /** Aborts only at the deadline. */ - deadline: AbortSignal; - /** - * Waits for the `authenticate` call that got the body, then ends the window. `null` when the - * deadline came first. The slot stays held until that call settles. - */ - authenticate(pending: Promise): Promise; - /** Ends the window. The slot is free once the `authenticate` call settled too. */ - end(): void; -}; - -/** - * One proxy's pre-auth slots. A caller holds one from before its body is read until its - * authentication ends. `null` when every slot is held. - */ -export function createRpcPreauthSlots( - slots: number, -): (clientSignal: AbortSignal) => RpcPreauth | null { - let free = slots; - return (clientSignal) => { - if (free === 0) return null; - free -= 1; - let holds = 1; - const release = () => { - holds -= 1; - if (holds === 0) free += 1; - }; - let ended = false; - const end = () => { - if (ended) return; - ended = true; - release(); - }; - const deadline = AbortSignal.timeout(DAEMON_RPC_PREAUTH_TIMEOUT_MS); - const signal = AbortSignal.any([clientSignal, deadline]); - return { - signal, - deadline, - authenticate: async (pending) => { - holds += 1; - void pending.then(release, release); - try { - return await awaitWithSignal(pending, signal); - } catch (error) { - if (deadline.aborted) return null; - throw error; - } finally { - end(); - } - }, - end, - }; - }; -} +import { DAEMON_RPC_PREAUTH_REASONS } from '@agent-device/contracts/daemon-http'; +import type { RpcPreauthWindow } from '@agent-device/host-kit/transport'; /** The retryable answer to an `/rpc` caller that found every pre-auth slot held. */ export function preauthBusyResponse(): Response { @@ -81,21 +19,21 @@ export function preauthBusyResponse(): Response { } /** - * Reads a request body up to `maxBodyBytes`. When `signal` aborts it stops waiting but leaves the - * stream alone: cancelling it would destroy a Node request before the refusal is written. + * Reads a request body up to `maxBodyBytes`. When the pre-auth window aborts it stops waiting but + * leaves the stream alone: cancelling it would destroy a Node request before the refusal is written. */ export async function readRequestText( request: Request, maxBodyBytes: number, tooLargeMessage: string, - signal: AbortSignal | undefined, + preauth: RpcPreauthWindow | undefined, ): Promise { if (!request.body) return ''; const reader = request.body.getReader(); const chunks: Uint8Array[] = []; let bodyBytes = 0; for (;;) { - const { done, value } = await awaitWithSignal(reader.read(), signal); + const { done, value } = await (preauth ? preauth.wait(reader.read()) : reader.read()); if (done) break; bodyBytes += value.byteLength; if (bodyBytes > maxBodyBytes) { diff --git a/packages/replay-port/src/daemon-port/script-source.ts b/packages/replay-port/src/daemon-port/script-source.ts index 73729655b55..ab88d6d954f 100644 --- a/packages/replay-port/src/daemon-port/script-source.ts +++ b/packages/replay-port/src/daemon-port/script-source.ts @@ -1,5 +1,4 @@ import { AppError } from '@agent-device/kernel/errors'; -import { isRecord } from '@agent-device/kernel/record'; import type { ReplayScriptSourceBundle } from '@agent-device/contracts/replay'; export const REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES = 2 * 1024 * 1024; @@ -32,15 +31,16 @@ export function assertReplayRequestScriptSources( const { replayScriptSource: single, replayScriptSources: suite = [] } = flags ?? {}; if (!Array.isArray(suite)) throw invalidScriptSourceBundle(); for (const bundle of single === undefined ? suite : [single, ...suite]) { - if (!isRecord(bundle) || typeof bundle.entry !== 'string' || !isRecord(bundle.files)) { + const { entry, files } = (bundle ?? {}) as { entry?: unknown; files?: unknown }; + if (typeof entry !== 'string' || typeof files !== 'object' || !files || Array.isArray(files)) { throw invalidScriptSourceBundle(); } let totalBytes = 0; - for (const script of Object.values(bundle.files)) { + for (const script of Object.values(files)) { if (typeof script !== 'string') throw invalidScriptSourceBundle(); totalBytes += Buffer.byteLength(script, 'utf8'); } - assertBundleWithinLimit(totalBytes, bundle.entry); + assertBundleWithinLimit(totalBytes, entry); } } diff --git a/packages/replay-port/src/script-source-bundle.ts b/packages/replay-port/src/script-source-bundle.ts index d151c480770..f7a4b4bb77d 100644 --- a/packages/replay-port/src/script-source-bundle.ts +++ b/packages/replay-port/src/script-source-bundle.ts @@ -4,7 +4,6 @@ import { AppError } from '@agent-device/kernel/errors'; import type { ReplayScriptSourceBundle } from '@agent-device/contracts/replay'; import { resolveUserPath } from '@agent-device/host-kit/path-resolution'; import { resolveReplayFormat } from '@agent-device/ad-script'; -import { assertBundleWithinLimit } from './daemon-port/script-source.ts'; export type ReplayScriptSourceRequest = { inputPath: string; @@ -22,7 +21,7 @@ export async function loadReplayScriptSourceBundle( const entrySource = readReplayEntryScript(entry, params.inputPath); const backendId = resolveReplayFormat(entry, params.replayBackend); if (backendId === 'ad') { - return finishBundle(entry, { [entry]: entrySource }, params.inputPath); + return await finishBundle(entry, { [entry]: entrySource }, params.inputPath); } // Function-scoped on purpose: the eager-closure budget gate counts a static import here as a // module every warm CLI command evaluates, for a format most runs never use (#1802), and the @@ -41,19 +40,20 @@ export async function loadReplayScriptSourceBundle( }), params.resolveReplayBackend, ); - return finishBundle(entry, files, params.inputPath); + return await finishBundle(entry, files, params.inputPath); } -function finishBundle( +async function finishBundle( entry: string, files: Record, inputPath: string, -): ReplayScriptSourceBundle { +): Promise { const totalBytes = Object.values(files).reduce( (total, script) => total + Buffer.byteLength(script, 'utf8'), 0, ); - assertBundleWithinLimit(totalBytes, inputPath); + // Function-scoped: the daemon-safe owner of the limit stays out of the warm CLI closure. + (await import('./daemon-port/script-source.ts')).assertBundleWithinLimit(totalBytes, inputPath); return { entry, files }; } From b813a1cfbf25a83b2f30f47e90f6be059371e895 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 11:42:34 +0100 Subject: [PATCH 05/11] fix(proxy): close early refusals and release settled pre-auth waits --- .../server/http/http-server-rpc-preauth-deadline.test.ts | 2 +- packages/host-kit/src/internal/transport.ts | 4 +++- packages/proxy/src/daemon-proxy-preauth.test.ts | 5 +++-- packages/proxy/src/node-http.ts | 7 ++++--- packages/proxy/src/rpc-ingress.ts | 2 +- 5 files changed, 12 insertions(+), 8 deletions(-) diff --git a/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts index fb7f3999564..8fcd73e1821 100644 --- a/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts +++ b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts @@ -62,7 +62,7 @@ test('an unauthenticated rpc caller that stalls its body is closed at the pre-au 'Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"', ); await closed; - assert.ok(Date.now() - startedAt < 5_000, 'the deadline, not a Node ceiling, closed it'); + assert.ok(Date.now() - startedAt < 2_000, 'the deadline, not a Node ceiling, closed it'); assert.equal(handlerCalls, 0); } finally { socket.destroy(); diff --git a/packages/host-kit/src/internal/transport.ts b/packages/host-kit/src/internal/transport.ts index 393a58a74b5..af33520cd61 100644 --- a/packages/host-kit/src/internal/transport.ts +++ b/packages/host-kit/src/internal/transport.ts @@ -340,7 +340,9 @@ export function createRpcPreauthSlots(slots: number, timeoutMs: number): RpcPrea const abort = () => reject(signal.reason); signal.addEventListener('abort', abort, { once: true }); if (signal.aborted) abort(); - void Promise.resolve(pending).then(resolve, reject); + void Promise.resolve(pending) + .finally(() => signal.removeEventListener('abort', abort)) + .then(resolve, reject); }); let ended = false; return { diff --git a/packages/proxy/src/daemon-proxy-preauth.test.ts b/packages/proxy/src/daemon-proxy-preauth.test.ts index a4fa4b11470..96842d6b0e3 100644 --- a/packages/proxy/src/daemon-proxy-preauth.test.ts +++ b/packages/proxy/src/daemon-proxy-preauth.test.ts @@ -85,10 +85,11 @@ async function stalledNodeExchange(server: http.Server, headers: string): Promis `POST /agent-device/rpc HTTP/1.1\r\nHost: 127.0.0.1\r\n${headers}` + 'Content-Type: application/json\r\nContent-Length: 1024\r\n\r\n{"jsonrpc":"2.0"', ); + let fallback: NodeJS.Timeout | undefined; const closed = await new Promise((resolve) => { socket.once('close', () => resolve(true)); - setTimeout(() => resolve(false), 2_000); - }); + fallback = setTimeout(() => resolve(false), 2_000); + }).finally(() => clearTimeout(fallback)); expect(closed, 'the proxy closed the connection').toBe(true); return received; } finally { diff --git a/packages/proxy/src/node-http.ts b/packages/proxy/src/node-http.ts index cc432d78403..8a57bc6f29e 100644 --- a/packages/proxy/src/node-http.ts +++ b/packages/proxy/src/node-http.ts @@ -12,12 +12,12 @@ export async function serveProxyRequest( ): Promise { // Fetch refuses TRACE. node:http rejects TRACK and routes CONNECT to the 'connect' event. if (req.method === 'TRACE') { - endWithStatus(res, 404); + endWithStatus(req, res, 404); return; } const url = requestUrl(req); if (!url) { - endWithStatus(res, 400); + endWithStatus(req, res, 400); return; } const response = await proxy.handle(toWebRequest(url, req, res)); @@ -33,8 +33,9 @@ export async function serveProxyRequest( await pipeline(Readable.fromWeb(response.body as Parameters[0]), res); } -function endWithStatus(res: ServerResponse, status: number): void { +function endWithStatus(req: IncomingMessage, res: ServerResponse, status: number): void { res.statusCode = status; + if (!req.complete) res.setHeader('connection', 'close'); res.end(); } diff --git a/packages/proxy/src/rpc-ingress.ts b/packages/proxy/src/rpc-ingress.ts index 7c8c0a3d518..fcf1e148eb1 100644 --- a/packages/proxy/src/rpc-ingress.ts +++ b/packages/proxy/src/rpc-ingress.ts @@ -14,7 +14,7 @@ export function preauthBusyResponse(): Response { id: null, error: { code: -32000, message: error.message, data: normalizeError(error) }, }, - { status: 503 }, + { status: 503, headers: { connection: 'close' } }, ); } From f9bf3b451b445f06400327c5a7401bc74b0a8773 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 12:33:47 +0100 Subject: [PATCH 06/11] fix(proxy): retire pre-auth slots once on abort and end refused windows at once A slot now retires exactly once, when its window ends or its signal aborts, so a hung auth hook no longer holds it past the deadline. The daemon ends the window at every terminal refusal, clears the buffered body at handoff, and both busy answers carry dispatched 'no'. The proxy no longer awaits reader.cancel. Co-Authored-By: Claude --- .../http-server-rpc-preauth-deadline.test.ts | 48 +++++++++++++++++++ .../daemon/src/server/http/http-server.ts | 26 +++++----- .../host-kit/src/internal/transport.test.ts | 15 ++++++ packages/host-kit/src/internal/transport.ts | 44 ++++------------- .../proxy/src/daemon-proxy-preauth.test.ts | 5 +- packages/proxy/src/daemon-proxy.ts | 5 +- packages/proxy/src/rpc-ingress.ts | 14 +++--- website/docs/docs/remote-proxy.md | 2 +- 8 files changed, 103 insertions(+), 56 deletions(-) diff --git a/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts index 8fcd73e1821..1ec2f4c356e 100644 --- a/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts +++ b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts @@ -133,3 +133,51 @@ test('a caller that leaves while the auth hook runs aborts the hook signal', asy Reflect.deleteProperty(globalThis, '__preauthHook'); } }); + +test('a refusal queued behind an earlier answer frees its pre-auth slot before that answer', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { createDaemonHttpServer } = await import('./http-server.ts'); + const slowAnswer = Promise.withResolvers(); + const server = await createDaemonHttpServer({ + token: 'daemon-secret', + handleRequest: async (): Promise => { + await slowAnswer.promise; + return { ok: true, data: {} }; + }, + env: process.env, + cwd: process.cwd(), + }); + const port = await listenOnLoopback(server); + const pipelined = connect(port); + const next = connect(port); + try { + const refused = new Promise((resolve) => { + let requests = 0; + server.on('request', (req: NodeJS.ReadableStream) => { + if (++requests === 2) req.once('end', () => setImmediate(resolve)); + }); + }); + const call = JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'agent_device.command', + params: { command: 'devices' }, + }); + pipelined.write( + `${RPC_HEAD}x-agent-device-token: daemon-secret\r\nContent-Length: ${call.length}\r\n\r\n${call}` + + `${RPC_HEAD}Content-Length: 1\r\n\r\nx`, + ); + await refused; + let received = ''; + next.on('data', (chunk) => (received += chunk.toString('utf8'))); + const closed = new Promise((resolve) => next.once('close', () => resolve())); + next.write(`${RPC_HEAD}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`); + await closed; + assert.doesNotMatch(received, /503/, 'the queued refusal held no slot'); + } finally { + slowAnswer.resolve(); + pipelined.destroy(); + next.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 91e6ca2d552..9e0abe13902 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -276,9 +276,12 @@ export async function createDaemonHttpServer(options: { handleRequest, checked, preauth, - }).catch((error: unknown) => { - sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); - }); + }) + .catch((error: unknown) => { + sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); + }) + // A refusal answered behind an earlier response ends its window now, not at close. + .finally(() => preauth?.end()); }); }); // Socket ingress ceilings from one owner (ingress-budget.ts). They bound socket ingress @@ -327,16 +330,14 @@ function openPreauthWindow( if (!preauth) { const error = new AppError('COMMAND_FAILED', 'Too many unauthenticated requests', { reason: DAEMON_RPC_PREAUTH_REASONS.preauthBusy.reason, + dispatched: 'no', retriable: true, }); res.setHeader('connection', 'close'); sendRpcRefusal(res, rpcRefusal(null, -32000, error.message, 503, normalizeError(error))); return null; } - res.once('close', () => { - closed.abort(); - preauth.end(); - }); + res.once('close', () => closed.abort()); return preauth; } @@ -358,6 +359,7 @@ function readRpcRequestBody( }); req.on('error', () => { + body = ''; if (!res.headersSent) { sendRpcRefusal(res, rpcParseErrorRefusal()); } @@ -366,7 +368,10 @@ function readRpcRequestBody( req.on( 'end', AsyncResource.bind(() => { - onBody(body); + const text = body; + // A queued response keeps this request alive, so the listener must not keep its body. + body = ''; + onBody(text); }), ); } @@ -690,10 +695,7 @@ async function admitRpcRequest(params: { // decision, never an identity. const clientDeclaredTenant = daemonRequest.meta?.tenantId ?? daemonRequest.flags?.tenant; - // The pre-auth slot stays held until each hook call settles. - const heldHook: HttpAuthHook | null = - authHook && preauth ? (context) => preauth.hold(authHook(context)) : authHook; - const authResult = await runHttpAuthHook(heldHook, { + const authResult = await runHttpAuthHook(authHook, { headers: req.headers, rpcRequest, daemonRequest, diff --git a/packages/host-kit/src/internal/transport.test.ts b/packages/host-kit/src/internal/transport.test.ts index 51dfd5420bf..90dfe34a30a 100644 --- a/packages/host-kit/src/internal/transport.test.ts +++ b/packages/host-kit/src/internal/transport.test.ts @@ -8,6 +8,7 @@ import { test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; import { consumeTextLines, + createRpcPreauthSlots, loadNodeHttpRequester, readNodeHttpRequestBody, readNodeHttpResponseBody, @@ -107,3 +108,17 @@ test('readNodeHttpResponseBody propagates response errors', async () => { response.emit('error', error); await assert.rejects(promise, error); }); + +test('a pre-auth slot retires exactly once, at end or at abort', () => { + const acquire = createRpcPreauthSlots(1, 60_000); + const gone = new AbortController(); + const first = acquire(gone.signal); + assert.ok(first); + assert.equal(acquire(new AbortController().signal), null); + gone.abort(); + first.end(); + const second = acquire(new AbortController().signal); + assert.ok(second, 'the caller leaving retired its slot'); + assert.equal(acquire(new AbortController().signal), null, 'end after abort freed no extra slot'); + second.end(); +}); diff --git a/packages/host-kit/src/internal/transport.ts b/packages/host-kit/src/internal/transport.ts index af33520cd61..1e392fd0cca 100644 --- a/packages/host-kit/src/internal/transport.ts +++ b/packages/host-kit/src/internal/transport.ts @@ -304,11 +304,7 @@ export type RpcPreauthWindow = { signal: AbortSignal; /** Aborts only at the deadline. */ deadline: AbortSignal; - /** Waits for `pending`, but rejects with the abort reason once `signal` aborts. */ - wait(pending: T | PromiseLike): Promise; - /** Waits like `wait`, and keeps the slot held until `pending` settles, even after `end`. */ - hold(pending: T | PromiseLike): Promise; - /** Ends the window. */ + /** Ends the window. The slot retires exactly once, here or when `signal` aborts. */ end(): void; }; @@ -324,42 +320,22 @@ export function createRpcPreauthSlots(slots: number, timeoutMs: number): RpcPrea return (callerGone, onDeadline) => { if (free === 0) return null; free -= 1; - let holds = 1; - const release = () => { - holds -= 1; - if (holds === 0) free += 1; - }; const deadline = new AbortController(); const timer = setTimeout(() => { deadline.abort(); onDeadline?.(); }, timeoutMs); const signal = AbortSignal.any([callerGone, deadline.signal]); - const wait = (pending: T | PromiseLike) => - new Promise((resolve, reject) => { - const abort = () => reject(signal.reason); - signal.addEventListener('abort', abort, { once: true }); - if (signal.aborted) abort(); - void Promise.resolve(pending) - .finally(() => signal.removeEventListener('abort', abort)) - .then(resolve, reject); - }); let ended = false; - return { - signal, - deadline: deadline.signal, - wait, - hold: (pending) => { - holds += 1; - void Promise.resolve(pending).then(release, release); - return wait(pending); - }, - end: () => { - if (ended) return; - ended = true; - clearTimeout(timer); - release(); - }, + const end = () => { + if (ended) return; + ended = true; + clearTimeout(timer); + signal.removeEventListener('abort', end); + free += 1; }; + signal.addEventListener('abort', end, { once: true }); + if (signal.aborted) end(); + return { signal, deadline: deadline.signal, end }; }; } diff --git a/packages/proxy/src/daemon-proxy-preauth.test.ts b/packages/proxy/src/daemon-proxy-preauth.test.ts index 96842d6b0e3..85de1d91181 100644 --- a/packages/proxy/src/daemon-proxy-preauth.test.ts +++ b/packages/proxy/src/daemon-proxy-preauth.test.ts @@ -56,7 +56,10 @@ test('an authenticate hook that never answers is refused at the pre-auth deadlin headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent_device.command', params: {} }), }); + const next = request.clone(); expect((await proxy.handle(request)).status).toBe(401); + // The hook still runs, but the expired caller's slot is free for the next one. + expect((await proxy.handle(next)).status).toBe(401); }); test('a second unauthenticated caller is refused with a retryable 503 while the slot is held', async () => { @@ -67,7 +70,7 @@ test('a second unauthenticated caller is refused with a retryable 503 while the const body = (await response.json()) as { error: { data: Record } }; expect(body.error.data).toMatchObject({ retriable: true, - details: { reason: 'remote_preauth_busy' }, + details: { reason: 'remote_preauth_busy', dispatched: 'no' }, }); expect((await first).status).toBe(401); }); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 9ae5d2fb090..7648291cdc2 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -1,6 +1,7 @@ import { randomUUID } from 'node:crypto'; import http from 'node:http'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { createRpcPreauthSlots, timingSafeStringEqual, @@ -247,7 +248,7 @@ async function handleRpcRoute( request, options.maxRpcBodyBytes, 'Proxy request body is too large.', - preauth, + preauth?.signal, ); } catch (error) { if (preauth?.deadline.aborted) return unauthorizedResponse(route, null); @@ -333,7 +334,7 @@ async function authenticateCaller( ); let result; try { - result = await (preauth ? preauth.hold(authentication) : authentication); + result = await awaitWithSignal(Promise.resolve(authentication), preauth?.signal); } catch (error) { if (preauth?.deadline.aborted) return null; throw error; diff --git a/packages/proxy/src/rpc-ingress.ts b/packages/proxy/src/rpc-ingress.ts index fcf1e148eb1..c960fdeb2bd 100644 --- a/packages/proxy/src/rpc-ingress.ts +++ b/packages/proxy/src/rpc-ingress.ts @@ -1,11 +1,12 @@ import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { DAEMON_RPC_PREAUTH_REASONS } from '@agent-device/contracts/daemon-http'; -import type { RpcPreauthWindow } from '@agent-device/host-kit/transport'; +import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; /** The retryable answer to an `/rpc` caller that found every pre-auth slot held. */ export function preauthBusyResponse(): Response { const error = new AppError('COMMAND_FAILED', 'Too many unauthenticated requests', { reason: DAEMON_RPC_PREAUTH_REASONS.preauthBusy.reason, + dispatched: 'no', retriable: true, }); return Response.json( @@ -19,25 +20,26 @@ export function preauthBusyResponse(): Response { } /** - * Reads a request body up to `maxBodyBytes`. When the pre-auth window aborts it stops waiting but - * leaves the stream alone: cancelling it would destroy a Node request before the refusal is written. + * Reads a request body up to `maxBodyBytes`. When `signal` aborts it stops waiting but leaves the + * stream alone: cancelling it would destroy a Node request before the refusal is written. Over the + * limit, it starts the cancel without waiting for it, since a source may never settle it. */ export async function readRequestText( request: Request, maxBodyBytes: number, tooLargeMessage: string, - preauth: RpcPreauthWindow | undefined, + signal: AbortSignal | undefined, ): Promise { if (!request.body) return ''; const reader = request.body.getReader(); const chunks: Uint8Array[] = []; let bodyBytes = 0; for (;;) { - const { done, value } = await (preauth ? preauth.wait(reader.read()) : reader.read()); + const { done, value } = await awaitWithSignal(reader.read(), signal); if (done) break; bodyBytes += value.byteLength; if (bodyBytes > maxBodyBytes) { - await reader.cancel(); + reader.cancel().catch(() => {}); throw new AppError('INVALID_ARGS', tooLargeMessage); } chunks.push(value); diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index fc232205333..904da62b741 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -365,7 +365,7 @@ them to tell whether the daemon or the proxy answered. The proxy checks the client token and forwards authorized requests with the local daemon token. Remote clients never see the daemon token. -Send the token in the `authorization` or `x-agent-device-token` header. The proxy then refuses a wrong token with `401` before it reads the request body, and closes the connection. An `/rpc` caller that sends no token header, or a proxy with `authenticate`, must finish the body and authentication within 30 seconds. Otherwise the request fails with `401`. If the body is still incomplete at that time, the proxy also closes the connection. The daemon closes an `/rpc` connection that has not passed authentication after 30 seconds. A daemon without an auth hook skips this limit when the header carries the daemon token. The daemon and the proxy each hold at most 16 unauthenticated `/rpc` callers at once. They answer another such caller with `503` and the retryable reason `remote_preauth_busy`, then close the connection. Retry it after a short delay. +Send the token in the `authorization` or `x-agent-device-token` header. The proxy then refuses a wrong token with `401` before it reads the request body. An `/rpc` caller that sends no token header, or a proxy with `authenticate`, must finish the body and authentication within 30 seconds. Otherwise the request fails with `401`. When the proxy's Node HTTP adapter answers before the body is complete, it closes the connection. The daemon closes an `/rpc` connection that has not passed authentication after 30 seconds. A daemon without an auth hook skips this limit when the header carries the daemon token. The daemon and the proxy each hold at most 16 unauthenticated `/rpc` callers at once. They answer another such caller with `503` and the retryable reason `remote_preauth_busy`. The daemon and the proxy's Node HTTP adapter then close the connection. Retry it after a short delay. The proxy does not forward `/admin/*`, including human-control holds. A caller on the device host must use the daemon's loopback port and local daemon token. From d0f7c8319dafeb02fe16a4323351ded9061a6341 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 12:38:49 +0100 Subject: [PATCH 07/11] perf(proxy): load awaitWithSignal only on the authenticate path --- packages/proxy/src/daemon-proxy.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 7648291cdc2..14d0ce3230f 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -1,7 +1,6 @@ import { randomUUID } from 'node:crypto'; import http from 'node:http'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; -import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { createRpcPreauthSlots, timingSafeStringEqual, @@ -332,6 +331,7 @@ async function authenticateCaller( ...(rpcBody !== undefined ? { body: rpcBody } : {}), }), ); + const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); let result; try { result = await awaitWithSignal(Promise.resolve(authentication), preauth?.signal); From 9f5daa84c20b79f9f070607d3e620f20c9f33246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 13:28:40 +0100 Subject: [PATCH 08/11] fix(remote): fence pipelined requests behind a scheduled close At the pre-auth deadline the daemon answers one 401 with Connection: close and detaches the body reader instead of destroying the response. A busy 503 or expiry 401 marks its socket closing, and later requests on it are declined before admission. The proxy's Node adapter holds later requests on a socket until the earlier one is admitted or answered, and declines them before forwarding when that answer closes the connection. The proxy loads awaitWithSignal before it calls authenticate, so a rejection is handled at once. --- .../http-server-rpc-preauth-deadline.test.ts | 82 +++++++++++++++++++ .../daemon/src/server/http/http-server.ts | 54 +++++++++--- .../proxy/src/daemon-proxy-preauth.test.ts | 52 ++++++++++++ packages/proxy/src/daemon-proxy.ts | 5 +- packages/proxy/src/node-http.ts | 58 +++++++------ packages/proxy/src/rpc-ingress.ts | 6 ++ 6 files changed, 218 insertions(+), 39 deletions(-) diff --git a/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts index 1ec2f4c356e..47ccd54168d 100644 --- a/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts +++ b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts @@ -54,6 +54,8 @@ test('an unauthenticated rpc caller that stalls its body is closed at the pre-au const socket = net.connect(port, '127.0.0.1'); socket.on('error', () => {}); try { + let received = ''; + socket.on('data', (chunk) => (received += chunk.toString('utf8'))); const closed = new Promise((resolve) => socket.once('close', () => resolve())); const startedAt = Date.now(); // No token header, so the token can only be in a body that never finishes. @@ -63,6 +65,7 @@ test('an unauthenticated rpc caller that stalls its body is closed at the pre-au ); await closed; assert.ok(Date.now() - startedAt < 2_000, 'the deadline, not a Node ceiling, closed it'); + assert.deepEqual(received.match(/HTTP\/1\.1 \d+/g), ['HTTP/1.1 401']); assert.equal(handlerCalls, 0); } finally { socket.destroy(); @@ -181,3 +184,82 @@ test('a refusal queued behind an earlier answer frees its pre-auth slot before t await closeLoopbackServer(server); } }); + +const CALL = JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'agent_device.command', + params: { command: 'devices' }, +}); +const AUTHED_CALL = `${RPC_HEAD}x-agent-device-token: daemon-secret\r\nContent-Length: ${CALL.length}\r\n\r\n${CALL}`; + +async function startSlowDaemon() { + const { createDaemonHttpServer } = await import('./http-server.ts'); + const slowAnswer = Promise.withResolvers(); + const handled = { calls: 0 }; + const server = await createDaemonHttpServer({ + token: 'daemon-secret', + handleRequest: async (): Promise => { + handled.calls += 1; + await slowAnswer.promise; + return { ok: true, data: {} }; + }, + env: process.env, + cwd: process.cwd(), + }); + return { server, port: await listenOnLoopback(server), slowAnswer, handled }; +} + +async function readUntilClosed(socket: net.Socket, write: string): Promise { + let received = ''; + socket.on('data', (chunk) => (received += chunk.toString('utf8'))); + const closed = new Promise((resolve) => socket.once('close', () => resolve())); + socket.write(write); + await closed; + return received; +} + +test('a pre-auth deadline behind a queued answer refuses once with 401 and closes after it', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port, slowAnswer } = await startSlowDaemon(); + const socket = connect(port); + try { + const exchange = readUntilClosed( + socket, + `${AUTHED_CALL}${RPC_HEAD}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`, + ); + setTimeout(() => slowAnswer.resolve(), 400); + const received = await exchange; + assert.deepEqual(received.match(/HTTP\/1\.1 \d+/g), ['HTTP/1.1 200', 'HTTP/1.1 401']); + assert.match(received.slice(received.indexOf('HTTP/1.1 401')), /connection: close/i); + } finally { + slowAnswer.resolve(); + socket.destroy(); + await closeLoopbackServer(server); + } +}); + +test('a header-token call pipelined behind a queued 503 is declined before dispatch', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port, slowAnswer, handled } = await startSlowDaemon(); + const holder = connect(port); + const socket = connect(port); + try { + const held = new Promise((resolve) => server.once('request', resolve)); + holder.write(`${RPC_HEAD}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`); + await held; + const exchange = readUntilClosed( + socket, + `${AUTHED_CALL}${RPC_HEAD}Content-Length: 1\r\n\r\nx${AUTHED_CALL}`, + ); + setTimeout(() => slowAnswer.resolve(), 100); + const received = await exchange; + assert.deepEqual(received.match(/HTTP\/1\.1 \d+/g), ['HTTP/1.1 200', 'HTTP/1.1 503']); + assert.equal(handled.calls, 1, 'the later header-token call never ran'); + } finally { + slowAnswer.resolve(); + holder.destroy(); + socket.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 9e0abe13902..46929d58208 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -10,6 +10,7 @@ import { responseDisconnectSignal } from './response-disconnect-signal.ts'; import type { DaemonResponse, DaemonResponseData } from '@agent-device/kernel/contracts'; import { AsyncResource } from 'node:async_hooks'; import http from 'node:http'; +import type { Socket } from 'node:net'; import { TLSSocket } from 'node:tls'; import { randomUUID } from 'node:crypto'; import type { DiagnosticsRecordRef, NormalizedError } from '@agent-device/kernel/errors'; @@ -175,6 +176,11 @@ export async function createDaemonHttpServer(options: { DAEMON_RPC_PREAUTH_TIMEOUT_MS, ); const onRequest = AsyncResource.bind((req: http.IncomingMessage, res: http.ServerResponse) => { + // Its answer would be dropped by the close, so a request on a closing socket never runs. + if (closingSockets.has(req.socket)) { + refuseAndClose(res, preauthBusyRefusal()); + return; + } const ingressUrl = nodeHttpRequestUrl(req.url, req.rawHeaders, req.socket instanceof TLSSocket); if (!ingressUrl) { res.writeHead(400); @@ -261,7 +267,7 @@ export async function createDaemonHttpServer(options: { ? undefined : openPreauthWindow(acquirePreauth, res); if (preauth === null) return; - readRpcRequestBody(req, res, (body) => { + readRpcRequestBody(req, res, preauth?.deadline, (body) => { // 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 @@ -317,40 +323,62 @@ function headerProvesDaemonToken( return !authHook && (!token || !enforceDaemonToken(resolveToken({}, req.headers), token)); } +/** Sockets whose close is scheduled behind a refusal. */ +const closingSockets = new WeakSet(); + +/** + * Answers `refusal` and closes the socket once it flushes. Answers queued ahead of it still + * finish; every later request on the socket is declined before admission. + */ +function refuseAndClose(res: http.ServerResponse, refusal: RpcRefusal): void { + closingSockets.add(res.req.socket); + res.setHeader('connection', 'close'); + sendRpcRefusal(res, refusal); +} + +function preauthBusyRefusal(): RpcRefusal { + const error = new AppError('COMMAND_FAILED', 'Too many unauthenticated requests', { + reason: DAEMON_RPC_PREAUTH_REASONS.preauthBusy.reason, + dispatched: 'no', + retriable: true, + }); + return rpcRefusal(null, -32000, error.message, 503, normalizeError(error)); +} + /** - * Opens a pre-auth window whose deadline destroys the connection. When every slot is held, it - * answers a retryable 503 that closes the connection before the body is read, and returns `null`. + * Opens a pre-auth window whose deadline answers one 401 that closes the connection. When every + * slot is held, it answers a retryable 503 that closes the connection, and returns `null`. */ function openPreauthWindow( acquire: RpcPreauthSlots, res: http.ServerResponse, ): RpcPreauthWindow | null { const closed = new AbortController(); - const preauth = acquire(closed.signal, () => res.destroy()); + const preauth = acquire(closed.signal, () => { + const error = new AppError('UNAUTHORIZED', 'Authentication did not finish in time'); + refuseAndClose(res, rpcRefusal(null, -32000, error.message, 401, normalizeError(error))); + }); if (!preauth) { - const error = new AppError('COMMAND_FAILED', 'Too many unauthenticated requests', { - reason: DAEMON_RPC_PREAUTH_REASONS.preauthBusy.reason, - dispatched: 'no', - retriable: true, - }); - res.setHeader('connection', 'close'); - sendRpcRefusal(res, rpcRefusal(null, -32000, error.message, 503, normalizeError(error))); + refuseAndClose(res, preauthBusyRefusal()); return null; } res.once('close', () => closed.abort()); return preauth; } -/** Accumulates one `/rpc` body and hands it to the flow once the stream ends. */ +/** Accumulates one `/rpc` body and hands it to the flow, unless `deadline` answered first. */ function readRpcRequestBody( req: http.IncomingMessage, res: http.ServerResponse, + deadline: AbortSignal | undefined, onBody: (body: string) => void, ): void { let body = ''; let bodyBytes = 0; + deadline?.addEventListener('abort', () => (body = ''), { once: true }); req.setEncoding('utf8'); req.on('data', (chunk: string) => { + if (deadline?.aborted) return; body += chunk; bodyBytes += Buffer.byteLength(chunk, 'utf8'); if (bodyBytes > MAX_HTTP_RPC_BODY_BYTES) { @@ -368,6 +396,7 @@ function readRpcRequestBody( req.on( 'end', AsyncResource.bind(() => { + if (deadline?.aborted) return; const text = body; // A queued response keeps this request alive, so the listener must not keep its body. body = ''; @@ -446,6 +475,7 @@ async function handleRpcRequest(params: { // pre-auth window that ran out, 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(); + if (preauth?.deadline.aborted) return; // The deadline answered this caller. sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); } finally { lifetime.release(); diff --git a/packages/proxy/src/daemon-proxy-preauth.test.ts b/packages/proxy/src/daemon-proxy-preauth.test.ts index 85de1d91181..eca212ffb47 100644 --- a/packages/proxy/src/daemon-proxy-preauth.test.ts +++ b/packages/proxy/src/daemon-proxy-preauth.test.ts @@ -110,6 +110,58 @@ test('over node:http a wrong header token is answered 401 and the connection is expect(received.toLowerCase()).toContain('connection: close'); }); +test('over node:http a header-token call pipelined behind a queued 503 is never forwarded', async () => { + const slowAnswer = Promise.withResolvers(); + let forwarded = 0; + const server = createDaemonProxyServer({ + ...UPSTREAM, + clientToken: 'client-secret', + upstreamFetch: async () => { + forwarded += 1; + await slowAnswer.promise; + return Response.json({ jsonrpc: '2.0', id: 1, result: {} }); + }, + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as net.AddressInfo; + const head = + 'POST /agent-device/rpc HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n'; + const call = '{"jsonrpc":"2.0","id":1,"method":"agent_device.command","params":{}}'; + const authed = `${head}Authorization: Bearer client-secret\r\nContent-Length: ${call.length}\r\n\r\n${call}`; + const holder = net.connect(port, '127.0.0.1'); + const socket = net.connect(port, '127.0.0.1'); + holder.on('error', () => {}); + socket.on('error', () => {}); + try { + holder.write(`${head}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`); + await new Promise((resolve) => setTimeout(resolve, 50)); + let received = ''; + socket.on('data', (chunk) => (received += chunk.toString('utf8'))); + const closed = new Promise((resolve) => socket.once('close', () => resolve())); + socket.write(`${authed}${head}Content-Length: 1\r\n\r\nx${authed}`); + setTimeout(() => slowAnswer.resolve(), 100); + await closed; + expect(received.match(/HTTP\/1\.1 \d+/g)).toEqual(['HTTP/1.1 200', 'HTTP/1.1 503']); + expect(forwarded).toBe(1); + } finally { + slowAnswer.resolve(); + holder.destroy(); + socket.destroy(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +test('an authenticate rejection on a first diagnostics request is answered, not leaked', async () => { + const proxy = createDaemonProxy({ + ...UPSTREAM, + authenticate: () => Promise.reject(new Error('identity service down')), + }); + const response = await proxy.handle( + new Request('https://gateway.example.test/agent-device/sessions/s/requests/r/diagnostics'), + ); + expect(response.status).toBe(500); +}); + test('over node:http a body that stalls past the pre-auth deadline is answered 401 and closed', async () => { const received = await stalledNodeExchange( createDaemonProxyServer({ ...UPSTREAM, clientToken: 'client-secret' }), diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 14d0ce3230f..ff825f0a21a 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -278,6 +278,8 @@ async function handleDaemonRoute( if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } + if (rpcBody !== undefined) + (await import('./rpc-ingress.ts')).laterRequestReleases.get(request)?.(); 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'); @@ -323,6 +325,8 @@ async function authenticateCaller( ? { uploadHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } : null; } + // Loaded before the hook runs, so its rejection gets a handler at once. + const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); const authentication = options.authenticate( forwardedRequest(request, request.url, { method: request.method, @@ -331,7 +335,6 @@ async function authenticateCaller( ...(rpcBody !== undefined ? { body: rpcBody } : {}), }), ); - const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); let result; try { result = await awaitWithSignal(Promise.resolve(authentication), preauth?.signal); diff --git a/packages/proxy/src/node-http.ts b/packages/proxy/src/node-http.ts index 8a57bc6f29e..7080cc818f7 100644 --- a/packages/proxy/src/node-http.ts +++ b/packages/proxy/src/node-http.ts @@ -1,42 +1,48 @@ import type { IncomingMessage, ServerResponse } from 'node:http'; +import type { Socket } from 'node:net'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { TLSSocket } from 'node:tls'; import { nodeHttpRequestUrl } from '@agent-device/contracts/daemon-http'; import type { DaemonProxy } from './daemon-proxy.ts'; +import { laterRequestReleases, preauthBusyResponse } from './rpc-ingress.ts'; + +/** Per socket, whether its latest request scheduled a close, known once it is admitted or answered. */ +const socketCloses = new WeakMap>(); export async function serveProxyRequest( proxy: DaemonProxy, req: IncomingMessage, res: ServerResponse, ): Promise { - // Fetch refuses TRACE. node:http rejects TRACK and routes CONNECT to the 'connect' event. - if (req.method === 'TRACE') { - endWithStatus(req, res, 404); - return; - } - const url = requestUrl(req); - if (!url) { - endWithStatus(req, res, 400); - return; - } - const response = await proxy.handle(toWebRequest(url, req, res)); - res.statusCode = response.status; - for (const [name, value] of response.headers) res.setHeader(name, value); - // An answer sent before the body was read, such as an early refusal, closes the connection - // instead of leaving Node to read and discard the rest of that body. - if (!req.complete) res.setHeader('connection', 'close'); - if (!response.body) { - res.end(); - return; + const closes = Promise.withResolvers(); + const earlier = socketCloses.get(req.socket); + socketCloses.set(req.socket, closes.promise); + try { + const url = requestUrl(req); + let response: Response; + // The close would drop its answer, so a request behind one never reaches the proxy. + if (earlier && (await earlier)) response = preauthBusyResponse(); + // Fetch refuses TRACE. node:http rejects TRACK and routes CONNECT to the 'connect' event. + else if (req.method === 'TRACE' || !url) + response = new Response(null, { status: req.method === 'TRACE' ? 404 : 400 }); + else { + const request = toWebRequest(url, req, res); + laterRequestReleases.set(request, () => closes.resolve(false)); + response = await proxy.handle(request); + } + // An answer sent before the body was read, such as an early refusal, closes the connection + // instead of leaving Node to read and discard the rest of that body. + const closing = !req.complete || response.headers.get('connection') === 'close'; + closes.resolve(closing); + res.statusCode = response.status; + for (const [name, value] of response.headers) res.setHeader(name, value); + if (closing) res.setHeader('connection', 'close'); + if (!response.body) return void res.end(); + await pipeline(Readable.fromWeb(response.body as Parameters[0]), res); + } finally { + closes.resolve(true); } - await pipeline(Readable.fromWeb(response.body as Parameters[0]), res); -} - -function endWithStatus(req: IncomingMessage, res: ServerResponse, status: number): void { - res.statusCode = status; - if (!req.complete) res.setHeader('connection', 'close'); - res.end(); } /** `null` when the Host header and path do not form a URL that Fetch accepts. */ diff --git a/packages/proxy/src/rpc-ingress.ts b/packages/proxy/src/rpc-ingress.ts index c960fdeb2bd..150a92323b9 100644 --- a/packages/proxy/src/rpc-ingress.ts +++ b/packages/proxy/src/rpc-ingress.ts @@ -19,6 +19,12 @@ export function preauthBusyResponse(): Response { ); } +/** + * Per Node adapter request: lets later requests on its socket run. Runs once the caller is + * admitted with its body read, since its answer can then no longer close the socket. + */ +export const laterRequestReleases = new WeakMap void>(); + /** * Reads a request body up to `maxBodyBytes`. When `signal` aborts it stops waiting but leaves the * stream alone: cancelling it would destroy a Node request before the refusal is written. Over the From e3c39e3ea011c1954743aab2f626a414d987e945 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 13:33:20 +0100 Subject: [PATCH 09/11] refactor(daemon): split the RPC route out of the request dispatcher --- .../daemon/src/server/http/http-server.ts | 69 ++++++++++--------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 46929d58208..847f2165ea6 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -175,6 +175,41 @@ export async function createDaemonHttpServer(options: { DAEMON_RPC_PREAUTH_SLOTS, DAEMON_RPC_PREAUTH_TIMEOUT_MS, ); + const serveRpcRoute = (req: http.IncomingMessage, res: http.ServerResponse): void => { + const checked = req.url === DAEMON_HTTP_CHECKED_RPC_ROUTE; + if (req.method !== 'POST' || (req.url !== '/rpc' && !checked)) { + res.statusCode = 404; + res.end('Not found'); + return; + } + + const preauth = headerProvesDaemonToken(req, authHook, token) + ? undefined + : openPreauthWindow(acquirePreauth, res); + if (preauth === null) return; + readRpcRequestBody(req, res, preauth?.deadline, (body) => { + // 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, + preauth, + }) + .catch((error: unknown) => { + sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); + }) + // A refusal answered behind an earlier response ends its window now, not at close. + .finally(() => preauth?.end()); + }); + }; const onRequest = AsyncResource.bind((req: http.IncomingMessage, res: http.ServerResponse) => { // Its answer would be dropped by the close, so a request on a closing socket never runs. if (closingSockets.has(req.socket)) { @@ -256,39 +291,7 @@ export async function createDaemonHttpServer(options: { return; } - const checked = req.url === DAEMON_HTTP_CHECKED_RPC_ROUTE; - if (req.method !== 'POST' || (req.url !== '/rpc' && !checked)) { - res.statusCode = 404; - res.end('Not found'); - return; - } - - const preauth = headerProvesDaemonToken(req, authHook, token) - ? undefined - : openPreauthWindow(acquirePreauth, res); - if (preauth === null) return; - readRpcRequestBody(req, res, preauth?.deadline, (body) => { - // 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, - preauth, - }) - .catch((error: unknown) => { - sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); - }) - // A refusal answered behind an earlier response ends its window now, not at close. - .finally(() => preauth?.end()); - }); + serveRpcRoute(req, res); }); // 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 From 1296183afe2029d53b2916729b9139bc51fe5bd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 13:55:48 +0100 Subject: [PATCH 10/11] revert(daemon,proxy): drop pipelining socket fences; keep the lazy-import order fix --- .../http-server-rpc-preauth-deadline.test.ts | 82 ------------ .../daemon/src/server/http/http-server.ts | 121 +++++++----------- .../proxy/src/daemon-proxy-preauth.test.ts | 52 -------- packages/proxy/src/daemon-proxy.ts | 5 +- packages/proxy/src/node-http.ts | 58 ++++----- packages/proxy/src/rpc-ingress.ts | 6 - 6 files changed, 71 insertions(+), 253 deletions(-) diff --git a/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts index 47ccd54168d..1ec2f4c356e 100644 --- a/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts +++ b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts @@ -54,8 +54,6 @@ test('an unauthenticated rpc caller that stalls its body is closed at the pre-au const socket = net.connect(port, '127.0.0.1'); socket.on('error', () => {}); try { - let received = ''; - socket.on('data', (chunk) => (received += chunk.toString('utf8'))); const closed = new Promise((resolve) => socket.once('close', () => resolve())); const startedAt = Date.now(); // No token header, so the token can only be in a body that never finishes. @@ -65,7 +63,6 @@ test('an unauthenticated rpc caller that stalls its body is closed at the pre-au ); await closed; assert.ok(Date.now() - startedAt < 2_000, 'the deadline, not a Node ceiling, closed it'); - assert.deepEqual(received.match(/HTTP\/1\.1 \d+/g), ['HTTP/1.1 401']); assert.equal(handlerCalls, 0); } finally { socket.destroy(); @@ -184,82 +181,3 @@ test('a refusal queued behind an earlier answer frees its pre-auth slot before t await closeLoopbackServer(server); } }); - -const CALL = JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'agent_device.command', - params: { command: 'devices' }, -}); -const AUTHED_CALL = `${RPC_HEAD}x-agent-device-token: daemon-secret\r\nContent-Length: ${CALL.length}\r\n\r\n${CALL}`; - -async function startSlowDaemon() { - const { createDaemonHttpServer } = await import('./http-server.ts'); - const slowAnswer = Promise.withResolvers(); - const handled = { calls: 0 }; - const server = await createDaemonHttpServer({ - token: 'daemon-secret', - handleRequest: async (): Promise => { - handled.calls += 1; - await slowAnswer.promise; - return { ok: true, data: {} }; - }, - env: process.env, - cwd: process.cwd(), - }); - return { server, port: await listenOnLoopback(server), slowAnswer, handled }; -} - -async function readUntilClosed(socket: net.Socket, write: string): Promise { - let received = ''; - socket.on('data', (chunk) => (received += chunk.toString('utf8'))); - const closed = new Promise((resolve) => socket.once('close', () => resolve())); - socket.write(write); - await closed; - return received; -} - -test('a pre-auth deadline behind a queued answer refuses once with 401 and closes after it', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - const { server, port, slowAnswer } = await startSlowDaemon(); - const socket = connect(port); - try { - const exchange = readUntilClosed( - socket, - `${AUTHED_CALL}${RPC_HEAD}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`, - ); - setTimeout(() => slowAnswer.resolve(), 400); - const received = await exchange; - assert.deepEqual(received.match(/HTTP\/1\.1 \d+/g), ['HTTP/1.1 200', 'HTTP/1.1 401']); - assert.match(received.slice(received.indexOf('HTTP/1.1 401')), /connection: close/i); - } finally { - slowAnswer.resolve(); - socket.destroy(); - await closeLoopbackServer(server); - } -}); - -test('a header-token call pipelined behind a queued 503 is declined before dispatch', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - const { server, port, slowAnswer, handled } = await startSlowDaemon(); - const holder = connect(port); - const socket = connect(port); - try { - const held = new Promise((resolve) => server.once('request', resolve)); - holder.write(`${RPC_HEAD}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`); - await held; - const exchange = readUntilClosed( - socket, - `${AUTHED_CALL}${RPC_HEAD}Content-Length: 1\r\n\r\nx${AUTHED_CALL}`, - ); - setTimeout(() => slowAnswer.resolve(), 100); - const received = await exchange; - assert.deepEqual(received.match(/HTTP\/1\.1 \d+/g), ['HTTP/1.1 200', 'HTTP/1.1 503']); - assert.equal(handled.calls, 1, 'the later header-token call never ran'); - } finally { - slowAnswer.resolve(); - holder.destroy(); - socket.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 847f2165ea6..9e0abe13902 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -10,7 +10,6 @@ import { responseDisconnectSignal } from './response-disconnect-signal.ts'; import type { DaemonResponse, DaemonResponseData } from '@agent-device/kernel/contracts'; import { AsyncResource } from 'node:async_hooks'; import http from 'node:http'; -import type { Socket } from 'node:net'; import { TLSSocket } from 'node:tls'; import { randomUUID } from 'node:crypto'; import type { DiagnosticsRecordRef, NormalizedError } from '@agent-device/kernel/errors'; @@ -175,47 +174,7 @@ export async function createDaemonHttpServer(options: { DAEMON_RPC_PREAUTH_SLOTS, DAEMON_RPC_PREAUTH_TIMEOUT_MS, ); - const serveRpcRoute = (req: http.IncomingMessage, res: http.ServerResponse): void => { - const checked = req.url === DAEMON_HTTP_CHECKED_RPC_ROUTE; - if (req.method !== 'POST' || (req.url !== '/rpc' && !checked)) { - res.statusCode = 404; - res.end('Not found'); - return; - } - - const preauth = headerProvesDaemonToken(req, authHook, token) - ? undefined - : openPreauthWindow(acquirePreauth, res); - if (preauth === null) return; - readRpcRequestBody(req, res, preauth?.deadline, (body) => { - // 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, - preauth, - }) - .catch((error: unknown) => { - sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); - }) - // A refusal answered behind an earlier response ends its window now, not at close. - .finally(() => preauth?.end()); - }); - }; const onRequest = AsyncResource.bind((req: http.IncomingMessage, res: http.ServerResponse) => { - // Its answer would be dropped by the close, so a request on a closing socket never runs. - if (closingSockets.has(req.socket)) { - refuseAndClose(res, preauthBusyRefusal()); - return; - } const ingressUrl = nodeHttpRequestUrl(req.url, req.rawHeaders, req.socket instanceof TLSSocket); if (!ingressUrl) { res.writeHead(400); @@ -291,7 +250,39 @@ export async function createDaemonHttpServer(options: { return; } - serveRpcRoute(req, res); + const checked = req.url === DAEMON_HTTP_CHECKED_RPC_ROUTE; + if (req.method !== 'POST' || (req.url !== '/rpc' && !checked)) { + res.statusCode = 404; + res.end('Not found'); + return; + } + + const preauth = headerProvesDaemonToken(req, authHook, token) + ? undefined + : openPreauthWindow(acquirePreauth, res); + if (preauth === null) return; + readRpcRequestBody(req, res, (body) => { + // 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, + preauth, + }) + .catch((error: unknown) => { + sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); + }) + // A refusal answered behind an earlier response ends its window now, not at close. + .finally(() => preauth?.end()); + }); }); // 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 @@ -326,62 +317,40 @@ function headerProvesDaemonToken( return !authHook && (!token || !enforceDaemonToken(resolveToken({}, req.headers), token)); } -/** Sockets whose close is scheduled behind a refusal. */ -const closingSockets = new WeakSet(); - /** - * Answers `refusal` and closes the socket once it flushes. Answers queued ahead of it still - * finish; every later request on the socket is declined before admission. - */ -function refuseAndClose(res: http.ServerResponse, refusal: RpcRefusal): void { - closingSockets.add(res.req.socket); - res.setHeader('connection', 'close'); - sendRpcRefusal(res, refusal); -} - -function preauthBusyRefusal(): RpcRefusal { - const error = new AppError('COMMAND_FAILED', 'Too many unauthenticated requests', { - reason: DAEMON_RPC_PREAUTH_REASONS.preauthBusy.reason, - dispatched: 'no', - retriable: true, - }); - return rpcRefusal(null, -32000, error.message, 503, normalizeError(error)); -} - -/** - * Opens a pre-auth window whose deadline answers one 401 that closes the connection. When every - * slot is held, it answers a retryable 503 that closes the connection, and returns `null`. + * Opens a pre-auth window whose deadline destroys the connection. When every slot is held, it + * answers a retryable 503 that closes the connection before the body is read, and returns `null`. */ function openPreauthWindow( acquire: RpcPreauthSlots, res: http.ServerResponse, ): RpcPreauthWindow | null { const closed = new AbortController(); - const preauth = acquire(closed.signal, () => { - const error = new AppError('UNAUTHORIZED', 'Authentication did not finish in time'); - refuseAndClose(res, rpcRefusal(null, -32000, error.message, 401, normalizeError(error))); - }); + const preauth = acquire(closed.signal, () => res.destroy()); if (!preauth) { - refuseAndClose(res, preauthBusyRefusal()); + const error = new AppError('COMMAND_FAILED', 'Too many unauthenticated requests', { + reason: DAEMON_RPC_PREAUTH_REASONS.preauthBusy.reason, + dispatched: 'no', + retriable: true, + }); + res.setHeader('connection', 'close'); + sendRpcRefusal(res, rpcRefusal(null, -32000, error.message, 503, normalizeError(error))); return null; } res.once('close', () => closed.abort()); return preauth; } -/** Accumulates one `/rpc` body and hands it to the flow, unless `deadline` answered first. */ +/** Accumulates one `/rpc` body and hands it to the flow once the stream ends. */ function readRpcRequestBody( req: http.IncomingMessage, res: http.ServerResponse, - deadline: AbortSignal | undefined, onBody: (body: string) => void, ): void { let body = ''; let bodyBytes = 0; - deadline?.addEventListener('abort', () => (body = ''), { once: true }); req.setEncoding('utf8'); req.on('data', (chunk: string) => { - if (deadline?.aborted) return; body += chunk; bodyBytes += Buffer.byteLength(chunk, 'utf8'); if (bodyBytes > MAX_HTTP_RPC_BODY_BYTES) { @@ -399,7 +368,6 @@ function readRpcRequestBody( req.on( 'end', AsyncResource.bind(() => { - if (deadline?.aborted) return; const text = body; // A queued response keeps this request alive, so the listener must not keep its body. body = ''; @@ -478,7 +446,6 @@ async function handleRpcRequest(params: { // pre-auth window that ran out, 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(); - if (preauth?.deadline.aborted) return; // The deadline answered this caller. sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); } finally { lifetime.release(); diff --git a/packages/proxy/src/daemon-proxy-preauth.test.ts b/packages/proxy/src/daemon-proxy-preauth.test.ts index eca212ffb47..85de1d91181 100644 --- a/packages/proxy/src/daemon-proxy-preauth.test.ts +++ b/packages/proxy/src/daemon-proxy-preauth.test.ts @@ -110,58 +110,6 @@ test('over node:http a wrong header token is answered 401 and the connection is expect(received.toLowerCase()).toContain('connection: close'); }); -test('over node:http a header-token call pipelined behind a queued 503 is never forwarded', async () => { - const slowAnswer = Promise.withResolvers(); - let forwarded = 0; - const server = createDaemonProxyServer({ - ...UPSTREAM, - clientToken: 'client-secret', - upstreamFetch: async () => { - forwarded += 1; - await slowAnswer.promise; - return Response.json({ jsonrpc: '2.0', id: 1, result: {} }); - }, - }); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); - const { port } = server.address() as net.AddressInfo; - const head = - 'POST /agent-device/rpc HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n'; - const call = '{"jsonrpc":"2.0","id":1,"method":"agent_device.command","params":{}}'; - const authed = `${head}Authorization: Bearer client-secret\r\nContent-Length: ${call.length}\r\n\r\n${call}`; - const holder = net.connect(port, '127.0.0.1'); - const socket = net.connect(port, '127.0.0.1'); - holder.on('error', () => {}); - socket.on('error', () => {}); - try { - holder.write(`${head}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`); - await new Promise((resolve) => setTimeout(resolve, 50)); - let received = ''; - socket.on('data', (chunk) => (received += chunk.toString('utf8'))); - const closed = new Promise((resolve) => socket.once('close', () => resolve())); - socket.write(`${authed}${head}Content-Length: 1\r\n\r\nx${authed}`); - setTimeout(() => slowAnswer.resolve(), 100); - await closed; - expect(received.match(/HTTP\/1\.1 \d+/g)).toEqual(['HTTP/1.1 200', 'HTTP/1.1 503']); - expect(forwarded).toBe(1); - } finally { - slowAnswer.resolve(); - holder.destroy(); - socket.destroy(); - await new Promise((resolve) => server.close(() => resolve())); - } -}); - -test('an authenticate rejection on a first diagnostics request is answered, not leaked', async () => { - const proxy = createDaemonProxy({ - ...UPSTREAM, - authenticate: () => Promise.reject(new Error('identity service down')), - }); - const response = await proxy.handle( - new Request('https://gateway.example.test/agent-device/sessions/s/requests/r/diagnostics'), - ); - expect(response.status).toBe(500); -}); - test('over node:http a body that stalls past the pre-auth deadline is answered 401 and closed', async () => { const received = await stalledNodeExchange( createDaemonProxyServer({ ...UPSTREAM, clientToken: 'client-secret' }), diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index ff825f0a21a..14d0ce3230f 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -278,8 +278,6 @@ async function handleDaemonRoute( if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } - if (rpcBody !== undefined) - (await import('./rpc-ingress.ts')).laterRequestReleases.get(request)?.(); 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'); @@ -325,8 +323,6 @@ async function authenticateCaller( ? { uploadHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } : null; } - // Loaded before the hook runs, so its rejection gets a handler at once. - const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); const authentication = options.authenticate( forwardedRequest(request, request.url, { method: request.method, @@ -335,6 +331,7 @@ async function authenticateCaller( ...(rpcBody !== undefined ? { body: rpcBody } : {}), }), ); + const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); let result; try { result = await awaitWithSignal(Promise.resolve(authentication), preauth?.signal); diff --git a/packages/proxy/src/node-http.ts b/packages/proxy/src/node-http.ts index 7080cc818f7..8a57bc6f29e 100644 --- a/packages/proxy/src/node-http.ts +++ b/packages/proxy/src/node-http.ts @@ -1,48 +1,42 @@ import type { IncomingMessage, ServerResponse } from 'node:http'; -import type { Socket } from 'node:net'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { TLSSocket } from 'node:tls'; import { nodeHttpRequestUrl } from '@agent-device/contracts/daemon-http'; import type { DaemonProxy } from './daemon-proxy.ts'; -import { laterRequestReleases, preauthBusyResponse } from './rpc-ingress.ts'; - -/** Per socket, whether its latest request scheduled a close, known once it is admitted or answered. */ -const socketCloses = new WeakMap>(); export async function serveProxyRequest( proxy: DaemonProxy, req: IncomingMessage, res: ServerResponse, ): Promise { - const closes = Promise.withResolvers(); - const earlier = socketCloses.get(req.socket); - socketCloses.set(req.socket, closes.promise); - try { - const url = requestUrl(req); - let response: Response; - // The close would drop its answer, so a request behind one never reaches the proxy. - if (earlier && (await earlier)) response = preauthBusyResponse(); - // Fetch refuses TRACE. node:http rejects TRACK and routes CONNECT to the 'connect' event. - else if (req.method === 'TRACE' || !url) - response = new Response(null, { status: req.method === 'TRACE' ? 404 : 400 }); - else { - const request = toWebRequest(url, req, res); - laterRequestReleases.set(request, () => closes.resolve(false)); - response = await proxy.handle(request); - } - // An answer sent before the body was read, such as an early refusal, closes the connection - // instead of leaving Node to read and discard the rest of that body. - const closing = !req.complete || response.headers.get('connection') === 'close'; - closes.resolve(closing); - res.statusCode = response.status; - for (const [name, value] of response.headers) res.setHeader(name, value); - if (closing) res.setHeader('connection', 'close'); - if (!response.body) return void res.end(); - await pipeline(Readable.fromWeb(response.body as Parameters[0]), res); - } finally { - closes.resolve(true); + // Fetch refuses TRACE. node:http rejects TRACK and routes CONNECT to the 'connect' event. + if (req.method === 'TRACE') { + endWithStatus(req, res, 404); + return; + } + const url = requestUrl(req); + if (!url) { + endWithStatus(req, res, 400); + return; + } + const response = await proxy.handle(toWebRequest(url, req, res)); + res.statusCode = response.status; + for (const [name, value] of response.headers) res.setHeader(name, value); + // An answer sent before the body was read, such as an early refusal, closes the connection + // instead of leaving Node to read and discard the rest of that body. + if (!req.complete) res.setHeader('connection', 'close'); + if (!response.body) { + res.end(); + return; } + await pipeline(Readable.fromWeb(response.body as Parameters[0]), res); +} + +function endWithStatus(req: IncomingMessage, res: ServerResponse, status: number): void { + res.statusCode = status; + if (!req.complete) res.setHeader('connection', 'close'); + res.end(); } /** `null` when the Host header and path do not form a URL that Fetch accepts. */ diff --git a/packages/proxy/src/rpc-ingress.ts b/packages/proxy/src/rpc-ingress.ts index 150a92323b9..c960fdeb2bd 100644 --- a/packages/proxy/src/rpc-ingress.ts +++ b/packages/proxy/src/rpc-ingress.ts @@ -19,12 +19,6 @@ export function preauthBusyResponse(): Response { ); } -/** - * Per Node adapter request: lets later requests on its socket run. Runs once the caller is - * admitted with its body read, since its answer can then no longer close the socket. - */ -export const laterRequestReleases = new WeakMap void>(); - /** * Reads a request body up to `maxBodyBytes`. When `signal` aborts it stops waiting but leaves the * stream alone: cancelling it would destroy a Node request before the refusal is written. Over the From 165b8c5cea520738b5dc756a85f102046fbf07ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 14:17:58 +0100 Subject: [PATCH 11/11] fix(proxy): load awaitWithSignal before calling authenticate --- packages/proxy/src/daemon-proxy-preauth.test.ts | 11 +++++++++++ packages/proxy/src/daemon-proxy.ts | 3 ++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/proxy/src/daemon-proxy-preauth.test.ts b/packages/proxy/src/daemon-proxy-preauth.test.ts index 85de1d91181..43801652fa0 100644 --- a/packages/proxy/src/daemon-proxy-preauth.test.ts +++ b/packages/proxy/src/daemon-proxy-preauth.test.ts @@ -118,3 +118,14 @@ test('over node:http a body that stalls past the pre-auth deadline is answered 4 expect(received).toMatch(/^HTTP\/1\.1 401 /); expect(received.toLowerCase()).toContain('connection: close'); }); + +test('an authenticate rejection on a first diagnostics request is answered, not leaked', async () => { + const proxy = createDaemonProxy({ + ...UPSTREAM, + authenticate: () => Promise.reject(new Error('identity service down')), + }); + const response = await proxy.handle( + new Request('https://gateway.example.test/agent-device/sessions/s/requests/r/diagnostics'), + ); + expect(response.status).toBe(500); +}); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 14d0ce3230f..4576a7ccbd5 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -323,6 +323,8 @@ async function authenticateCaller( ? { uploadHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } : null; } + // Loaded before the call: an await between the call and awaitWithSignal would leave a rejection unhandled. + const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); const authentication = options.authenticate( forwardedRequest(request, request.url, { method: request.method, @@ -331,7 +333,6 @@ async function authenticateCaller( ...(rpcBody !== undefined ? { body: rpcBody } : {}), }), ); - const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); let result; try { result = await awaitWithSignal(Promise.resolve(authentication), preauth?.signal);