diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 9d150b47ac..a05f7db046 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -146,6 +146,10 @@ export const DAEMON_RPC_PROTOCOL_VERSION = 4; * worst-case escaping. It also bounds the memory one unauthenticated connection can hold. */ export const DAEMON_REQUEST_MAX_BYTES = 64 * 1024 * 1024; +/** Time for receiving and authenticating an RPC before command execution begins. */ +export const DAEMON_RPC_PREAUTH_TIMEOUT_MS = 5_000; +/** Maximum string ID length echoed in an RPC preauthorization timeout. */ +export const DAEMON_RPC_PREAUTH_MAX_ID_LENGTH = 128; export const DAEMON_HTTP_INSTANCE_HEADER = 'x-agent-device-instance'; export const DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER = 'x-agent-device-upstream-instance'; diff --git a/packages/daemon/src/server/__tests__/http-server-rpc.fixtures.ts b/packages/daemon/src/server/__tests__/http-server-rpc.fixtures.ts index 2df9432efb..8da5222763 100644 --- a/packages/daemon/src/server/__tests__/http-server-rpc.fixtures.ts +++ b/packages/daemon/src/server/__tests__/http-server-rpc.fixtures.ts @@ -9,7 +9,10 @@ const RPC_ANSWER_DEADLINE_MS = 1_000; export type RpcErrorBody = { id?: unknown; - error?: { code?: number; data?: { details?: { reason?: string } } }; + error?: { + code?: number; + data?: { retriable?: boolean; details?: { reason?: string; dispatched?: string } }; + }; }; /** One `agent_device.command` call over `/rpc`, as the daemon answered it. */ diff --git a/packages/daemon/src/server/http/http-authorization-script-admission.test.ts b/packages/daemon/src/server/http/http-authorization-script-admission.test.ts index 071a5a8483..8ab763785b 100644 --- a/packages/daemon/src/server/http/http-authorization-script-admission.test.ts +++ b/packages/daemon/src/server/http/http-authorization-script-admission.test.ts @@ -60,3 +60,19 @@ test.each([ }), ); }); + +test('a client-declared tenant does not make a local request remote', () => { + const request: DaemonRequest = { + token: 'test', + session: 'owned', + command: 'open', + positionals: [], + flags: { saveScript: '/host/a.ad' }, + meta: { tenantId: 'tenant-a', scriptPublicationId: PUBLICATION_ID }, + }; + const result = restrictRemoteHttpRequest(request, false, undefined); + + expect(result.meta?.tenantId).toBe('tenant-a'); + expect(result.flags?.saveScript).toBe('/host/a.ad'); + expect(result.internal?.publicNetworkOnly).toBeUndefined(); +}); diff --git a/packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts b/packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts index 60299ead9d..86d0cec110 100644 --- a/packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts +++ b/packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts @@ -1,10 +1,176 @@ import http from 'node:http'; import assert from 'node:assert/strict'; -import { test } from 'vitest'; -import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; -import { postRpcCommand, startRpcServer } from '../__tests__/http-server-rpc.fixtures.ts'; +import fs from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { test, vi } from 'vitest'; +import { createDaemonProxyServer } from '@agent-device/proxy'; +import { + closeLoopbackServer, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { createDaemonHttpServer } from './http-server.ts'; +import { + postRpcCommand, + startRpcServer, + type RpcErrorBody, +} from '../__tests__/http-server-rpc.fixtures.ts'; -test('unfinished RPC bodies exhaust a bounded ingress budget without dispatch', async (t) => { +test('preauthorization body deadline answers with a typed reason before dispatch', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let dispatched = 0; + const { port, server } = await startRpcServer('budget-token', async () => { + dispatched += 1; + return { ok: true, data: {} }; + }); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const reached = new Promise((resolve) => server.once('request', () => resolve())); + let request!: http.ClientRequest; + const response = new Promise<{ status: number; body: string }>((resolve, reject) => { + request = http.request({ + host: '127.0.0.1', + port, + method: 'POST', + path: '/rpc', + headers: { 'content-type': 'application/json' }, + }); + request.on('response', (res) => { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => + resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') }), + ); + }); + request.on('error', reject); + request.flushHeaders(); + }); + try { + await reached; + await vi.advanceTimersByTimeAsync(5_000); + const answered = await response; + const body = JSON.parse(answered.body) as { + error?: { data?: { details?: { reason?: string; dispatched?: string } } }; + }; + assert.equal(answered.status, 408); + assert.equal(body.error?.data?.details?.reason, 'RPC_PREAUTH_DEADLINE_EXCEEDED'); + assert.equal(body.error?.data?.details?.dispatched, 'no'); + assert.equal(dispatched, 0); + } finally { + vi.useRealTimers(); + request.destroy(); + await closeLoopbackServer(server); + } +}); + +test.for([ + ['proxy', 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', 0], + ['daemon', 'RPC_PREAUTH_DEADLINE_EXCEEDED', 1], +] as const)( + 'the %s auth deadline answers through the proxy and allows a fresh call', + async ([origin, reason, expectedDaemonCalls], t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const root = mkdtempForTestSync('rpc-preauth-id-'); + const hookPath = path.join(root, 'auth-hook.mjs'); + fs.writeFileSync( + hookPath, + `const entered = Promise.withResolvers(); +const held = Promise.withResolvers(); +export const authEntered = entered.promise; +export const releaseAuth = () => held.resolve({ tenantId: 'budget-tenant' }); +export function holdAuth() { + entered.resolve(); + return held.promise; +} +export default function authHook({ rpcRequest }) { + return rpcRequest.id === 'daemon-timeout' ? holdAuth() : { tenantId: 'budget-tenant' }; +} +`, + ); + const auth = (await import(pathToFileURL(hookPath).href)) as { + authEntered: Promise; + holdAuth: () => Promise<{ tenantId: string }>; + releaseAuth: () => void; + }; + let daemonCalls = 0; + let dispatched = 0; + const daemon = await createDaemonHttpServer({ + token: 'budget-token', + env: { AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath }, + cwd: process.cwd(), + handleRequest: async () => { + dispatched += 1; + return { ok: true, data: { reached: 'daemon-handler' } }; + }, + }); + t.onTestFinished(() => closeLoopbackServer(daemon)); + daemon.on('request', () => { + daemonCalls += 1; + }); + const daemonPort = await listenOnLoopback(daemon); + const proxy = createDaemonProxyServer({ + upstreamBaseUrl: `http://127.0.0.1:${daemonPort}`, + upstreamToken: 'budget-token', + authenticate: (request) => + request.headers.get('x-request-id') === 'proxy-timeout' + ? auth.holdAuth() + : { tenantId: 'budget-tenant' }, + }); + t.onTestFinished(() => closeLoopbackServer(proxy)); + const proxyPort = await listenOnLoopback(proxy); + const post = (id: string) => + fetch(`http://127.0.0.1:${proxyPort}/agent-device/rpc`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-request-id': id }, + body: JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'agent_device.command', + params: { command: 'session_list' }, + }), + signal: AbortSignal.timeout(2_000), + }); + + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + t.onTestFinished(() => { + vi.useRealTimers(); + auth.releaseAuth(); + }); + const id = `${origin}-timeout`; + const pending = post(id); + await Promise.race([ + auth.authEntered, + pending.then((response) => + assert.fail(`HTTP ${response.status} before entering ${origin} auth`), + ), + ]); + await vi.advanceTimersByTimeAsync(5_000); + const response = await pending; + assert.equal(response.status, 408); + const body = (await response.json()) as RpcErrorBody; + assert.equal(body.id, id); + assert.equal(body.error?.data?.details?.reason, reason); + assert.equal(body.error?.data?.details?.dispatched, 'no'); + assert.equal(body.error?.data?.retriable, true); + assert.equal(daemonCalls, expectedDaemonCalls); + assert.equal(dispatched, 0); + + vi.useRealTimers(); + auth.releaseAuth(); + const fresh = await post(`${origin}-fresh`); + assert.equal(fresh.status, 200); + assert.deepEqual(await fresh.json(), { + jsonrpc: '2.0', + id: `${origin}-fresh`, + result: { ok: true, data: { reached: 'daemon-handler' } }, + }); + assert.equal(daemonCalls, expectedDaemonCalls + 1); + assert.equal(dispatched, 1); + }, +); + +test('unfinished unauthenticated RPC bodies do not block authenticated dispatch', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; let dispatched = 0; const { port, server } = await startRpcServer('budget-token', async () => { @@ -34,10 +200,12 @@ test('unfinished RPC bodies exhaust a bounded ingress budget without dispatch', held.push(request); } await ready; - const refused = await postRpcCommand(port, 'budget-token', 'overflow'); - assert.equal(refused.status, 503); - assert.equal(refused.body.error?.data?.details?.reason, 'RPC_BODY_CAPACITY_EXCEEDED'); - assert.equal(dispatched, 0); + const admitted = await postRpcCommand(port, 'budget-token', 'admitted'); + assert.equal(admitted.status, 200); + assert.equal(dispatched, 1); + for (const request of held) request.destroy(); + const afterDisconnect = await postRpcCommand(port, 'budget-token', 'after-disconnect'); + assert.equal(afterDisconnect.status, 200); } finally { for (const request of held) request.destroy(); await closeLoopbackServer(server); diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 82cc6551f6..cdf5c3bd8f 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -41,6 +41,8 @@ import { DAEMON_HTTP_NETWORK_ACCESS_HEADER, type CheckedRpcProtocolRefusal, DAEMON_REQUEST_MAX_BYTES, + DAEMON_RPC_PREAUTH_MAX_ID_LENGTH, + DAEMON_RPC_PREAUTH_TIMEOUT_MS, } from '@agent-device/contracts/daemon-http'; import { readVersion } from '@agent-device/host-kit/version'; import { readHostCpuArch } from '@agent-device/host-kit/process'; @@ -96,14 +98,15 @@ import { } from './http-checked-rpc.ts'; const MAX_HTTP_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; -const MAX_IN_FLIGHT_RPC_BODIES = 32; const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; -const RPC_INGRESS_REASONS = { - // Too many daemon RPC requests are in flight through dispatch. The daemon closes a request - // that exceeds its aggregate body-byte limit. - capacityExceeded: { reason: 'RPC_BODY_CAPACITY_EXCEEDED' }, +const MAX_RPC_PREAUTH_REQUESTS = 128; +const DAEMON_RPC_INGRESS_REASONS = { + // The daemon has no free slot to receive and authenticate another RPC request. + preauthCapacityExceeded: { reason: 'RPC_PREAUTH_CAPACITY_EXCEEDED' }, + // The RPC body or authentication did not finish before its preauthorization deadline, so nothing was dispatched. + preauthDeadlineExceeded: { reason: 'RPC_PREAUTH_DEADLINE_EXCEEDED' }, } as const satisfies ReasonTable<'RPC ingress'>; -type RpcBodyBudget = { active: number; bytes: number }; +type RpcIngressBudget = { bytes: number; preauthRequests: number }; /** What this daemon serves over HTTP beyond the base RPC contract, as `/health` advertises it. */ const DAEMON_HTTP_CAPABILITIES = [ 'script-artifacts', @@ -157,7 +160,7 @@ export async function createDaemonHttpServer(options: { resolveRequestDiagnosticsPath, onUnownedRequestFailure, } = options; - const rpcBodyBudget: RpcBodyBudget = { active: 0, bytes: 0 }; + const rpcIngressBudget: RpcIngressBudget = { bytes: 0, preauthRequests: 0 }; const onRequest = AsyncResource.bind((req: http.IncomingMessage, res: http.ServerResponse) => { const ingressUrl = nodeHttpRequestUrl(req.url, req.rawHeaders, req.socket instanceof TLSSocket); if (!ingressUrl) { @@ -264,26 +267,33 @@ export async function createDaemonHttpServer(options: { return; } - readRpcRequestBody(req, res, rpcBodyBudget, (body, release) => { - // The flow owns this request's lifetime, so this call site must neither hold lifetime state - // nor re-run it; the `catch` reports the failure to the daemon-level sink and answers. That - // answer is load-bearing: the daemon exits on an `unhandledRejection`, so a rejection dropped - // 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, - }) - .catch((error: unknown) => { - sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); + readRpcRequestBody( + req, + res, + rpcIngressBudget, + (body, release, preauthSignal, finishPreauth) => { + // The flow owns this request's lifetime, so this call site must neither hold lifetime state + // nor re-run it; the `catch` reports the failure to the daemon-level sink and answers. That + // answer is load-bearing: the daemon exits on an `unhandledRejection`, so a rejection dropped + // here would let any process that reaches the port stop the daemon with one request body. + void handleRpcRequest({ + req, + res, + body, + authHook, + expectedToken: token, + instanceId, + handleRequest, + checked, + preauthSignal, + finishPreauth, }) - .finally(release); - }); + .catch((error: unknown) => { + sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); + }) + .finally(release); + }, + ); }); // Socket ingress ceilings from one owner (ingress-budget.ts). They bound socket ingress // only; RPC execution keeps its own deadlines. The header ceiling acts before admission @@ -310,37 +320,63 @@ export async function createDaemonHttpServer(options: { function readRpcRequestBody( req: http.IncomingMessage, res: http.ServerResponse, - budget: RpcBodyBudget, - onBody: (body: string, release: () => void) => void, + budget: RpcIngressBudget, + onBody: ( + body: string, + release: () => void, + preauthSignal: AbortSignal, + finishPreauth: () => void, + ) => void, ): void { - if (budget.active >= MAX_IN_FLIGHT_RPC_BODIES) { - const failure = normalizeError( - new AppError('COMMAND_FAILED', 'RPC ingress capacity exceeded', { - reason: RPC_INGRESS_REASONS.capacityExceeded.reason, - retriable: true, - }), + if (budget.preauthRequests >= MAX_RPC_PREAUTH_REQUESTS) { + res.setHeader('connection', 'close'); + sendRpcPreauthRefusal( + res, + null, + 503, + 'RPC preauthorization capacity exceeded', + DAEMON_RPC_INGRESS_REASONS.preauthCapacityExceeded.reason, ); - sendRpcRefusal(res, rpcRefusal(null, -32000, failure.message, 503, failure)); - req.resume(); return; } - budget.active += 1; + budget.preauthRequests += 1; + const preauth = new AbortController(); + let deadline: ReturnType | undefined = setTimeout(() => { + preauth.abort(new Error('RPC ingress deadline exceeded')); + release(); + if (!res.headersSent && !res.writableEnded) { + res.once('finish', () => req.destroy()); + sendRpcPreauthRefusal( + res, + bodyComplete ? readCompletedRpcId(body) : null, + 408, + 'RPC ingress deadline exceeded', + DAEMON_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason, + ); + } else { + req.destroy(); + } + }, DAEMON_RPC_PREAUTH_TIMEOUT_MS); + const finishPreauth = () => { + if (deadline === undefined) return; + clearTimeout(deadline); + deadline = undefined; + budget.preauthRequests -= 1; + res.off('close', release); + }; let body = ''; let bodyBytes = 0; let released = false; let bodyComplete = false; - const onAborted = () => { - if (!bodyComplete) release(); - }; const release = () => { if (released) return; released = true; - req.off('aborted', onAborted); - budget.active -= 1; + finishPreauth(); budget.bytes -= bodyBytes; }; req.setEncoding('utf8'); req.on('data', (chunk: string) => { + if (released) return; const bytes = Buffer.byteLength(chunk, 'utf8'); if ( bodyBytes + bytes > MAX_HTTP_RPC_BODY_BYTES || @@ -356,21 +392,48 @@ function readRpcRequestBody( req.on('error', () => { if (!bodyComplete) release(); - if (!res.headersSent) { + if (!res.headersSent && !res.writableEnded) { sendRpcRefusal(res, rpcParseErrorRefusal()); } }); - req.once('aborted', onAborted); + res.once('close', release); req.on( 'end', AsyncResource.bind(() => { + if (released) return; bodyComplete = true; - onBody(body, release); + onBody(body, release, preauth.signal, finishPreauth); }), ); } +function sendRpcPreauthRefusal( + res: http.ServerResponse, + id: string | number | null, + status: number, + message: string, + reason: string, +): void { + const error = normalizeError( + new AppError('COMMAND_FAILED', message, { reason, dispatched: 'no', retriable: true }), + ); + sendRpcRefusal(res, rpcRefusal(id, -32000, error.message, status, error)); +} + +function readCompletedRpcId(body: string): string | number | null { + try { + const parsed: unknown = JSON.parse(body); + if (!isRecord(parsed)) return null; + const id = parsed.id; + if (typeof id === 'string') return id.length <= DAEMON_RPC_PREAUTH_MAX_ID_LENGTH ? id : null; + if (typeof id === 'number') return Number.isFinite(id) ? id : null; + } catch { + // An incomplete or malformed body has no request id to preserve. + } + return null; +} + // The `/rpc` flow, in the order it runs: the envelope decides whether this body is a // call at all; admission decides whether its caller may run it; the lifetime owns the // tracking id and cancellation from that moment to cleanup; invocation runs the @@ -387,8 +450,21 @@ async function handleRpcRequest(params: { handleRequest: DaemonInvokeFn; /** The call came on the checked route, so its protocol is checked before dispatch. */ checked: boolean; + preauthSignal: AbortSignal; + finishPreauth: () => void; }): Promise { - const { req, res, body, authHook, expectedToken, instanceId, handleRequest, checked } = params; + const { + req, + res, + body, + authHook, + expectedToken, + instanceId, + handleRequest, + checked, + preauthSignal, + finishPreauth, + } = params; // A checked call proves its credential before anything reads its protocol or method. One on // another protocol then takes the `/rpc` flow and is refused only once every auth gate passed. if (checked && refuseCheckedRpcCredential(req, res, body, expectedToken)) return; @@ -416,7 +492,9 @@ async function handleRpcRequest(params: { params: validated.params, lifetime, protocolRefusal, + preauthSignal, }); + finishPreauth(); if (admission.outcome !== 'admitted') { if (admission.outcome === 'rejected') { sendRpcRefusal(res, admission.refusal); @@ -424,6 +502,8 @@ async function handleRpcRequest(params: { return; } + preauthSignal.throwIfAborted(); + lifetime.watchForClientDisconnect(); await invokeAdmittedRpcRequest({ res, @@ -437,7 +517,8 @@ async function handleRpcRequest(params: { // or a duplicate tracking id. The failure answer is on its way, so a socket closing // after it is not a client walking out on work still in flight. lifetime.markHandlerCompleted(); - sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); + if (!res.writableEnded) + sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); } finally { lifetime.release(); } @@ -663,8 +744,19 @@ async function admitRpcRequest(params: { lifetime: RpcRequestLifetime; /** A checked call's protocol refusal, answered once the caller passes the auth gates. */ protocolRefusal: CheckedRpcProtocolRefusal | undefined; + preauthSignal: AbortSignal; }): Promise { - const { req, res, authHook, expectedToken, instanceId, rpcRequest, method, lifetime } = params; + const { + req, + res, + authHook, + expectedToken, + instanceId, + rpcRequest, + method, + lifetime, + preauthSignal, + } = params; const { protocolRefusal } = params; const wireRequest = methodToDaemonRequest(method, params.params, req.headers); // A command call naming no command is params the router cannot route. @@ -692,7 +784,7 @@ async function admitRpcRequest(params: { headers: req.headers, rpcRequest, daemonRequest, - signal: lifetime.signal, + signal: AbortSignal.any([lifetime.signal, preauthSignal]), }); if (!authResult.ok) { return { diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts index 07761e6c71..30b6d729fd 100644 --- a/packages/proxy/src/daemon-proxy-cancellation.test.ts +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -3,6 +3,8 @@ import type { AddressInfo } from 'node:net'; import { setFlagsFromString } from 'node:v8'; import { runInNewContext } from 'node:vm'; import { expect, onTestFinished, test, vi } from 'vitest'; +import { DAEMON_RPC_PREAUTH_MAX_ID_LENGTH } from '@agent-device/contracts/daemon-http'; +import { AppError } from '@agent-device/kernel/errors'; import { createDaemonProxy, createDaemonProxyServer, @@ -69,7 +71,7 @@ function rpcRequest(body: unknown, init: RequestInit = {}): Request { }); } -test('a disconnected RPC stops waiting for authentication and releases its body slot', async () => { +test('a pending RPC authentication does not block another caller', async () => { let authenticating = 0; const proxy = createDaemonProxy({ upstreamBaseUrl: 'http://daemon.internal:4310', @@ -90,21 +92,147 @@ test('a disconnected RPC stops waiting for authentication and releases its body ), ); await vi.waitFor(() => expect(authenticating).toBe(32)); - const full = await proxy.handle( + const admitted = await proxy.handle( rpcRequest({ jsonrpc: '2.0', id: 33, method: 'agent-device.command' }), ); - expect(full.status).toBe(503); + expect(admitted.status).toBe(200); controllers[0]!.abort(); await pending[0]; - const admitted = await proxy.handle( + const afterDisconnect = await proxy.handle( rpcRequest({ jsonrpc: '2.0', id: 34, method: 'agent-device.command' }), ); - expect(admitted.status).toBe(200); + expect(afterDisconnect.status).toBe(200); for (const controller of controllers.slice(1)) controller.abort(); await Promise.all(pending); }); +test('RPC authentication that completes after the ingress deadline cannot dispatch', async () => { + vi.useFakeTimers(); + try { + const entered = signalled(); + const auth = Promise.withResolvers<{ tenantId: string }>(); + const upstreamFetch = vi.fn(async () => Response.json({ ok: true })); + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch, + authenticate: () => { + entered.resolve(); + return auth.promise; + }, + }); + const pending = proxy.handle( + rpcRequest({ jsonrpc: '2.0', id: 1, method: 'agent-device.command' }), + ); + await entered.promise; + await vi.advanceTimersByTimeAsync(5_001); + const response = await pending; + const body = (await response.json()) as { + id?: unknown; + error?: { data?: { details?: { reason?: string; dispatched?: string } } }; + }; + expect(response.status).toBe(408); + expect(body.id).toBe(1); + expect(body.error?.data?.details).toMatchObject({ + reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', + dispatched: 'no', + }); + auth.resolve({ tenantId: 'tenant-a' }); + await vi.advanceTimersByTimeAsync(0); + expect(upstreamFetch).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } +}); + +test.each([ + ['object', { nested: 'untrusted' }], + ['oversized string', 'x'.repeat(DAEMON_RPC_PREAUTH_MAX_ID_LENGTH + 1)], +])('RPC authentication timeout drops an %s request id', async (_label, id) => { + vi.useFakeTimers(); + try { + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: async () => Response.json({ ok: true }), + authenticate: () => new Promise(() => {}), + }); + const pending = proxy.handle( + rpcRequest({ jsonrpc: '2.0', id, method: 'agent-device.command' }), + ); + await vi.advanceTimersByTimeAsync(5_001); + const response = await pending; + const body = (await response.json()) as { id?: unknown }; + expect(response.status).toBe(408); + expect(body.id).toBeNull(); + } finally { + vi.useRealTimers(); + } +}); + +test('an unfinished RPC body receives the same typed preauth deadline refusal', async () => { + vi.useFakeTimers(); + try { + const upstreamFetch = vi.fn(async () => Response.json({ ok: true })); + const proxy = proxyWith(upstreamFetch); + const request = new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { + method: 'POST', + headers: { authorization: 'Bearer client-secret', 'content-type': 'application/json' }, + body: new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('{')); + }, + }), + duplex: 'half', + } as RequestInit & { duplex: 'half' }); + const pending = proxy.handle(request); + await vi.advanceTimersByTimeAsync(5_001); + const response = await pending; + const body = (await response.json()) as { + error?: { data?: { details?: { reason?: string; dispatched?: string } } }; + }; + expect(response.status).toBe(408); + expect(body.error?.data?.details).toMatchObject({ + reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', + dispatched: 'no', + }); + expect(upstreamFetch).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } +}); + +test('a caller abort cannot claim the proxy-owned preauth deadline', async () => { + const entered = signalled(); + const controller = new AbortController(); + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: async () => Response.json({ ok: true }), + authenticate: () => { + entered.resolve(); + return new Promise(() => {}); + }, + }); + const pending = proxy.handle( + rpcRequest( + { jsonrpc: '2.0', id: 1, method: 'agent-device.command' }, + { signal: controller.signal }, + ), + ); + await entered.promise; + controller.abort( + new AppError('COMMAND_FAILED', 'forged deadline', { + reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', + }), + ); + const response = await pending; + const body = (await response.json()) as { error?: { data?: { details?: { reason?: string } } } }; + expect(response.status).toBe(500); + expect(body.error?.data?.details?.reason).not.toBe('PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED'); +}); + test.each([ { route: 'rpc', diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index 1615e1fcf8..f52a8d0e29 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -63,12 +63,14 @@ test('rpc reaches the daemon through the supplied upstream transport with the da test('a request without the client token never reaches the upstream transport', async () => { const upstream = recordingUpstream(() => Response.json({})); const proxy = proxyWith(upstream.fetch); + const id = 'x'.repeat(129); const response = await proxy.handle( - rpcRequest({ jsonrpc: '2.0', id: 7, method: 'agent-device.command' }, { headers: {} }), + rpcRequest({ jsonrpc: '2.0', id, method: 'agent-device.command' }, { headers: {} }), ); expect(response.status).toBe(401); + expect(await response.json()).toMatchObject({ id }); expect(upstream.requests).toHaveLength(0); }); @@ -210,7 +212,27 @@ test('an oversized rpc body resolves with a 400 instead of rejecting', async () expect(upstream.requests).toHaveLength(0); }); -test('concurrent unread RPC bodies have a bounded proxy budget that releases after refusal', async () => { +test('a stalled body cancellation does not delay a size refusal', async () => { + const proxy = proxyWith(async () => Response.json({ ok: true }), 16); + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(17)); + }, + cancel() { + return new Promise(() => {}); + }, + }); + const response = await proxy.handle( + new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { + method: 'POST', + body, + duplex: 'half', + } as RequestInit & { duplex: 'half' }), + ); + expect(response.status).toBe(400); +}); + +test('unread unauthenticated RPC bodies do not block an authenticated caller', async () => { const upstream = recordingUpstream(() => Response.json({ ok: true })); const proxy = proxyWith(upstream.fetch); const bodies: ReadableStreamDefaultController[] = []; @@ -229,35 +251,17 @@ test('concurrent unread RPC bodies have a bounded proxy budget that releases aft ); }); - let refusedBodyCanceled = false; - const refusedBody = new ReadableStream({ - cancel() { - refusedBodyCanceled = true; - }, - }); - const refused = await proxy.handle( - new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { - method: 'POST', - body: refusedBody, - duplex: 'half', - } as RequestInit & { duplex: 'half' }), - ); - expect(refused.status).toBe(503); - await vi.waitFor(() => expect(refusedBodyCanceled).toBe(true)); - expect(await refused.json()).toMatchObject({ - error: { data: { details: { reason: 'PROXY_RPC_BODY_CAPACITY_EXCEEDED' } } }, - }); - expect(upstream.requests).toHaveLength(0); - - for (const body of bodies) body.close(); - await Promise.all(pending); const admitted = await proxy.handle( rpcRequest({ jsonrpc: '2.0', id: 34, method: 'agent-device.command' }), ); expect(admitted.status).toBe(200); + expect(upstream.requests).toHaveLength(1); + + for (const body of bodies) body.close(); + await Promise.all(pending); }); -test('aborting an unread RPC body releases its proxy budget slot', async () => { +test('aborting an unread RPC body does not affect another caller', async () => { const upstream = recordingUpstream(() => Response.json({ ok: true })); const proxy = proxyWith(upstream.fetch); const controllers = Array.from({ length: 32 }, () => new AbortController()); @@ -271,10 +275,10 @@ test('aborting an unread RPC body releases its proxy budget slot', async () => { } as RequestInit & { duplex: 'half' }), ), ); - const full = await proxy.handle( + const first = await proxy.handle( rpcRequest({ jsonrpc: '2.0', id: 33, method: 'agent-device.command' }), ); - expect(full.status).toBe(503); + expect(first.status).toBe(200); controllers[0]!.abort(); await pending[0]; diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 9268ace267..80061d7ac4 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto'; import http from 'node:http'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, createRequestCanceledError, normalizeError } from '@agent-device/kernel/errors'; import { timingSafeStringEqual } from '@agent-device/host-kit/transport'; import { buildDaemonHealthPayload, @@ -20,6 +20,8 @@ import { normalizeTenantId, normalizeDaemonPublicOrigin, DAEMON_REQUEST_MAX_BYTES, + DAEMON_RPC_PREAUTH_MAX_ID_LENGTH, + DAEMON_RPC_PREAUTH_TIMEOUT_MS, DAEMON_INSTANCE_REASONS, DAEMON_HTTP_CHECKED_RPC_CAPABILITY, DAEMON_HTTP_CHECKED_RPC_ROUTE, @@ -133,7 +135,6 @@ type ProxyCaller = { tenantId?: string; uploadHeaders: Record }; /** The client request headers an upload ticket repeats when `authenticate` names none. */ const DEFAULT_UPLOAD_CREDENTIAL_HEADERS = Object.keys(buildDaemonHttpAuthHeaders('client')); - const DEFAULT_MAX_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; /** `/health` answers quickly or not at all; its probe never waits on `upstreamTimeoutMs`. */ const UPSTREAM_HEALTH_TIMEOUT_MS = 5_000; @@ -206,28 +207,59 @@ async function handleProxyRequest( return new Response(new TextEncoder().encode('Not found'), { status: 404 }); } - if (!isRpcRoute(route)) return await handleDaemonRoute(request, route, options, instanceId); + return isRpcRoute(route) + ? await handleRpcRoute(request, route, options, instanceId) + : await handleDaemonRoute(request, route, options, instanceId); +} - let ingress: { body: string; release: () => void }; - try { - ingress = await (await options.getRpcBodyBudget()).read(request, options.maxRpcBodyBytes); - } catch (error) { - return rpcErrorResponse(null, error); - } +async function handleRpcRoute( + request: Request, + route: string, + options: NormalizedProxyOptions, + instanceId: string, +): Promise { + const { refuseInvalidRpcEnvelope, rpcErrorResponse, rpcPreauthDeadlineError } = + await import('./rpc-refusals.ts'); + const preauth = new AbortController(); + const signal = AbortSignal.any([request.signal, preauth.signal]); + let deadline: ReturnType | undefined = setTimeout( + () => preauth.abort(rpcPreauthDeadlineError()), + DAEMON_RPC_PREAUTH_TIMEOUT_MS, + ); + let ingress: { body: string; release: () => void } | undefined; try { + ingress = await ( + await options.getRpcBodyBudget() + ).read(request, options.maxRpcBodyBytes, signal); const rpcBody = ingress.body; // The checked route checks its envelope after authentication and the protocol: a caller on // another protocol is told so before the proxy reads what its own protocol defines. const envelopeRefusal = route === DAEMON_HTTP_CHECKED_RPC_ROUTE ? null : refuseInvalidRpcEnvelope(rpcBody); if (envelopeRefusal) return envelopeRefusal; - try { - return await handleDaemonRoute(request, route, options, instanceId, rpcBody); - } catch (error) { - return rpcErrorResponse(readJsonRpcId(rpcBody), error); + const caller = await authenticateCaller(request, options, rpcBody, signal); + signal.throwIfAborted(); + clearTimeout(deadline); + deadline = undefined; + return await handleDaemonRoute(request, route, options, instanceId, rpcBody, caller); + } catch (error) { + let refusal = error; + if (deadline !== undefined && signal.aborted) { + refusal = + preauth.signal.aborted && signal.reason === preauth.signal.reason + ? preauth.signal.reason + : createRequestCanceledError(undefined, signal.reason); } + const id = readJsonRpcId(ingress?.body); + const oversizedTimeoutId = + preauth.signal.aborted && + refusal === preauth.signal.reason && + typeof id === 'string' && + id.length > DAEMON_RPC_PREAUTH_MAX_ID_LENGTH; + return rpcErrorResponse(oversizedTimeoutId ? null : id, refusal); } finally { - ingress.release(); + clearTimeout(deadline); + ingress?.release(); } } @@ -237,14 +269,19 @@ async function handleDaemonRoute( options: NormalizedProxyOptions, instanceId: string, rpcBody?: string, + admittedCaller?: ProxyCaller | null, ): Promise { - const caller = await authenticateCaller(request, options, rpcBody); + const caller = + admittedCaller === undefined + ? await authenticateCaller(request, options, rpcBody) + : admittedCaller; if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } if (route === DAEMON_HTTP_CHECKED_RPC_ROUTE) { // Loaded only on the checked route: authentication, then the protocol, then the envelope. const { refuseCheckedRpcProtocol } = await import('./checked-rpc-admission.ts'); + const { refuseInvalidRpcEnvelope } = await import('./rpc-refusals.ts'); const refusal = (await refuseCheckedRpcProtocol(request, readJsonRpcId(rpcBody))) ?? refuseInvalidRpcEnvelope(rpcBody ?? ''); @@ -279,6 +316,7 @@ async function authenticateCaller( request: Request, options: NormalizedProxyOptions, rpcBody: string | undefined, + signal: AbortSignal = request.signal, ): Promise { if (!options.authenticate) { return isAuthorized(request, options.clientToken ?? '', rpcBody) @@ -292,12 +330,12 @@ async function authenticateCaller( forwardedRequest(request, request.url, { method: request.method, headers: request.headers, - signal: request.signal, + signal, ...(rpcBody !== undefined ? { body: rpcBody } : {}), }), ), ), - request.signal, + signal, ); if (!result) return null; const tenantId = normalizeTenantId( @@ -845,14 +883,18 @@ function readJsonRpcMethod(body: string | undefined): string | undefined { } } -function readJsonRpcId(body: string | undefined): unknown { +function readJsonRpcId(body: string | undefined): string | number | null { if (!body) return null; try { - const parsed = JSON.parse(body) as { id?: unknown }; - return parsed.id ?? null; + const parsed: unknown = JSON.parse(body); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null; + const id = (parsed as { id?: unknown }).id; + if (typeof id === 'string') return id; + if (typeof id === 'number') return Number.isFinite(id) ? id : null; } catch { - return null; + // A malformed body has no request id to preserve. } + return null; } function resolveRequestId(request: Request): string { @@ -925,51 +967,6 @@ function tenantRpcMethodRefusedResponse(rpcId: unknown): Response { ); } -const JSON_RPC_PARSE_ERROR = -32700; -const JSON_RPC_INVALID_REQUEST = -32600; - -/** Refuses an `/rpc` body that is not JSON, or not one object, as the daemon itself does. */ -function refuseInvalidRpcEnvelope(body: string): Response | null { - let parsed: unknown; - try { - parsed = JSON.parse(body); - } catch { - return rpcRefusalResponse(JSON_RPC_PARSE_ERROR, 'Parse error'); - } - if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return null; - return rpcRefusalResponse(JSON_RPC_INVALID_REQUEST, 'Invalid Request'); -} - -function rpcRefusalResponse(code: number, message: string): Response { - return Response.json( - { - jsonrpc: '2.0', - id: null, - error: { - code, - message, - data: normalizeError(new AppError('INVALID_ARGS', message)), - }, - }, - { status: 400 }, - ); -} - -/** An `/rpc` failure in the JSON-RPC envelope the client reads its error code and message from. */ -function rpcErrorResponse(rpcId: unknown, error: unknown): Response { - const normalized = normalizeError(error); - const invalidArgs = normalized.code === 'INVALID_ARGS'; - const capacityExceeded = normalized.details?.reason === 'PROXY_RPC_BODY_CAPACITY_EXCEEDED'; - return Response.json( - { - jsonrpc: '2.0', - id: rpcId, - error: { code: invalidArgs ? -32602 : -32000, message: normalized.message, data: normalized }, - }, - { status: invalidArgs ? 400 : capacityExceeded ? 503 : 500 }, - ); -} - async function proxyErrorResponse(error: unknown, request: Request): Promise { const details = isTransferRoute(resolveProxyRoute(request.url), request.method) ? (await import('./transfer-transport.ts')).transferWireDetails(error) diff --git a/packages/proxy/src/node-http.test.ts b/packages/proxy/src/node-http.test.ts index 26378bb976..de38829986 100644 --- a/packages/proxy/src/node-http.test.ts +++ b/packages/proxy/src/node-http.test.ts @@ -130,6 +130,42 @@ test('a handler can cancel an unread body and still answer the request', async ( } }); +test('cancelling an unfinished body still writes a capacity refusal', async () => { + const proxy: DaemonProxy = { + instanceId: 'test', + handle: async (request) => { + await request.body?.cancel(); + return new Response(null, { status: 503 }); + }, + }; + const server = http.createServer((req, res) => void serveProxyRequest(proxy, req, res)); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const status = await new Promise((resolve, reject) => { + const client = http.request( + { + port, + host: '127.0.0.1', + method: 'POST', + path: '/agent-device/rpc', + headers: { 'content-length': '100' }, + }, + (response) => { + response.resume(); + resolve(response.statusCode); + }, + ); + client.on('error', reject); + client.write('partial'); + }); + expect(status).toBe(503); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + } +}); + test('real HTTP ingress refuses invalid targets and Host before forwarding', async () => { let calls = 0; const server = http.createServer( diff --git a/packages/proxy/src/rpc-body-budget.ts b/packages/proxy/src/rpc-body-budget.ts index bca4dc51e7..c18299cd3b 100644 --- a/packages/proxy/src/rpc-body-budget.ts +++ b/packages/proxy/src/rpc-body-budget.ts @@ -5,10 +5,9 @@ import { } from '@agent-device/kernel/errors'; import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; -const MAX_IN_FLIGHT_RPC_BODIES = 32; const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; const RPC_INGRESS_REASONS = { - // Too many proxy RPC requests or aggregate body bytes are in flight through dispatch. + // Proxy RPC request bodies exceed the aggregate buffered-byte limit. capacityExceeded: { reason: 'PROXY_RPC_BODY_CAPACITY_EXCEEDED' }, } as const satisfies ReasonTable<'proxy RPC ingress'>; @@ -21,23 +20,20 @@ function capacityError(): AppError { /** Holds the body bytes until the caller finishes authentication and dispatch. */ export function createRpcBodyBudget(): { - read(request: Request, maxBodyBytes: number): Promise<{ body: string; release: () => void }>; + read( + request: Request, + maxBodyBytes: number, + signal: AbortSignal, + ): Promise<{ body: string; release: () => void }>; } { - let active = 0; let totalBytes = 0; return { - async read(request, maxBodyBytes) { - if (active >= MAX_IN_FLIGHT_RPC_BODIES) { - void request.body?.cancel().catch(() => {}); - throw capacityError(); - } - active += 1; + async read(request, maxBodyBytes, signal) { let ownedBytes = 0; let released = false; const release = () => { if (released) return; released = true; - active -= 1; totalBytes -= ownedBytes; }; try { @@ -45,17 +41,17 @@ export function createRpcBodyBudget(): { const reader = request.body.getReader(); const chunks: Uint8Array[] = []; for (;;) { - const { done, value } = await awaitWithSignal(reader.read(), request.signal, () => { + const { done, value } = await awaitWithSignal(reader.read(), signal, () => { void reader.cancel().catch(() => {}); - return createRequestCanceledError(undefined, request.signal.reason); + return createRequestCanceledError(undefined, signal.reason); }); if (done) break; if (ownedBytes + value.byteLength > maxBodyBytes) { - await reader.cancel(); + void reader.cancel().catch(() => {}); throw new AppError('INVALID_ARGS', 'Proxy request body is too large.'); } if (totalBytes + value.byteLength > MAX_IN_FLIGHT_RPC_BODY_BYTES) { - await reader.cancel(); + void reader.cancel().catch(() => {}); throw capacityError(); } ownedBytes += value.byteLength; diff --git a/packages/proxy/src/rpc-refusals.ts b/packages/proxy/src/rpc-refusals.ts new file mode 100644 index 0000000000..a9f48d27aa --- /dev/null +++ b/packages/proxy/src/rpc-refusals.ts @@ -0,0 +1,60 @@ +import { AppError, normalizeError, type ReasonTable } from '@agent-device/kernel/errors'; + +const JSON_RPC_PARSE_ERROR = -32700; +const JSON_RPC_INVALID_REQUEST = -32600; +const PROXY_RPC_INGRESS_REASONS = { + // Proxy RPC body or authentication did not finish before its deadline, so nothing was dispatched. + preauthDeadlineExceeded: { reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED' }, +} as const satisfies ReasonTable<'proxy RPC ingress'>; + +export function rpcPreauthDeadlineError(): AppError { + return new AppError('COMMAND_FAILED', 'Proxy RPC ingress deadline exceeded', { + reason: PROXY_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason, + dispatched: 'no', + retriable: true, + }); +} + +/** Refuses an `/rpc` body that is not JSON, or not one object, as the daemon itself does. */ +export function refuseInvalidRpcEnvelope(body: string): Response | null { + let parsed: unknown; + try { + parsed = JSON.parse(body); + } catch { + return rpcRefusalResponse(JSON_RPC_PARSE_ERROR, 'Parse error'); + } + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return null; + return rpcRefusalResponse(JSON_RPC_INVALID_REQUEST, 'Invalid Request'); +} + +function rpcRefusalResponse(code: number, message: string): Response { + return Response.json( + { + jsonrpc: '2.0', + id: null, + error: { + code, + message, + data: normalizeError(new AppError('INVALID_ARGS', message)), + }, + }, + { status: 400 }, + ); +} + +/** An `/rpc` failure in the JSON-RPC envelope the client reads its error code and message from. */ +export function rpcErrorResponse(rpcId: string | number | null, error: unknown): Response { + const normalized = normalizeError(error); + const invalidArgs = normalized.code === 'INVALID_ARGS'; + const capacityExceeded = normalized.details?.reason === 'PROXY_RPC_BODY_CAPACITY_EXCEEDED'; + const preauthDeadline = + normalized.details?.reason === PROXY_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason; + return Response.json( + { + jsonrpc: '2.0', + id: rpcId, + error: { code: invalidArgs ? -32602 : -32000, message: normalized.message, data: normalized }, + }, + { status: invalidArgs ? 400 : capacityExceeded ? 503 : preauthDeadline ? 408 : 500 }, + ); +} diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 297cc732af..fdfde816db 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -460,7 +460,8 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `RPC_BODY_CAPACITY_EXCEEDED` | Too many daemon RPC requests are in flight through dispatch. The daemon closes a request that exceeds its aggregate body-byte limit. | +| `RPC_PREAUTH_CAPACITY_EXCEEDED` | The daemon has no free slot to receive and authenticate another RPC request. | +| `RPC_PREAUTH_DEADLINE_EXCEEDED` | The RPC body or authentication did not finish before its preauthorization deadline, so nothing was dispatched. | ### Swift helper cache @@ -928,7 +929,8 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `PROXY_RPC_BODY_CAPACITY_EXCEEDED` | Too many proxy RPC requests or aggregate body bytes are in flight through dispatch. | +| `PROXY_RPC_BODY_CAPACITY_EXCEEDED` | Proxy RPC request bodies exceed the aggregate buffered-byte limit. | +| `PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED` | Proxy RPC body or authentication did not finish before its deadline, so nothing was dispatched. | ### Ref frames diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 70dd11af60..82b9ef6616 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -31,7 +31,9 @@ Holds and leases live in memory; neither survives a daemon restart. When a hook is configured, it must attest a `tenantId` on every request it wants admitted. If the hook's result has no `tenantId`, the daemon rejects the request with 401. It never falls back to a tenant the client declares (RPC body `meta.tenantId` or `flags.tenant`, or the `x-agent-device-tenant` header on the upload, artifact-download, and diagnostics routes), and it never admits the request unscoped. This keeps a caller with a shared token from claiming another tenant's identity, or from reading a tenant-owned session or artifact by declaring no tenant. Deployments without a hook are unaffected. -A tenant can read only artifacts registered to that tenant. Artifacts produced by local work without a tenant remain available to local callers without a tenant. Cloud artifact lookup by lease ID requires an active lease whose tenant, run, and provider match the request. The daemon and proxy each limit concurrent RPC requests to 32 and their accumulated request bodies to 128 MiB. These budgets remain reserved through request dispatch. When the concurrent request limit is reached, the daemon returns 503 with reason `RPC_BODY_CAPACITY_EXCEEDED`; when its aggregate byte limit is reached, it closes the request. The proxy returns 503 with reason `PROXY_RPC_BODY_CAPACITY_EXCEEDED` when either limit is reached. +A tenant can read only artifacts registered to that tenant. Artifacts produced by local work without a tenant remain available to local callers without a tenant. Cloud artifact lookup by lease ID requires an active lease whose tenant, run, and provider match the request. The daemon and proxy each limit accumulated RPC request bodies to 128 MiB. A body and its authentication must finish within five seconds. Buffered body bytes remain reserved through dispatch. When the aggregate byte limit is reached, the daemon closes the request and the proxy returns 503 with reason `PROXY_RPC_BODY_CAPACITY_EXCEEDED`. + +The daemon allows up to 128 RPC requests to receive a body or wait for authentication at once. When all slots are occupied, it returns a retriable HTTP 503 with reason `RPC_PREAUTH_CAPACITY_EXCEEDED` before dispatch. ## Remote access