diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index a1eb9a90ac9..7981c1002f8 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -134,6 +134,20 @@ 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; +/** How many unauthenticated `/rpc` callers one daemon or one proxy holds at once. */ +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 = { + // 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/__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..1ec2f4c356e --- /dev/null +++ b/packages/daemon/src/server/http/http-server-rpc-preauth-deadline.test.ts @@ -0,0 +1,183 @@ +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'; + +// 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, + 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'); + 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 < 2_000, 'the deadline, not a Node ceiling, closed it'); + assert.equal(handlerCalls, 0); + } finally { + socket.destroy(); + 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'); + } +}); + +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 daae7f1eef0..9e0abe13902 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'; @@ -40,9 +40,17 @@ import { DAEMON_HTTP_NETWORK_ACCESS_HEADER, 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'; +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'; @@ -162,6 +170,10 @@ export async function createDaemonHttpServer(options: { resolveRequestDiagnosticsPath, onUnownedRequestFailure, } = options; + 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) { @@ -245,6 +257,10 @@ export async function createDaemonHttpServer(options: { 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 @@ -259,9 +275,13 @@ export async function createDaemonHttpServer(options: { instanceId, handleRequest, checked, - }).catch((error: unknown) => { - sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); - }); + 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 @@ -285,6 +305,42 @@ export async function createDaemonHttpServer(options: { return server; } +/** + * 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, + authHook: HttpAuthHook | null, + token: string | undefined, +): boolean { + return !authHook && (!token || !enforceDaemonToken(resolveToken({}, req.headers), token)); +} + +/** + * 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, () => res.destroy()); + 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()); + return preauth; +} + /** Accumulates one `/rpc` body and hands it to the flow once the stream ends. */ function readRpcRequestBody( req: http.IncomingMessage, @@ -303,6 +359,7 @@ function readRpcRequestBody( }); req.on('error', () => { + body = ''; if (!res.headersSent) { sendRpcRefusal(res, rpcParseErrorRefusal()); } @@ -311,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); }), ); } @@ -332,8 +392,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. */ + preauth: RpcPreauthWindow | undefined; }): Promise { const { req, res, body, authHook, expectedToken, instanceId, handleRequest, checked } = 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; @@ -361,7 +424,8 @@ async function handleRpcRequest(params: { params: validated.params, lifetime, protocolRefusal, - }); + preauth, + }).finally(() => preauth?.end()); if (admission.outcome !== 'admitted') { if (admission.outcome === 'rejected') { sendRpcRefusal(res, admission.refusal); @@ -378,9 +442,9 @@ 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 - // 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 { @@ -496,8 +560,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 +654,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,9 +671,11 @@ async function admitRpcRequest(params: { lifetime: RpcRequestLifetime; /** 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: 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)) { @@ -623,10 +689,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 +699,7 @@ async function admitRpcRequest(params: { headers: req.headers, rpcRequest, daemonRequest, + signal: preauth?.signal, }); if (!authResult.ok) { return { @@ -663,9 +727,11 @@ 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: stampAdmittedIdentity(daemonRequest, tenantTrust, authHook, req), + daemonRequest: lifetime.admit(stampAdmittedIdentity(daemonRequest, tenantTrust, authHook, req)), }; } 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 99ba9455d2b..1e392fd0cca 100644 --- a/packages/host-kit/src/internal/transport.ts +++ b/packages/host-kit/src/internal/transport.ts @@ -297,3 +297,45 @@ 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; + /** Ends the window. The slot retires exactly once, here or when `signal` aborts. */ + 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; + const deadline = new AbortController(); + const timer = setTimeout(() => { + deadline.abort(); + onDeadline?.(); + }, timeoutMs); + const signal = AbortSignal.any([callerGone, deadline.signal]); + let ended = false; + 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/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-preauth.test.ts b/packages/proxy/src/daemon-proxy-preauth.test.ts new file mode 100644 index 00000000000..43801652fa0 --- /dev/null +++ b/packages/proxy/src/daemon-proxy-preauth.test.ts @@ -0,0 +1,131 @@ +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, createDaemonProxyServer } = 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: {} }), + }); + 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 () => { + 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', dispatched: 'no' }, + }); + 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"', + ); + let fallback: NodeJS.Timeout | undefined; + const closed = await new Promise((resolve) => { + socket.once('close', () => resolve(true)); + fallback = setTimeout(() => resolve(false), 2_000); + }).finally(() => clearTimeout(fallback)); + 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'); +}); + +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 6ab4e8788d5..4576a7ccbd5 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, @@ -19,6 +24,8 @@ import { normalizeTenantId, 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, @@ -159,11 +166,15 @@ 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, + DAEMON_RPC_PREAUTH_TIMEOUT_MS, + ); 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); } @@ -194,6 +205,7 @@ async function handleProxyRequest( request: Request, options: NormalizedProxyOptions, instanceId: string, + acquirePreauth: RpcPreauthSlots, ): Promise { const route = resolveProxyRoute(request.url); if (request.method === 'GET' && route === '/health') { @@ -206,14 +218,39 @@ 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 preauth = headerAuthenticated ? undefined : acquirePreauth(request.signal); + if (preauth === null) return (await import('./rpc-ingress.ts')).preauthBusyResponse(); + return await handleRpcRoute(request, route, options, instanceId, preauth).finally(() => + preauth?.end(), + ); +} + +async function handleRpcRoute( + request: Request, + route: string, + options: NormalizedProxyOptions, + instanceId: string, + 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, ); } catch (error) { + 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 @@ -222,7 +259,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, preauth); } catch (error) { return rpcErrorResponse(readJsonRpcId(rpcBody), error); } @@ -234,14 +271,17 @@ async function handleDaemonRoute( options: NormalizedProxyOptions, instanceId: string, rpcBody?: string, + preauth?: RpcPreauthWindow, ): Promise { - const caller = await authenticateCaller(request, options, rpcBody); + 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 ?? ''); @@ -276,20 +316,30 @@ async function authenticateCaller( request: Request, options: NormalizedProxyOptions, rpcBody: string | undefined, + preauth: RpcPreauthWindow | undefined, ): Promise { if (!options.authenticate) { return isAuthorized(request, options.clientToken ?? '', rpcBody) ? { uploadHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } : null; } - const result = await options.authenticate( + // 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, headers: request.headers, - signal: request.signal, + signal: preauth?.signal ?? request.signal, ...(rpcBody !== undefined ? { body: rpcBody } : {}), }), ); + let result; + try { + result = await awaitWithSignal(Promise.resolve(authentication), preauth?.signal); + } catch (error) { + if (preauth?.deadline.aborted) return null; + throw error; + } if (!result) return null; const tenantId = normalizeTenantId( typeof result.tenantId === 'string' ? result.tenantId : undefined, @@ -757,28 +807,6 @@ function resolveUpstreamBody( return request.body; } -async function readRequestText( - request: Request, - maxBodyBytes: number, - tooLargeMessage: string, -): Promise { - if (!request.body) return ''; - const reader = request.body.getReader(); - const chunks: Uint8Array[] = []; - let bodyBytes = 0; - for (;;) { - const { done, value } = await reader.read(); - if (done) break; - bodyBytes += value.byteLength; - if (bodyBytes > maxBodyBytes) { - await reader.cancel(); - throw new AppError('INVALID_ARGS', tooLargeMessage); - } - chunks.push(value); - } - return Buffer.concat(chunks).toString('utf8'); -} - function isAuthorized(request: Request, expectedToken: string, rpcBody: string | undefined) { const requestToken = resolveRequestToken(request, rpcBody); return requestToken.length > 0 && timingSafeStringEqual(requestToken, expectedToken); @@ -925,36 +953,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..8a57bc6f29e 100644 --- a/packages/proxy/src/node-http.ts +++ b/packages/proxy/src/node-http.ts @@ -12,17 +12,20 @@ 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)); 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; @@ -30,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 new file mode 100644 index 00000000000..c960fdeb2bd --- /dev/null +++ b/packages/proxy/src/rpc-ingress.ts @@ -0,0 +1,78 @@ +import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { DAEMON_RPC_PREAUTH_REASONS } from '@agent-device/contracts/daemon-http'; +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( + { + jsonrpc: '2.0', + id: null, + error: { code: -32000, message: error.message, data: normalizeError(error) }, + }, + { status: 503, headers: { connection: 'close' } }, + ); +} + +/** + * 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, + 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) { + reader.cancel().catch(() => {}); + 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 e7d35f20840..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,6 +1,37 @@ 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.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..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,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.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..ab88d6d954f 100644 --- a/packages/replay-port/src/daemon-port/script-source.ts +++ b/packages/replay-port/src/daemon-port/script-source.ts @@ -1,6 +1,8 @@ import { AppError } from '@agent-device/kernel/errors'; import type { ReplayScriptSourceBundle } from '@agent-device/contracts/replay'; +export const REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES = 2 * 1024 * 1024; + 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.'; @@ -8,7 +10,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', @@ -18,3 +20,42 @@ 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]) { + 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(files)) { + if (typeof script !== 'string') throw invalidScriptSourceBundle(); + totalBytes += Buffer.byteLength(script, 'utf8'); + } + assertBundleWithinLimit(totalBytes, 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 2c1152d6821..f7a4b4bb77d 100644 --- a/packages/replay-port/src/script-source-bundle.ts +++ b/packages/replay-port/src/script-source-bundle.ts @@ -5,8 +5,6 @@ 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; - export type ReplayScriptSourceRequest = { inputPath: string; cwd: string; @@ -23,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 @@ -42,15 +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 { - assertBundleWithinLimit(files, inputPath); +): Promise { + const totalBytes = Object.values(files).reduce( + (total, script) => total + Buffer.byteLength(script, 'utf8'), + 0, + ); + // 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 }; } @@ -77,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 bea0453832d..904da62b741 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 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.