From 861ac019c4134cf04134629ee281b7a049f89621 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 08:17:06 +0100 Subject: [PATCH 1/5] feat(daemon,proxy): serve checked RPC that refuses protocol skew before dispatch POST /rpc/checked takes the same auth, body and answer as /rpc. After authentication, the daemon and the proxy compare the mandatory x-agent-device-rpc-protocol header with their own protocol before they decode anything that protocol defines, and refuse with 409 plus a typed x-agent-device-refusal header. The proxy admits both routes through one path, checks its own protocol, and forwards to the daemon's checked route. /health advertises checked-rpc. Additive: no protocol bump. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0006-daemon-rpc-protocol-version.md | 30 +++- packages/contracts/src/daemon-http.ts | 76 ++++++++- .../src/server/http/http-checked-rpc.test.ts | 149 +++++++++++++++++ .../src/server/http/http-checked-rpc.ts | 129 ++++++++++++++ .../daemon/src/server/http/http-server.ts | 31 +++- .../src/daemon-proxy-checked-rpc.test.ts | 158 ++++++++++++++++++ packages/proxy/src/daemon-proxy.ts | 83 ++++++++- test/wire-compat/ledger.json | 25 ++- test/wire-compat/surface.ts | 24 +++ website/docs/docs/error-reasons.md | 2 + 10 files changed, 690 insertions(+), 17 deletions(-) create mode 100644 packages/daemon/src/server/http/http-checked-rpc.test.ts create mode 100644 packages/daemon/src/server/http/http-checked-rpc.ts create mode 100644 packages/proxy/src/daemon-proxy-checked-rpc.test.ts diff --git a/docs/adr/0006-daemon-rpc-protocol-version.md b/docs/adr/0006-daemon-rpc-protocol-version.md index 46e27836b8..b61f796c19 100644 --- a/docs/adr/0006-daemon-rpc-protocol-version.md +++ b/docs/adr/0006-daemon-rpc-protocol-version.md @@ -6,7 +6,9 @@ Accepted ## Rules at a glance -- Before remote JSON-RPC requests, compare the daemon's `rpcProtocolVersion` from `/health`. +- Before remote JSON-RPC requests, compare the daemon's `rpcProtocolVersion` from `/health`, or send them on the checked route, where the server makes that comparison. +- The checked route refuses every precondition after authentication and before dispatch, with HTTP 409 and a typed `x-agent-device-refusal` header. +- A client uses the checked route only when its connection opts in. It never resends a checked call and never falls back to `/rpc` after one. - Package `version` is diagnostic only and must not be used as a compatibility gate. - Allow a missing `rpcProtocolVersion` unless a later security or protocol decision explicitly retires legacy compatibility. - A persistent client may cache a successful probe if `/health` advertises an instance ID for the daemon endpoint and, for a proxy, for its upstream daemon. @@ -51,6 +53,29 @@ A peer that advertises an instance ID must continue to honor the conditional RPC The reason is that older clients may hold a cached identity across a restart. Such clients must receive a pre-dispatch refusal before they retry a mutating command. +### Checked RPC + +`POST /rpc/checked` takes the same authentication, body, and answer as `/rpc`. +The client names its protocol in the mandatory `x-agent-device-rpc-protocol` header. +The daemon or proxy authenticates the caller first. +Then it compares that header with its own protocol, before it decodes anything that its own protocol defines. +A missing header or another protocol gets HTTP 409, `x-agent-device-refusal: protocol-missing` or `protocol-mismatch`, and a JSON-RPC error. +The error details name the refusing `service`, its `version`, and its `rpcProtocolVersion`, so the client can name who must upgrade. +A proxy admits `/rpc` and the checked route through one path: body limit, authentication, tenant method rules, credential rewriting, and public-only stamping. +A proxy checks its own protocol, then forwards to the daemon's checked route, which checks again. +The proxy marks a forwarded daemon protocol refusal as `upstream-protocol-mismatch`. +A call that records a session script (`scriptPublicationId`) needs the `script-artifacts` capability; the daemon reads that requirement from the request itself and refuses with `script-artifacts`. +`/health` advertises `checked-rpc` on each link that serves the route. + +The route, not a header, is what makes the check safe. +Released daemons and proxies answer an unknown route with 404 before dispatch, and they ignore unknown headers on `/rpc`. +A 404 is still not proof of non-dispatch, because a gateway can answer for a command that ran. +So a client does not discover the route. +The connection opts in with `daemonRpc: "checked"`, which `connect` accepts only when `/health` advertises `checked-rpc` on every link. +With the opt-in, a 404 is a typed failure with `dispatched: 'unknown'`, and the client does not resend. +Flows with remote side effects before the command, such as artifact uploads and lease beats, keep the `/health` probe and the instance headers. +A connect timeout before the socket connects is proof, inside the client, that nothing left; only then does the client run the `/health` recovery loop and send once. + `rpcProtocolVersion` changes only when an older client and newer daemon, or a newer client and older daemon, cannot safely communicate over the HTTP RPC boundary for existing commands. Increment it for incompatible changes to: @@ -77,6 +102,9 @@ This preference does not apply if the change also affects the shared transport c - **Do not check compatibility.** This maximizes compatibility. However, it fails later, after the client has sent an RPC payload that a remote daemon may parse incorrectly. - **Negotiate full schemas.** This is more precise, but it is too much machinery for the current JSON-RPC boundary. +- **Persist the `/health` answer in the client state directory (#5134).** It saves the probe across CLI processes, but it adds a local trust boundary and cache rules, and a rollback to a daemon that ignores instance headers would dispatch on a stale view. +- **Send the protocol as a header on `/rpc`.** Released daemons ignore unknown headers and dispatch anyway. +- **Fall back to `/health` and `/rpc` after a 404 on the checked route.** A 404 can come after dispatch, so the fallback could run a command twice. ## Consequences diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 78c6122085..4b9a8e1b08 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -1,5 +1,5 @@ import path from 'node:path'; -import type { ReasonTable } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; // The daemon HTTP wire vocabulary shared by the daemon server, the remote // proxy, and every client that talks to them: the base path, the tenant, lease @@ -147,6 +147,80 @@ export const DAEMON_INSTANCE_REASONS = { instanceMismatch: { reason: 'remote_instance_mismatch' }, } as const satisfies ReasonTable<'remote connection'>; +/** + * The checked RPC route (ADR 0006). It takes the same auth, body and answer as `/rpc`, and the + * server itself refuses a call on another RPC protocol before it dispatches anything. A server that + * predates the route answers 404 before dispatch. + */ +export const DAEMON_HTTP_CHECKED_RPC_ROUTE = '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/rpc/checked'; +/** The `/health` capability of a daemon or proxy that serves the checked route. */ +export const DAEMON_HTTP_CHECKED_RPC_CAPABILITY = 'checked-rpc'; +/** The caller's `DAEMON_RPC_PROTOCOL_VERSION`. The checked route refuses a call without it. */ +export const DAEMON_HTTP_RPC_PROTOCOL_HEADER = 'x-agent-device-rpc-protocol'; +/** Which checked-route precondition refused a call. It comes only on a 409, before dispatch. */ +export const DAEMON_HTTP_REFUSAL_HEADER = 'x-agent-device-refusal'; +export const DAEMON_HTTP_REFUSALS = { + /** The call named no readable RPC protocol. */ + protocolMissing: 'protocol-missing', + /** The daemon or proxy that answered speaks another RPC protocol. */ + protocolMismatch: 'protocol-mismatch', + /** A proxy forwards the protocol refusal of the daemon behind it. */ + upstreamProtocolMismatch: 'upstream-protocol-mismatch', + /** The call records a session script, and the daemon cannot deliver one. */ + scriptArtifacts: 'script-artifacts', +} as const; +export type DaemonHttpRefusal = (typeof DAEMON_HTTP_REFUSALS)[keyof typeof DAEMON_HTTP_REFUSALS]; + +/** Why the checked RPC route refused a call. Each refusal comes before dispatch. */ +export const DAEMON_CHECKED_RPC_REASONS = { + // The checked RPC call named no RPC protocol. An intermediary that strips request headers causes + // this. + protocolMissing: { reason: 'remote_rpc_protocol_missing' }, + // The daemon or proxy speaks another RPC protocol than the caller; `details.service`, + // `details.version` and `details.rpcProtocolVersion` name the side that refused. + protocolMismatch: { reason: 'remote_rpc_protocol_mismatch' }, +} as const satisfies ReasonTable<'remote connection'>; + +/** The RPC protocol a checked call names, or `undefined` when its header is absent or malformed. */ +export function readDaemonRpcProtocolHeader(value: unknown): number | undefined { + return typeof value === 'string' && /^[0-9]{1,9}$/.test(value) ? Number(value) : undefined; +} + +/** The protocol refusal of a checked call on this build, or `undefined` when its protocol matches. */ +export function checkedRpcProtocolRefusal(headerValue: unknown): DaemonHttpRefusal | undefined { + const protocol = readDaemonRpcProtocolHeader(headerValue); + if (protocol === undefined) return DAEMON_HTTP_REFUSALS.protocolMissing; + return protocol === DAEMON_RPC_PROTOCOL_VERSION + ? undefined + : DAEMON_HTTP_REFUSALS.protocolMismatch; +} + +/** + * The error a daemon or proxy answers a refused checked call with. Its details name the refusing + * side in the `/health` vocabulary, so a client can name who must upgrade. + */ +export function checkedRpcProtocolRefusalError( + refusal: DaemonHttpRefusal, + side: Pick, +): AppError { + const missing = refusal === DAEMON_HTTP_REFUSALS.protocolMissing; + return new AppError( + 'COMMAND_FAILED', + missing + ? `Checked RPC requires the ${DAEMON_HTTP_RPC_PROTOCOL_HEADER} header` + : `The ${side.service} speaks RPC protocol ${DAEMON_RPC_PROTOCOL_VERSION}`, + { + reason: missing + ? DAEMON_CHECKED_RPC_REASONS.protocolMissing.reason + : DAEMON_CHECKED_RPC_REASONS.protocolMismatch.reason, + dispatched: 'no', + service: side.service, + version: side.version, + rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, + }, + ); +} + export function buildDaemonInstanceMismatchRpcResponse( id: Id, message: string, diff --git a/packages/daemon/src/server/http/http-checked-rpc.test.ts b/packages/daemon/src/server/http/http-checked-rpc.test.ts new file mode 100644 index 0000000000..679d5952db --- /dev/null +++ b/packages/daemon/src/server/http/http-checked-rpc.test.ts @@ -0,0 +1,149 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import type http from 'node:http'; +import { createDaemonHttpServer } from './http-server.ts'; +import { refuseUnservedCheckedRequest } from './http-checked-rpc.ts'; +import { + DAEMON_HTTP_CHECKED_RPC_CAPABILITY, + DAEMON_HTTP_CHECKED_RPC_ROUTE, + DAEMON_HTTP_REFUSAL_HEADER, + DAEMON_HTTP_RPC_PROTOCOL_HEADER, + DAEMON_RPC_PROTOCOL_VERSION, +} from '@agent-device/contracts/daemon-http'; +import { + closeLoopbackServer, + listenOnLoopback, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; + +type RpcError = { + error?: { data?: { code?: string; details?: Record } }; +}; + +test('the checked route authenticates, then refuses protocol skew before dispatch', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let handlerCalls = 0; + const server = await createDaemonHttpServer({ + token: 'daemon-secret', + handleRequest: async () => { + handlerCalls += 1; + return { ok: true, data: {} }; + }, + env: process.env, + cwd: process.cwd(), + }); + try { + const endpoint = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const health = (await (await fetch(`${endpoint}/health`)).json()) as { capabilities: string[] }; + assert.ok(health.capabilities.includes(DAEMON_HTTP_CHECKED_RPC_CAPABILITY)); + const checked = (protocol: string | undefined, token = 'daemon-secret') => + fetch(`${endpoint}${DAEMON_HTTP_CHECKED_RPC_ROUTE}`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + authorization: `Bearer ${token}`, + ...(protocol === undefined ? {} : { [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: protocol }), + }, + // A method this build does not know: the skew answer must not depend on decoding it. + body: JSON.stringify({ + jsonrpc: '2.0', + id: 'req-1', + method: 'agent_device.future_method', + params: { command: 'devices' }, + }), + }); + + const unauthenticated = await checked('999', 'wrong-token'); + assert.equal(unauthenticated.status, 401); + assert.equal(unauthenticated.headers.get(DAEMON_HTTP_REFUSAL_HEADER), null); + assert.equal( + ((await unauthenticated.json()) as RpcError).error?.data?.details?.version, + undefined, + ); + + const skewed = await checked('999'); + assert.equal(skewed.status, 409); + assert.equal(skewed.headers.get(DAEMON_HTTP_REFUSAL_HEADER), 'protocol-mismatch'); + const details = ((await skewed.json()) as RpcError).error?.data?.details; + assert.equal(details?.reason, 'remote_rpc_protocol_mismatch'); + assert.equal(details?.service, 'agent-device-daemon'); + assert.equal(details?.rpcProtocolVersion, DAEMON_RPC_PROTOCOL_VERSION); + assert.equal(details?.dispatched, 'no'); + + const missing = await checked(undefined); + assert.equal(missing.status, 409); + assert.equal(missing.headers.get(DAEMON_HTTP_REFUSAL_HEADER), 'protocol-missing'); + assert.equal(handlerCalls, 0); + } finally { + await closeLoopbackServer(server); + } +}); + +test('a matching checked call runs exactly like /rpc', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const commands: string[] = []; + const server = await createDaemonHttpServer({ + token: 'daemon-secret', + handleRequest: async (request) => { + commands.push(request.command); + return { ok: true, data: { echoed: request.command } }; + }, + env: process.env, + cwd: process.cwd(), + }); + try { + const endpoint = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const response = await fetch(`${endpoint}${DAEMON_HTTP_CHECKED_RPC_ROUTE}`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + authorization: 'Bearer daemon-secret', + [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: String(DAEMON_RPC_PROTOCOL_VERSION), + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 'req-2', + method: 'agent_device.command', + params: { command: 'devices', positionals: [] }, + }), + }); + assert.equal(response.status, 200); + const body = (await response.json()) as { result?: { data?: { echoed?: string } } }; + assert.equal(body.result?.data?.echoed, 'devices'); + assert.deepEqual(commands, ['devices']); + } finally { + await closeLoopbackServer(server); + } +}); + +test('a checked script recording needs the script-artifacts capability before dispatch', () => { + const written: { status?: number; headers: Record; body?: string } = { + headers: {}, + }; + const res = { + setHeader: (name: string, value: unknown) => { + written.headers[name] = value; + }, + set statusCode(value: number) { + written.status = value; + }, + end: (body: string) => { + written.body = body; + }, + } as unknown as http.ServerResponse; + const recording = { + token: '', + session: 'default', + command: 'open', + positionals: [], + meta: { scriptPublicationId: 'publication-1' }, + }; + assert.equal(refuseUnservedCheckedRequest(res, 'req-3', recording, ['script-artifacts']), false); + assert.equal(refuseUnservedCheckedRequest(res, 'req-3', { ...recording, meta: {} }, []), false); + + assert.equal(refuseUnservedCheckedRequest(res, 'req-3', recording, []), true); + assert.equal(written.status, 409); + assert.equal(written.headers[DAEMON_HTTP_REFUSAL_HEADER], 'script-artifacts'); + const details = (JSON.parse(written.body ?? '{}') as RpcError).error?.data?.details; + assert.equal(details?.reason, 'remote_script_artifacts_unsupported'); +}); diff --git a/packages/daemon/src/server/http/http-checked-rpc.ts b/packages/daemon/src/server/http/http-checked-rpc.ts new file mode 100644 index 0000000000..032a2dc8a4 --- /dev/null +++ b/packages/daemon/src/server/http/http-checked-rpc.ts @@ -0,0 +1,129 @@ +// The checked RPC route's own preconditions (ADR 0006): the RPC protocol the caller names, and the +// capability its request needs. Every refusal here is a 409 with a typed refusal header, answered +// before dispatch, so the caller learns that nothing ran. +import type http from 'node:http'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { isRecord } from '@agent-device/kernel/record'; +import { readVersion } from '@agent-device/host-kit/version'; +import { + checkedRpcProtocolRefusalError, + DAEMON_HTTP_REFUSAL_HEADER, + DAEMON_HTTP_REFUSALS, + DAEMON_HTTP_RPC_PROTOCOL_HEADER, + checkedRpcProtocolRefusal, + type DaemonHttpRefusal, +} from '@agent-device/contracts/daemon-http'; +import { assertScriptArtifactsCapability } from '@agent-device/daemon-contracts/daemon-resolution'; +import type { DaemonRequest } from '../../core/daemon-request.ts'; +import { + enforceDaemonToken, + resolveToken, + runHttpAuthHook, + type HttpAuthHook, +} from './http-authorization.ts'; +import { createRpcError, sendJson, type JsonRpcRequest } from './http-rpc-envelope.ts'; + +/** + * Answers a checked call whose RPC protocol header is absent or names another protocol, and reports + * whether it did. It reads only the stable JSON-RPC framing, never this build's params decoding, so + * a caller on any protocol gets the refusal. It authenticates first, with the token and the auth hook, + * so an unauthenticated caller learns nothing about this daemon. + */ +export async function refuseCheckedRpcProtocol(params: { + req: http.IncomingMessage; + res: http.ServerResponse; + body: string; + authHook: HttpAuthHook | null; + expectedToken: string | undefined; +}): Promise { + const { req, res, body, authHook, expectedToken } = params; + const refusal = checkedRpcProtocolRefusal(req.headers[DAEMON_HTTP_RPC_PROTOCOL_HEADER]); + if (!refusal) return false; + const frame = readStableRpcFrame(body); + const token = resolveToken(frame.params, req.headers); + const tokenError = enforceDaemonToken(token, expectedToken); + if (tokenError) { + sendJson( + res, + createRpcError(frame.rpcRequest.id ?? null, -32000, tokenError.message, tokenError), + 401, + ); + return true; + } + const authResult = await runHttpAuthHook(authHook, { + headers: req.headers, + rpcRequest: frame.rpcRequest, + daemonRequest: { + token, + session: 'default', + command: typeof frame.params.command === 'string' ? frame.params.command : '', + positionals: [], + }, + }); + if (!authResult.ok) { + sendJson(res, authResult.response, authResult.statusCode); + return true; + } + sendCheckedRpcRefusal( + res, + frame.rpcRequest.id ?? null, + refusal, + checkedRpcProtocolRefusalError(refusal, { + service: 'agent-device-daemon', + version: readVersion(), + }), + ); + return true; +} + +/** + * Answers an admitted checked call that this daemon cannot serve, and reports whether it did. A call + * that records a session script (`meta.scriptPublicationId`) needs the `script-artifacts` capability, + * so the requirement comes from the request itself and no header can remove it. + */ +export function refuseUnservedCheckedRequest( + res: http.ServerResponse, + rpcId: JsonRpcRequest['id'], + daemonRequest: DaemonRequest, + capabilities: readonly string[], +): boolean { + if (!daemonRequest.meta?.scriptPublicationId) return false; + try { + assertScriptArtifactsCapability(capabilities); + return false; + } catch (error) { + sendCheckedRpcRefusal(res, rpcId ?? null, DAEMON_HTTP_REFUSALS.scriptArtifacts, error); + return true; + } +} + +function sendCheckedRpcRefusal( + res: http.ServerResponse, + rpcId: JsonRpcRequest['id'], + refusal: DaemonHttpRefusal, + error: unknown, +): void { + const normalized = normalizeError( + error instanceof AppError ? error : new AppError('COMMAND_FAILED', String(error)), + ); + res.setHeader(DAEMON_HTTP_REFUSAL_HEADER, refusal); + sendJson(res, createRpcError(rpcId ?? null, -32001, normalized.message, normalized), 409); +} + +/** The JSON-RPC framing every protocol shares: the call id, its method, and its params object. */ +function readStableRpcFrame(body: string): { + rpcRequest: JsonRpcRequest; + params: Record; +} { + let parsed: unknown; + try { + parsed = JSON.parse(body); + } catch { + parsed = undefined; + } + const frame = isRecord(parsed) ? parsed : {}; + const id = typeof frame.id === 'string' || typeof frame.id === 'number' ? frame.id : null; + const method = typeof frame.method === 'string' ? frame.method : ''; + const params = isRecord(frame.params) ? frame.params : {}; + return { rpcRequest: { jsonrpc: '2.0', id, method, params }, params }; +} diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 47d031d661..392c5397d4 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -32,6 +32,8 @@ import { buildDaemonHealthPayload, normalizeDaemonPublicOrigin, nodeHttpRequestUrl, + DAEMON_HTTP_CHECKED_RPC_CAPABILITY, + DAEMON_HTTP_CHECKED_RPC_ROUTE, DAEMON_HTTP_NETWORK_ACCESS_HEADER, DAEMON_REQUEST_MAX_BYTES, } from '@agent-device/contracts/daemon-http'; @@ -81,8 +83,11 @@ import { type TenantTrustDecision, } from './tenant-trust.ts'; import { refuseStaleDaemonInstance } from './http-instance-precondition.ts'; +import { refuseCheckedRpcProtocol, refuseUnservedCheckedRequest } from './http-checked-rpc.ts'; const MAX_HTTP_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; +/** What this daemon serves over HTTP beyond the base RPC contract, as `/health` advertises it. */ +const DAEMON_HTTP_CAPABILITIES = ['script-artifacts', DAEMON_HTTP_CHECKED_RPC_CAPABILITY]; export async function createDaemonHttpServer(options: { handleRequest: DaemonInvokeFn; @@ -143,7 +148,7 @@ export async function createDaemonHttpServer(options: { JSON.stringify( buildDaemonHealthPayload('agent-device-daemon', readVersion(), { instanceId, - capabilities: ['script-artifacts'], + capabilities: DAEMON_HTTP_CAPABILITIES, hostArch, leaseBackends, }), @@ -224,7 +229,8 @@ export async function createDaemonHttpServer(options: { return; } - if (req.method !== 'POST' || req.url !== '/rpc') { + const checked = req.url === DAEMON_HTTP_CHECKED_RPC_ROUTE; + if (req.method !== 'POST' || (req.url !== '/rpc' && !checked)) { res.statusCode = 404; res.end('Not found'); return; @@ -243,6 +249,7 @@ export async function createDaemonHttpServer(options: { expectedToken: token, instanceId, handleRequest, + checked, }).catch((error: unknown) => { sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); }); @@ -314,8 +321,15 @@ async function handleRpcRequest(params: { expectedToken: string | undefined; instanceId: string; handleRequest: DaemonInvokeFn; + /** The call came on the checked route, so its protocol and capability are checked before dispatch. */ + checked: boolean; }): Promise { - const { req, res, body, authHook, expectedToken, instanceId, handleRequest } = params; + const { req, res, body, authHook, expectedToken, instanceId, handleRequest, checked } = params; + // Ahead of the envelope checks: a caller on another protocol is told so before this build reads + // anything its own protocol defines, such as the method vocabulary. + if (checked && (await refuseCheckedRpcProtocol({ req, res, body, authHook, expectedToken }))) { + return; + } const validated = validateRpcRequestEnvelope(body); if (!validated.ok) { sendRpcRefusal(res, validated.refusal); @@ -345,6 +359,17 @@ async function handleRpcRequest(params: { } return; } + if ( + checked && + refuseUnservedCheckedRequest( + res, + validated.rpcRequest.id ?? null, + admission.daemonRequest, + DAEMON_HTTP_CAPABILITIES, + ) + ) { + return; + } lifetime.watchForClientDisconnect(); await invokeAdmittedRpcRequest({ diff --git a/packages/proxy/src/daemon-proxy-checked-rpc.test.ts b/packages/proxy/src/daemon-proxy-checked-rpc.test.ts new file mode 100644 index 0000000000..f271592d2f --- /dev/null +++ b/packages/proxy/src/daemon-proxy-checked-rpc.test.ts @@ -0,0 +1,158 @@ +import { expect, test } from 'vitest'; +import { + DAEMON_HTTP_CHECKED_RPC_CAPABILITY, + DAEMON_HTTP_REFUSAL_HEADER, + DAEMON_HTTP_RPC_PROTOCOL_HEADER, + DAEMON_RPC_PROTOCOL_VERSION, +} from '@agent-device/contracts/daemon-http'; +import { createDaemonProxy, type DaemonProxyUpstreamFetch } from './daemon-proxy.ts'; + +const PROXY_ORIGIN = 'https://gateway.example.test'; +const PROTOCOL = String(DAEMON_RPC_PROTOCOL_VERSION); + +function recordingUpstream(respond: (request: Request) => Response | Promise) { + const requests: Request[] = []; + const fetch: DaemonProxyUpstreamFetch = async (request) => { + requests.push(request); + return await respond(request); + }; + return { requests, fetch }; +} + +function tokenProxy(upstreamFetch: DaemonProxyUpstreamFetch) { + return createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + upstreamFetch, + }); +} + +function checkedRequest( + body: unknown, + headers: Record = { [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: PROTOCOL }, + route = 'rpc/checked', +): Request { + return new Request(`${PROXY_ORIGIN}/agent-device/${route}`, { + method: 'POST', + headers: { + authorization: 'Bearer client-secret', + 'content-type': 'application/json', + ...headers, + }, + body: JSON.stringify(body), + }); +} + +const COMMAND = { jsonrpc: '2.0', id: 1, method: 'agent_device.command', params: {} }; + +test('a checked call reaches the upstream checked route with the same rewriting as /rpc', async () => { + const upstream = recordingUpstream(async (request) => + Response.json({ jsonrpc: '2.0', id: 1, echo: await request.json() }), + ); + const response = await tokenProxy(upstream.fetch).handle(checkedRequest(COMMAND)); + + expect(response.status).toBe(200); + const [forwarded] = upstream.requests; + expect(forwarded?.url).toBe('http://daemon.internal:4310/rpc/checked'); + expect(forwarded?.headers.get('authorization')).toBe('Bearer daemon-secret'); + expect(forwarded?.headers.get(DAEMON_HTTP_RPC_PROTOCOL_HEADER)).toBe(PROTOCOL); + expect(forwarded?.headers.get('x-agent-device-network-access')).toBe('public-only'); + const payload = (await response.json()) as { echo: { params: { token: string } } }; + expect(payload.echo.params.token).toBe('daemon-secret'); +}); + +test.each([ + ['protocol-mismatch', { [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: '999' }], + ['protocol-missing', {}], +])( + 'an authenticated checked call with %s is refused by the proxy before forwarding', + async (refusal, headers) => { + const upstream = recordingUpstream(() => Response.json({})); + const response = await tokenProxy(upstream.fetch).handle(checkedRequest(COMMAND, headers)); + + expect(response.status).toBe(409); + expect(response.headers.get(DAEMON_HTTP_REFUSAL_HEADER)).toBe(refusal); + const body = (await response.json()) as { + error: { data: { details: Record } }; + }; + expect(body.error.data.details).toMatchObject({ + service: 'agent-device-proxy', + rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, + dispatched: 'no', + }); + expect(upstream.requests).toHaveLength(0); + }, +); + +test('an unauthenticated checked call learns nothing about the proxy protocol', async () => { + const upstream = recordingUpstream(() => Response.json({})); + const response = await tokenProxy(upstream.fetch).handle( + checkedRequest(COMMAND, { + [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: '999', + authorization: 'Bearer wrong', + }), + ); + + expect(response.status).toBe(401); + expect(response.headers.get(DAEMON_HTTP_REFUSAL_HEADER)).toBeNull(); + expect(upstream.requests).toHaveLength(0); +}); + +test.each(['rpc', 'rpc/checked'])( + 'a tenant-restricted method is refused on /%s before the daemon', + async (route) => { + const upstream = recordingUpstream(() => Response.json({})); + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + authenticate: () => ({ tenantId: 'tenant-a' }), + upstreamFetch: upstream.fetch, + }); + const response = await proxy.handle( + checkedRequest( + { jsonrpc: '2.0', id: 2, method: 'agent_device.install_from_source', params: {} }, + { [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: PROTOCOL }, + route, + ), + ); + + expect(response.status).toBe(401); + expect(upstream.requests).toHaveLength(0); + }, +); + +test('the upstream protocol refusal reaches the client marked as the daemon behind the proxy', async () => { + const upstream = recordingUpstream(() => + Response.json( + { jsonrpc: '2.0', id: 1, error: { code: -32001, message: 'skew' } }, + { status: 409, headers: { [DAEMON_HTTP_REFUSAL_HEADER]: 'protocol-mismatch' } }, + ), + ); + const response = await tokenProxy(upstream.fetch).handle(checkedRequest(COMMAND)); + + expect(response.status).toBe(409); + expect(response.headers.get(DAEMON_HTTP_REFUSAL_HEADER)).toBe('upstream-protocol-mismatch'); +}); + +test('a refusal header the upstream sets on /rpc never reaches the client', async () => { + const upstream = recordingUpstream(() => + Response.json( + {}, + { status: 409, headers: { [DAEMON_HTTP_REFUSAL_HEADER]: 'script-artifacts' } }, + ), + ); + const response = await tokenProxy(upstream.fetch).handle(checkedRequest(COMMAND, {}, 'rpc')); + + expect(response.headers.get(DAEMON_HTTP_REFUSAL_HEADER)).toBeNull(); +}); + +test('proxy health advertises the checked route', async () => { + const upstream = recordingUpstream(() => Response.json({ ok: true })); + const response = await tokenProxy(upstream.fetch).handle( + new Request(`${PROXY_ORIGIN}/agent-device/health`), + ); + + const health = (await response.json()) as { capabilities: string[] }; + expect(health.capabilities).toEqual([DAEMON_HTTP_CHECKED_RPC_CAPABILITY]); +}); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 4710b7294b..3f9cc4520a 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -19,6 +19,14 @@ import { normalizeDaemonPublicOrigin, DAEMON_REQUEST_MAX_BYTES, DAEMON_INSTANCE_REASONS, + DAEMON_HTTP_CHECKED_RPC_CAPABILITY, + DAEMON_HTTP_CHECKED_RPC_ROUTE, + DAEMON_HTTP_REFUSAL_HEADER, + DAEMON_HTTP_REFUSALS, + DAEMON_HTTP_RPC_PROTOCOL_HEADER, + DAEMON_RPC_PROTOCOL_VERSION, + checkedRpcProtocolRefusal, + checkedRpcProtocolRefusalError, } from '@agent-device/contracts/daemon-http'; import { carriesUnbackedHostPathInstallSource, @@ -190,7 +198,7 @@ async function handleProxyRequest( return new Response(new TextEncoder().encode('Not found'), { status: 404 }); } - if (route !== '/rpc') return await handleDaemonRoute(request, route, options, instanceId); + if (!isRpcRoute(route)) return await handleDaemonRoute(request, route, options, instanceId); let rpcBody: string; try { @@ -222,13 +230,15 @@ async function handleDaemonRoute( if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } + const protocolRefusal = await refuseCheckedRpcProtocol(request, route, readJsonRpcId(rpcBody)); + if (protocolRefusal) return protocolRefusal; if (caller.tenantId && !isRouteWithinTenant(route, caller.tenantId)) { return Response.json( { ok: false, error: 'Session is outside this tenant', code: 'UNAUTHORIZED' }, { status: 401 }, ); } - if (caller.tenantId && route === '/rpc' && !isTenantStampedRpcMethod(rpcBody)) { + if (caller.tenantId && isRpcRoute(route) && !isTenantStampedRpcMethod(rpcBody)) { return tenantRpcMethodRefusedResponse(readJsonRpcId(rpcBody)); } @@ -331,6 +341,7 @@ async function proxyHealthResponse( upstream, instanceId, hostArch: await readHostCpuArch(), + capabilities: [DAEMON_HTTP_CHECKED_RPC_CAPABILITY], }), ); } @@ -422,9 +433,31 @@ function copyProxyResponseHeaders( if (value) headers.set(name, value); } if (!headers.has('x-request-id')) headers.set('x-request-id', resolveRequestId(request)); + const refusal = forwardedCheckedRpcRefusal(upstreamResponse, route); + if (refusal) headers.set(DAEMON_HTTP_REFUSAL_HEADER, refusal); return headers; } +/** + * The refusal header a checked call's 409 carries back through the proxy. A protocol refusal of the + * daemon behind the proxy says so, so the client names that daemon and not the proxy. Only the + * known values pass, and only on a 409 of the checked route. + */ +function forwardedCheckedRpcRefusal(upstreamResponse: Response, route: string): string | undefined { + if (route !== DAEMON_HTTP_CHECKED_RPC_ROUTE || upstreamResponse.status !== 409) return undefined; + switch (upstreamResponse.headers.get(DAEMON_HTTP_REFUSAL_HEADER)) { + case DAEMON_HTTP_REFUSALS.protocolMismatch: + case DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch: + return DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch; + case DAEMON_HTTP_REFUSALS.protocolMissing: + return DAEMON_HTTP_REFUSALS.protocolMissing; + case DAEMON_HTTP_REFUSALS.scriptArtifacts: + return DAEMON_HTTP_REFUSALS.scriptArtifacts; + default: + return undefined; + } +} + /** `content-length` stays off the preflight route because the proxy rewrites that body. */ function routeResponseHeaders(route: string): readonly string[] { if (route.startsWith('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/upload/direct/')) return FORWARDED_UPLOAD_CHUNK_RESPONSE_HEADERS; @@ -604,8 +637,13 @@ function resolveProxyRoute(requestUrl: string): string { return pathname; } +/** `/rpc` and the checked route share one admission: auth, tenant rules, credentials, stamping. */ +function isRpcRoute(route: string): boolean { + return route === '/rpc' || route === DAEMON_HTTP_CHECKED_RPC_ROUTE; +} + function isSupportedDaemonRoute(route: string, method: string): boolean { - if (route === '/rpc') return method === 'POST'; + if (isRpcRoute(route)) return method === 'POST'; if (isTransferRoute(route, method)) return true; if (isRequestDiagnosticsRoute(route)) return method === 'GET'; return false; @@ -672,10 +710,14 @@ function buildUpstreamHeaders( if (value?.trim()) headers.set(name, value); } if (tenantId) headers.set(DAEMON_HTTP_TENANT_HEADER, tenantId); - if (route === '/rpc' && !headers.has('content-type')) { + if (isRpcRoute(route) && !headers.has('content-type')) { headers.set('content-type', 'application/json'); } - if (route === '/rpc') { + if (route === DAEMON_HTTP_CHECKED_RPC_ROUTE) { + // The proxy admitted only its own protocol, so the daemon behind it checks that one again. + headers.set(DAEMON_HTTP_RPC_PROTOCOL_HEADER, String(DAEMON_RPC_PROTOCOL_VERSION)); + } + if (isRpcRoute(route)) { headers.set(DAEMON_HTTP_NETWORK_ACCESS_HEADER, DAEMON_HTTP_PUBLIC_NETWORK_ACCESS); for (const [name, value] of Object.entries( buildUpstreamInstancePreconditionHeaders(requestHeaders), @@ -697,7 +739,7 @@ function resolveUpstreamBody( tenantId: string | undefined, ): BodyInit | null { if (request.method === 'GET' || request.method === 'HEAD') return null; - if (route === '/rpc') return rewriteRpcParams(rpcBody ?? '', upstreamToken, tenantId); + if (isRpcRoute(route)) return rewriteRpcParams(rpcBody ?? '', upstreamToken, tenantId); return request.body; } @@ -811,7 +853,7 @@ function refuseStaleProxyInstance( rpcId: unknown, instanceId: string, ): Response | null { - if (route !== '/rpc') return null; + if (!isRpcRoute(route)) return null; const expectedInstanceId = request.headers.get(DAEMON_HTTP_INSTANCE_HEADER); if (expectedInstanceId === null || expectedInstanceId === instanceId) return null; return sendInstanceMismatch(rpcId); @@ -832,8 +874,33 @@ function sendInstanceMismatch(rpcId: unknown): Response { ); } +/** + * Refuses an authenticated checked call whose RPC protocol header is absent or names another + * protocol, before the proxy reads anything its own protocol defines or forwards a byte. + */ +async function refuseCheckedRpcProtocol( + request: Request, + route: string, + rpcId: unknown, +): Promise { + if (route !== DAEMON_HTTP_CHECKED_RPC_ROUTE) return null; + const refusal = checkedRpcProtocolRefusal(request.headers.get(DAEMON_HTTP_RPC_PROTOCOL_HEADER)); + if (!refusal) return null; + const { readVersion } = await import('@agent-device/host-kit/version'); + const error = normalizeError( + checkedRpcProtocolRefusalError(refusal, { + service: 'agent-device-proxy', + version: readVersion(), + }), + ); + return Response.json( + { jsonrpc: '2.0', id: rpcId, error: { code: -32001, message: error.message, data: error } }, + { status: 409, headers: { [DAEMON_HTTP_REFUSAL_HEADER]: refusal } }, + ); +} + function unauthorizedResponse(route: string, rpcId: unknown): Response { - if (route === '/rpc') { + if (isRpcRoute(route)) { return Response.json( { jsonrpc: '2.0', diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index faeae76e48..c137bf7ed4 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -195,7 +195,24 @@ "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER": "sha256:4564c2ce437d30d7a823e3326f4375c0750ba8d42bec22b4d02e8eb7f7db2973", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_INSTANCE_MISMATCH_HEADER": "sha256:a197edaf7f9fa94a6aab269856aa852da3204cc586f5fd23198689eb11908b61", "packages/daemon/src/server/http/http-instance-precondition.ts#refuseStaleDaemonInstance": "sha256:aab244a5946073ab494ca3c32613408107284ca9cf04c90983d9c7232be44289", - "packages/proxy/src/daemon-proxy.ts#refuseStaleProxyInstance": "sha256:a5d802a666fd04a5c41a40bf3c96cbb4d05d6b449e950cf52098836df01df6ea", + "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_CHECKED_RPC_ROUTE": "sha256:186cf62763a67a168d9b8148d9a06efe1de4c6755d83a05a6be85dae254435dd", + "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_CHECKED_RPC_CAPABILITY": "sha256:1a240ea04287b52e304bd845e8a0344649ed2e0f754c9ec80f8ea3fb10b971e7", + "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_RPC_PROTOCOL_HEADER": "sha256:7ce3188527c391c6f08f069d38438e70ad6ecdc257e44613b8f46055c5037766", + "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_REFUSAL_HEADER": "sha256:914b491b3f169de831e6758269a363f85778629286afc542646373c48d3145d3", + "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_REFUSALS": "sha256:202d236bc4b854fc992e7b5efb930e60215d253b49c870b87027a1255c6c5c18", + "packages/contracts/src/daemon-http.ts#DaemonHttpRefusal": "sha256:7900a17fee213477f4199f9bb38032f0ccf98e2b6ab79e8339b18399ab8ab35b", + "packages/contracts/src/daemon-http.ts#readDaemonRpcProtocolHeader": "sha256:755934987d438c05ab5e0fa16270723730a6dd56f73663335fa5d21935166f29", + "packages/contracts/src/daemon-http.ts#checkedRpcProtocolRefusal": "sha256:1015f40e770d069c83512f1333a8849f3d068d33820e1e480f4baa7106ca9d83", + "packages/contracts/src/daemon-http.ts#checkedRpcProtocolRefusalError": "sha256:a10e59ba9ad68af096b1a3fd6f8bd433d9a3e71dde0e930151ddbb434459d7ff", + "packages/daemon/src/server/http/http-checked-rpc.ts#refuseCheckedRpcProtocol": "sha256:87ebbeb38e45182ab1bce146ec7f45934c4569fcdb4872111ff05d0b772e6c7e", + "packages/daemon/src/server/http/http-checked-rpc.ts#refuseUnservedCheckedRequest": "sha256:27693cf9bd251e8af0e725a394688b6b141755be8dee29b828640d21a4b598fa", + "packages/daemon/src/server/http/http-checked-rpc.ts#sendCheckedRpcRefusal": "sha256:0b5c6247382aa05a01fb6b6ac1a669008d3bbc46b6999f23aab58b968abd3146", + "packages/daemon/src/server/http/http-checked-rpc.ts#readStableRpcFrame": "sha256:41492bb873e3c3825c1e75e6247105271bbe6691c2a478211f6cf3690c23c3e6", + "packages/daemon/src/server/http/http-server.ts#DAEMON_HTTP_CAPABILITIES": "sha256:bac67f03945b928de4fece3a5e02386ebba9b7b957b1107f76c84bc8ca574f94", + "packages/proxy/src/daemon-proxy.ts#isRpcRoute": "sha256:1bf3b68f6bc855bd87ee7c0bbdef467c3c76232238885ae6c67bcf245ce9b846", + "packages/proxy/src/daemon-proxy.ts#refuseCheckedRpcProtocol": "sha256:251a3dd674dbaea3fc40886ee3040ffbe50ff6b49ba38570e9f82d9b2e12d7b4", + "packages/proxy/src/daemon-proxy.ts#forwardedCheckedRpcRefusal": "sha256:ccb68925299f664ab18fff97b021c10b9a154a60a72055874868a24dad989399", + "packages/proxy/src/daemon-proxy.ts#refuseStaleProxyInstance": "sha256:5c39c2b5a1b4bc897a2b01ac47c6856af47e787e8cc5798657f0ae24fd1c78e0", "packages/proxy/src/daemon-proxy.ts#sendInstanceMismatch": "sha256:a196304a18d0a37cb259d94dd67efeffe08afb6caf6a3461ab0870ef8c7bbda4", "packages/contracts/src/daemon-http.ts#buildDaemonInstanceMismatchRpcResponse": "sha256:24e50130bbd0c4a21dfc51005cabf118525b9121f918719a2c16f73fcfcfbcf9", "packages/proxy/src/daemon-proxy.ts#buildUpstreamInstancePreconditionHeaders": "sha256:9f5d76a1f761d65fabd7244fc67295fed5934a544e86a6455451ef8520cf1615", @@ -313,7 +330,7 @@ { "declaration": "packages/daemon/src/server/http/http-authorization.ts#authorizeAuxiliaryHttpRequest", "digest": "sha256:be2f3a9965bb6fe456ab8b1f0a696cf80ffcc8016262a4aee28dee25d18650d0", - "rationale": "#2198 context: adds one optional field to the value this DAEMON-INTERNAL gate hands its own route handlers \u2014 sessionNamespace, the caller's tenant plus whether the daemon partitioned that caller's session names. Nothing about it is serialized: no request header is read that was not read before, no response field is added, and a refusal keeps the same 401 {ok:false,error,code} REST body sendRestJsonError already sent. What it enables is a refusal DROPPED, never one added \u2014 an unattested (client-declared) tenant no longer has the : prefix rule applied to it, because scopeRequestSession never applied that prefix to its sessions either. A released peer that now gets 200 where it got 401 is getting the ndjson record it asked for and already parses. The route also passes its ingress signal to the authorizer, so a held auth hook stops at the same deadline or disconnect; the request, response and status framing are unchanged. An auth-hook or tenant-trust refusal answered after the hook now goes through the request owner's commit gate, so a deadline that passed first answers with its own typed expiry; refusal status and body shapes are unchanged." + "rationale": "#2198 context: adds one optional field to the value this DAEMON-INTERNAL gate hands its own route handlers — sessionNamespace, the caller's tenant plus whether the daemon partitioned that caller's session names. Nothing about it is serialized: no request header is read that was not read before, no response field is added, and a refusal keeps the same 401 {ok:false,error,code} REST body sendRestJsonError already sent. What it enables is a refusal DROPPED, never one added — an unattested (client-declared) tenant no longer has the : prefix rule applied to it, because scopeRequestSession never applied that prefix to its sessions either. A released peer that now gets 200 where it got 401 is getting the ndjson record it asked for and already parses. The route also passes its ingress signal to the authorizer, so a held auth hook stops at the same deadline or disconnect; the request, response and status framing are unchanged. An auth-hook or tenant-trust refusal answered after the hook now goes through the request owner's commit gate, so a deadline that passed first answers with its own typed expiry; refusal status and body shapes are unchanged." }, { "declaration": "packages/daemon/src/server/request-diagnostics-http.ts#RequestDiagnosticsHttpAuthorizer", @@ -402,8 +419,8 @@ }, { "declaration": "packages/proxy/src/daemon-proxy.ts#refuseStaleProxyInstance", - "digest": "sha256:a5d802a666fd04a5c41a40bf3c96cbb4d05d6b449e950cf52098836df01df6ea", - "rationale": "Moved into @agent-device/proxy and rewritten over fetch Request/Response so the proxy can run on any transport. The 409 status, instance-mismatch header, JSON-RPC error body, and forwarded upstream precondition header are unchanged on the wire, so peers on both sides parse them as before." + "digest": "sha256:5c39c2b5a1b4bc897a2b01ac47c6856af47e787e8cc5798657f0ae24fd1c78e0", + "rationale": "Moved into @agent-device/proxy and rewritten over fetch Request/Response so the proxy can run on any transport. The 409 status, instance-mismatch header, JSON-RPC error body, and forwarded upstream precondition header are unchanged on the wire, so peers on both sides parse them as before. The checked RPC route (ADR 0006) shares the /rpc admission, so the same instance precondition now also applies to it; a released client never calls that route, and /rpc answers exactly as before." }, { "declaration": "packages/proxy/src/daemon-proxy.ts#sendInstanceMismatch", diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index 279ee27da5..3becea2d7b 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -49,6 +49,7 @@ const HTTP_RPC_ENVELOPE = 'packages/daemon/src/server/http/http-rpc-envelope.ts' const HTTP_RPC_METHODS = 'packages/daemon/src/server/http/http-rpc-methods.ts'; const HTTP_AUTHORIZATION = 'packages/daemon/src/server/http/http-authorization.ts'; const HTTP_INSTANCE_PRECONDITION = 'packages/daemon/src/server/http/http-instance-precondition.ts'; +const HTTP_CHECKED_RPC = 'packages/daemon/src/server/http/http-checked-rpc.ts'; const UPLOAD_HTTP = 'packages/daemon/src/server/upload-http.ts'; const ARTIFACT_HTTP = 'packages/daemon/src/server/downloadable-artifact-http.ts'; const REQUEST_DIAGNOSTICS_HTTP = 'packages/daemon/src/server/request-diagnostics-http.ts'; @@ -93,6 +94,29 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'buildDaemonInstanceMismatchRpcResponse', ), ...from(HTTP_INSTANCE_PRECONDITION, 'refuseStaleDaemonInstance'), + // The checked RPC route (ADR 0006): the server refuses protocol skew before dispatch, with a + // typed refusal header the client reads in place of a `/health` probe. + ...from( + DAEMON_HTTP, + 'DAEMON_HTTP_CHECKED_RPC_ROUTE', + 'DAEMON_HTTP_CHECKED_RPC_CAPABILITY', + 'DAEMON_HTTP_RPC_PROTOCOL_HEADER', + 'DAEMON_HTTP_REFUSAL_HEADER', + 'DAEMON_HTTP_REFUSALS', + 'DaemonHttpRefusal', + 'readDaemonRpcProtocolHeader', + 'checkedRpcProtocolRefusal', + 'checkedRpcProtocolRefusalError', + ), + ...from( + HTTP_CHECKED_RPC, + 'refuseCheckedRpcProtocol', + 'refuseUnservedCheckedRequest', + 'sendCheckedRpcRefusal', + 'readStableRpcFrame', + ), + ...from(HTTP_SERVER, 'DAEMON_HTTP_CAPABILITIES'), + ...from(DAEMON_PROXY, 'isRpcRoute', 'refuseCheckedRpcProtocol', 'forwardedCheckedRpcRefusal'), ...from( DAEMON_PROXY, 'refuseStaleProxyInstance', diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index fffb4d5baa..34c9e932ab 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -898,6 +898,8 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `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 another RPC protocol than the caller; `details.service`, `details.version` and `details.rpcProtocolVersion` name the side that refused. | | `REMOTE_SESSION_REQUIRED` | A command on a leased remote connection, or one that would lease one, named no session. | | `CONNECTION_DEVICE_CONFLICT` | The connection is bound to another device, or its lease was allocated by another device spec; `details.keys` names the disagreeing keys, and is present only for a device-spec mismatch. | | `CONNECTION_PLATFORM_CONFLICT` | The connection is bound to another platform, or the request names one its lease backend does not rent. | From af83bd5f923d754a5afe51446ac311f48cc44d5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 08:48:52 +0100 Subject: [PATCH 2/5] fix(daemon,proxy): give checked RPC the /rpc auth verdict before any protocol refusal The daemon now runs a checked call through the /rpc flow and answers the protocol refusal after the auth hook, tenant-trust and token gates, with the same inputs. A call this build cannot decode is refused with no version. The proxy authenticates, then checks the protocol, then the envelope. Refusal errors are built by their owners; contracts keep data, so daemon-http.ts gains no eager kernel edge. The unreachable script-artifacts refusal is gone: every checked-rpc daemon serves script artifacts. checked-rpc joins DAEMON_CAPABILITIES. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0006-daemon-rpc-protocol-version.md | 46 ++-- packages/contracts/src/daemon-http.ts | 62 ++--- .../daemon-contracts/src/daemon-resolution.ts | 4 +- .../src/server/http/http-checked-rpc.test.ts | 234 +++++++++++------- .../src/server/http/http-checked-rpc.ts | 152 ++++-------- .../daemon/src/server/http/http-server.ts | 55 ++-- packages/proxy/src/checked-rpc-admission.ts | 72 ++++++ .../src/daemon-proxy-checked-rpc.test.ts | 26 ++ packages/proxy/src/daemon-proxy.ts | 70 ++---- test/wire-compat/ledger.json | 26 +- test/wire-compat/surface.ts | 17 +- website/docs/docs/error-reasons.md | 2 +- 12 files changed, 397 insertions(+), 369 deletions(-) create mode 100644 packages/proxy/src/checked-rpc-admission.ts diff --git a/docs/adr/0006-daemon-rpc-protocol-version.md b/docs/adr/0006-daemon-rpc-protocol-version.md index b61f796c19..45f5710ef1 100644 --- a/docs/adr/0006-daemon-rpc-protocol-version.md +++ b/docs/adr/0006-daemon-rpc-protocol-version.md @@ -7,8 +7,7 @@ Accepted ## Rules at a glance - Before remote JSON-RPC requests, compare the daemon's `rpcProtocolVersion` from `/health`, or send them on the checked route, where the server makes that comparison. -- The checked route refuses every precondition after authentication and before dispatch, with HTTP 409 and a typed `x-agent-device-refusal` header. -- A client uses the checked route only when its connection opts in. It never resends a checked call and never falls back to `/rpc` after one. +- The checked route reaches its authentication verdict exactly as `/rpc` does, then refuses protocol skew before dispatch, with HTTP 409 and a typed `x-agent-device-refusal` header. - Package `version` is diagnostic only and must not be used as a compatibility gate. - Allow a missing `rpcProtocolVersion` unless a later security or protocol decision explicitly retires legacy compatibility. - A persistent client may cache a successful probe if `/health` advertises an instance ID for the daemon endpoint and, for a proxy, for its upstream daemon. @@ -53,29 +52,6 @@ A peer that advertises an instance ID must continue to honor the conditional RPC The reason is that older clients may hold a cached identity across a restart. Such clients must receive a pre-dispatch refusal before they retry a mutating command. -### Checked RPC - -`POST /rpc/checked` takes the same authentication, body, and answer as `/rpc`. -The client names its protocol in the mandatory `x-agent-device-rpc-protocol` header. -The daemon or proxy authenticates the caller first. -Then it compares that header with its own protocol, before it decodes anything that its own protocol defines. -A missing header or another protocol gets HTTP 409, `x-agent-device-refusal: protocol-missing` or `protocol-mismatch`, and a JSON-RPC error. -The error details name the refusing `service`, its `version`, and its `rpcProtocolVersion`, so the client can name who must upgrade. -A proxy admits `/rpc` and the checked route through one path: body limit, authentication, tenant method rules, credential rewriting, and public-only stamping. -A proxy checks its own protocol, then forwards to the daemon's checked route, which checks again. -The proxy marks a forwarded daemon protocol refusal as `upstream-protocol-mismatch`. -A call that records a session script (`scriptPublicationId`) needs the `script-artifacts` capability; the daemon reads that requirement from the request itself and refuses with `script-artifacts`. -`/health` advertises `checked-rpc` on each link that serves the route. - -The route, not a header, is what makes the check safe. -Released daemons and proxies answer an unknown route with 404 before dispatch, and they ignore unknown headers on `/rpc`. -A 404 is still not proof of non-dispatch, because a gateway can answer for a command that ran. -So a client does not discover the route. -The connection opts in with `daemonRpc: "checked"`, which `connect` accepts only when `/health` advertises `checked-rpc` on every link. -With the opt-in, a 404 is a typed failure with `dispatched: 'unknown'`, and the client does not resend. -Flows with remote side effects before the command, such as artifact uploads and lease beats, keep the `/health` probe and the instance headers. -A connect timeout before the socket connects is proof, inside the client, that nothing left; only then does the client run the `/health` recovery loop and send once. - `rpcProtocolVersion` changes only when an older client and newer daemon, or a newer client and older daemon, cannot safely communicate over the HTTP RPC boundary for existing commands. Increment it for incompatible changes to: @@ -95,6 +71,25 @@ Do not increment it for additive changes: If a single command needs finer-grained compatibility in the future, prefer command-level feature or capability metadata to an increment of the whole RPC protocol. This preference does not apply if the change also affects the shared transport contract. +### Checked RPC + +`POST /rpc/checked` takes the same authentication, body, and answer as `/rpc`. +The client names its protocol in the mandatory `x-agent-device-rpc-protocol` header. +A missing header or another protocol gets HTTP 409, `x-agent-device-refusal: protocol-missing` or `protocol-mismatch`, and a JSON-RPC error with `dispatched: 'no'`. + +The daemon runs a checked call through the `/rpc` flow: the same envelope, decoding, auth hook, tenant-trust and token gates, from the same inputs. +It answers the protocol refusal in place of any later answer, after those gates and before the instance precondition. +Only then do the error details name the refusing `service`, its `version`, and its `rpcProtocolVersion`. +A call that this build cannot decode cannot be authenticated the way `/rpc` would, so its refusal carries no version. +A proxy authenticates, then checks the protocol, then the envelope; its authentication does not decode the body. +A proxy admits `/rpc` and the checked route through one path: body limit, authentication, tenant method rules, credential rewriting, and public-only stamping. +It forwards a checked call to the daemon's checked route, which checks again, and marks a forwarded daemon protocol refusal as `upstream-protocol-mismatch`. +`/health` advertises `checked-rpc` on each link that serves the route. +A daemon that serves `checked-rpc` also serves `script-artifacts`, so the route needs no capability refusal. + +The route, not a header, is what makes the check safe. +Released daemons and proxies answer an unknown route with 404 before dispatch, and they ignore unknown headers on `/rpc`. + ## Alternatives Considered - **Gate by package version.** This is simple, but it rejects compatible version differences. @@ -104,7 +99,6 @@ This preference does not apply if the change also affects the shared transport c - **Negotiate full schemas.** This is more precise, but it is too much machinery for the current JSON-RPC boundary. - **Persist the `/health` answer in the client state directory (#5134).** It saves the probe across CLI processes, but it adds a local trust boundary and cache rules, and a rollback to a daemon that ignores instance headers would dispatch on a stale view. - **Send the protocol as a header on `/rpc`.** Released daemons ignore unknown headers and dispatch anyway. -- **Fall back to `/health` and `/rpc` after a 404 on the checked route.** A 404 can come after dispatch, so the fallback could run a command twice. ## Consequences diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 4b9a8e1b08..e204eb2050 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -1,5 +1,5 @@ import path from 'node:path'; -import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import type { ReasonTable } from '@agent-device/kernel/errors'; // The daemon HTTP wire vocabulary shared by the daemon server, the remote // proxy, and every client that talks to them: the base path, the tenant, lease @@ -166,59 +166,35 @@ export const DAEMON_HTTP_REFUSALS = { protocolMismatch: 'protocol-mismatch', /** A proxy forwards the protocol refusal of the daemon behind it. */ upstreamProtocolMismatch: 'upstream-protocol-mismatch', - /** The call records a session script, and the daemon cannot deliver one. */ - scriptArtifacts: 'script-artifacts', } as const; -export type DaemonHttpRefusal = (typeof DAEMON_HTTP_REFUSALS)[keyof typeof DAEMON_HTTP_REFUSALS]; +/** The refusals a checked call's own protocol header can earn. */ +export type CheckedRpcProtocolRefusal = + | typeof DAEMON_HTTP_REFUSALS.protocolMissing + | typeof DAEMON_HTTP_REFUSALS.protocolMismatch; -/** Why the checked RPC route refused a call. Each refusal comes before dispatch. */ +/** Why a checked RPC call failed. */ export const DAEMON_CHECKED_RPC_REASONS = { // The checked RPC call named no RPC protocol. An intermediary that strips request headers causes // this. protocolMissing: { reason: 'remote_rpc_protocol_missing' }, - // The daemon or proxy speaks another RPC protocol than the caller; `details.service`, - // `details.version` and `details.rpcProtocolVersion` name the side that refused. + // 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. protocolMismatch: { reason: 'remote_rpc_protocol_mismatch' }, } as const satisfies ReasonTable<'remote connection'>; -/** The RPC protocol a checked call names, or `undefined` when its header is absent or malformed. */ -export function readDaemonRpcProtocolHeader(value: unknown): number | undefined { - return typeof value === 'string' && /^[0-9]{1,9}$/.test(value) ? Number(value) : undefined; -} - -/** The protocol refusal of a checked call on this build, or `undefined` when its protocol matches. */ -export function checkedRpcProtocolRefusal(headerValue: unknown): DaemonHttpRefusal | undefined { - const protocol = readDaemonRpcProtocolHeader(headerValue); - if (protocol === undefined) return DAEMON_HTTP_REFUSALS.protocolMissing; - return protocol === DAEMON_RPC_PROTOCOL_VERSION - ? undefined - : DAEMON_HTTP_REFUSALS.protocolMismatch; -} - /** - * The error a daemon or proxy answers a refused checked call with. Its details name the refusing - * side in the `/health` vocabulary, so a client can name who must upgrade. + * The protocol refusal of a checked call on this build, or `undefined` when its protocol matches. A + * header that is absent or not a plain integer is `protocol-missing`. */ -export function checkedRpcProtocolRefusalError( - refusal: DaemonHttpRefusal, - side: Pick, -): AppError { - const missing = refusal === DAEMON_HTTP_REFUSALS.protocolMissing; - return new AppError( - 'COMMAND_FAILED', - missing - ? `Checked RPC requires the ${DAEMON_HTTP_RPC_PROTOCOL_HEADER} header` - : `The ${side.service} speaks RPC protocol ${DAEMON_RPC_PROTOCOL_VERSION}`, - { - reason: missing - ? DAEMON_CHECKED_RPC_REASONS.protocolMissing.reason - : DAEMON_CHECKED_RPC_REASONS.protocolMismatch.reason, - dispatched: 'no', - service: side.service, - version: side.version, - rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, - }, - ); +export function checkedRpcProtocolRefusal( + headerValue: unknown, +): CheckedRpcProtocolRefusal | undefined { + if (typeof headerValue !== 'string' || !/^[0-9]{1,9}$/.test(headerValue)) { + return DAEMON_HTTP_REFUSALS.protocolMissing; + } + return Number(headerValue) === DAEMON_RPC_PROTOCOL_VERSION + ? undefined + : DAEMON_HTTP_REFUSALS.protocolMismatch; } export function buildDaemonInstanceMismatchRpcResponse( diff --git a/packages/daemon-contracts/src/daemon-resolution.ts b/packages/daemon-contracts/src/daemon-resolution.ts index 2c7c359e4a..c343aaf6ba 100644 --- a/packages/daemon-contracts/src/daemon-resolution.ts +++ b/packages/daemon-contracts/src/daemon-resolution.ts @@ -321,7 +321,9 @@ export function resolveDaemonTransportPreference( } /** What a daemon can do beyond the base RPC contract, published in its `daemon.json`. */ -export const DAEMON_CAPABILITIES = ['quiesce', 'script-artifacts'] as const; +// `checked-rpc`: the daemon's HTTP server serves the checked RPC route (ADR 0006). Every daemon that +// serves it also serves `script-artifacts`. +export const DAEMON_CAPABILITIES = ['quiesce', 'script-artifacts', 'checked-rpc'] as const; export type DaemonCapability = (typeof DAEMON_CAPABILITIES)[number]; /** diff --git a/packages/daemon/src/server/http/http-checked-rpc.test.ts b/packages/daemon/src/server/http/http-checked-rpc.test.ts index 679d5952db..b16cfbdaa2 100644 --- a/packages/daemon/src/server/http/http-checked-rpc.test.ts +++ b/packages/daemon/src/server/http/http-checked-rpc.test.ts @@ -1,18 +1,20 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; -import type http from 'node:http'; +import fs from 'node:fs'; +import path from 'node:path'; import { createDaemonHttpServer } from './http-server.ts'; -import { refuseUnservedCheckedRequest } from './http-checked-rpc.ts'; import { DAEMON_HTTP_CHECKED_RPC_CAPABILITY, DAEMON_HTTP_CHECKED_RPC_ROUTE, DAEMON_HTTP_REFUSAL_HEADER, DAEMON_HTTP_RPC_PROTOCOL_HEADER, + DAEMON_HTTP_TENANT_HEADER, DAEMON_RPC_PROTOCOL_VERSION, } from '@agent-device/contracts/daemon-http'; import { closeLoopbackServer, listenOnLoopback, + mkdtempForTestSync, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; @@ -20,130 +22,172 @@ type RpcError = { error?: { data?: { code?: string; details?: Record } }; }; -test('the checked route authenticates, then refuses protocol skew before dispatch', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; +const PROTOCOL = String(DAEMON_RPC_PROTOCOL_VERSION); + +/** A daemon whose handler counts dispatches, optionally behind an auth hook module. */ +async function checkedDaemon(hookSource?: string) { let handlerCalls = 0; + const env: NodeJS.ProcessEnv = { ...process.env }; + if (hookSource) { + const hookPath = path.join(mkdtempForTestSync('checked-rpc-hook-'), 'hook.mjs'); + fs.writeFileSync(hookPath, hookSource); + env.AGENT_DEVICE_HTTP_AUTH_HOOK = hookPath; + } const server = await createDaemonHttpServer({ token: 'daemon-secret', - handleRequest: async () => { + handleRequest: async (request) => { handlerCalls += 1; - return { ok: true, data: {} }; + return { ok: true, data: { echoed: request.command } }; }, - env: process.env, + env, cwd: process.cwd(), }); + const endpoint = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const call = (options: { + protocol?: string; + token?: string; + headers?: Record; + body?: unknown; + route?: string; + }) => + fetch(`${endpoint}${options.route ?? DAEMON_HTTP_CHECKED_RPC_ROUTE}`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + authorization: `Bearer ${options.token ?? 'daemon-secret'}`, + ...(options.protocol === undefined + ? {} + : { [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: options.protocol }), + ...options.headers, + }, + body: + typeof options.body === 'string' + ? options.body + : JSON.stringify( + options.body ?? { + jsonrpc: '2.0', + id: 'req-1', + method: 'agent_device.command', + params: { command: 'devices', positionals: [], session: 'owned' }, + }, + ), + }); + return { + endpoint, + call, + handlerCalls: () => handlerCalls, + close: () => closeLoopbackServer(server), + }; +} + +async function details(response: Response): Promise | undefined> { + return ((await response.json()) as RpcError).error?.data?.details; +} + +test('the checked route runs the /rpc gates, then refuses protocol skew with the daemon side', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const daemon = await checkedDaemon(); try { - const endpoint = `http://127.0.0.1:${await listenOnLoopback(server)}`; - const health = (await (await fetch(`${endpoint}/health`)).json()) as { capabilities: string[] }; + const health = (await (await fetch(`${daemon.endpoint}/health`)).json()) as { + capabilities: string[]; + }; assert.ok(health.capabilities.includes(DAEMON_HTTP_CHECKED_RPC_CAPABILITY)); - const checked = (protocol: string | undefined, token = 'daemon-secret') => - fetch(`${endpoint}${DAEMON_HTTP_CHECKED_RPC_ROUTE}`, { - method: 'POST', - headers: { - 'content-type': 'application/json', - authorization: `Bearer ${token}`, - ...(protocol === undefined ? {} : { [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: protocol }), - }, - // A method this build does not know: the skew answer must not depend on decoding it. - body: JSON.stringify({ - jsonrpc: '2.0', - id: 'req-1', - method: 'agent_device.future_method', - params: { command: 'devices' }, - }), - }); - const unauthenticated = await checked('999', 'wrong-token'); + const unauthenticated = await daemon.call({ protocol: '999', token: 'wrong-token' }); assert.equal(unauthenticated.status, 401); assert.equal(unauthenticated.headers.get(DAEMON_HTTP_REFUSAL_HEADER), null); - assert.equal( - ((await unauthenticated.json()) as RpcError).error?.data?.details?.version, - undefined, - ); - const skewed = await checked('999'); + const skewed = await daemon.call({ protocol: '999' }); assert.equal(skewed.status, 409); assert.equal(skewed.headers.get(DAEMON_HTTP_REFUSAL_HEADER), 'protocol-mismatch'); - const details = ((await skewed.json()) as RpcError).error?.data?.details; - assert.equal(details?.reason, 'remote_rpc_protocol_mismatch'); - assert.equal(details?.service, 'agent-device-daemon'); - assert.equal(details?.rpcProtocolVersion, DAEMON_RPC_PROTOCOL_VERSION); - assert.equal(details?.dispatched, 'no'); + assert.deepEqual( + { ...(await details(skewed)), version: undefined }, + { + reason: 'remote_rpc_protocol_mismatch', + dispatched: 'no', + service: 'agent-device-daemon', + version: undefined, + rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, + }, + ); - const missing = await checked(undefined); + const missing = await daemon.call({}); assert.equal(missing.status, 409); assert.equal(missing.headers.get(DAEMON_HTTP_REFUSAL_HEADER), 'protocol-missing'); - assert.equal(handlerCalls, 0); + assert.equal(daemon.handlerCalls(), 0); } finally { - await closeLoopbackServer(server); + await daemon.close(); } }); -test('a matching checked call runs exactly like /rpc', async (t) => { +test('the auth hook sees the real request on the checked route and its denial wins over skew', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; - const commands: string[] = []; - const server = await createDaemonHttpServer({ - token: 'daemon-secret', - handleRequest: async (request) => { - commands.push(request.command); - return { ok: true, data: { echoed: request.command } }; - }, - env: process.env, - cwd: process.cwd(), - }); + // Denies every session but `default`, so a hook shown a stand-in request would admit the caller. + const daemon = await checkedDaemon( + "export default ({ daemonRequest }) => daemonRequest.session === 'default';\n", + ); try { - const endpoint = `http://127.0.0.1:${await listenOnLoopback(server)}`; - const response = await fetch(`${endpoint}${DAEMON_HTTP_CHECKED_RPC_ROUTE}`, { - method: 'POST', - headers: { - 'content-type': 'application/json', - authorization: 'Bearer daemon-secret', - [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: String(DAEMON_RPC_PROTOCOL_VERSION), - }, - body: JSON.stringify({ + const denied = await daemon.call({ protocol: '999' }); + assert.equal(denied.status, 401); + assert.equal(denied.headers.get(DAEMON_HTTP_REFUSAL_HEADER), null); + assert.equal((await details(denied))?.version, undefined); + } finally { + await daemon.close(); + } +}); + +test('an unattested tenant gets the /rpc tenant refusal on the checked route, not the version', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + // Admits the caller but attests no tenant, so a client-declared tenant fails tenant trust. + const daemon = await checkedDaemon('export default () => true;\n'); + try { + const refused = await daemon.call({ + protocol: '999', + headers: { [DAEMON_HTTP_TENANT_HEADER]: 'tenant-a' }, + body: { jsonrpc: '2.0', id: 'req-2', method: 'agent_device.command', - params: { command: 'devices', positionals: [] }, - }), + params: { command: 'devices', positionals: [], meta: { tenantId: 'tenant-a' } }, + }, }); - assert.equal(response.status, 200); - const body = (await response.json()) as { result?: { data?: { echoed?: string } } }; - assert.equal(body.result?.data?.echoed, 'devices'); - assert.deepEqual(commands, ['devices']); + assert.equal(refused.status, 401); + assert.equal(refused.headers.get(DAEMON_HTTP_REFUSAL_HEADER), null); } finally { - await closeLoopbackServer(server); + await daemon.close(); } }); -test('a checked script recording needs the script-artifacts capability before dispatch', () => { - const written: { status?: number; headers: Record; body?: string } = { - headers: {}, - }; - const res = { - setHeader: (name: string, value: unknown) => { - written.headers[name] = value; - }, - set statusCode(value: number) { - written.status = value; - }, - end: (body: string) => { - written.body = body; - }, - } as unknown as http.ServerResponse; - const recording = { - token: '', - session: 'default', - command: 'open', - positionals: [], - meta: { scriptPublicationId: 'publication-1' }, - }; - assert.equal(refuseUnservedCheckedRequest(res, 'req-3', recording, ['script-artifacts']), false); - assert.equal(refuseUnservedCheckedRequest(res, 'req-3', { ...recording, meta: {} }, []), false); +test('a skewed call this build cannot decode is refused without the daemon version', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const daemon = await checkedDaemon(); + try { + const refused = await daemon.call({ + protocol: '999', + body: { jsonrpc: '2.0', id: 'req-3', method: 'agent_device.future_method', params: {} }, + }); + assert.equal(refused.status, 409); + assert.equal(refused.headers.get(DAEMON_HTTP_REFUSAL_HEADER), 'protocol-mismatch'); + const refusal = await details(refused); + assert.equal(refusal?.reason, 'remote_rpc_protocol_mismatch'); + assert.equal(refusal?.version, undefined); + assert.equal(refusal?.service, undefined); + assert.equal(daemon.handlerCalls(), 0); + } finally { + await daemon.close(); + } +}); - assert.equal(refuseUnservedCheckedRequest(res, 'req-3', recording, []), true); - assert.equal(written.status, 409); - assert.equal(written.headers[DAEMON_HTTP_REFUSAL_HEADER], 'script-artifacts'); - const details = (JSON.parse(written.body ?? '{}') as RpcError).error?.data?.details; - assert.equal(details?.reason, 'remote_script_artifacts_unsupported'); +test('a matching checked call runs exactly like /rpc', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const daemon = await checkedDaemon(); + try { + const response = await daemon.call({ protocol: PROTOCOL }); + assert.equal(response.status, 200); + const body = (await response.json()) as { result?: { data?: { echoed?: string } } }; + assert.equal(body.result?.data?.echoed, 'devices'); + assert.equal(daemon.handlerCalls(), 1); + } finally { + await daemon.close(); + } }); diff --git a/packages/daemon/src/server/http/http-checked-rpc.ts b/packages/daemon/src/server/http/http-checked-rpc.ts index 032a2dc8a4..e4c4e26a56 100644 --- a/packages/daemon/src/server/http/http-checked-rpc.ts +++ b/packages/daemon/src/server/http/http-checked-rpc.ts @@ -1,129 +1,67 @@ -// The checked RPC route's own preconditions (ADR 0006): the RPC protocol the caller names, and the -// capability its request needs. Every refusal here is a 409 with a typed refusal header, answered -// before dispatch, so the caller learns that nothing ran. +// The checked RPC route's own precondition (ADR 0006): the RPC protocol the caller names. Its +// refusal is a 409 with a typed refusal header, answered before dispatch, so the caller learns that +// nothing ran. +// +// The route reaches its protocol verdict inside the `/rpc` flow: the same envelope, the same +// decoding, and the same auth hook, tenant-trust and token gates, with the same inputs. Only a caller +// that passed all of them learns this daemon's version. A call that this build cannot decode cannot +// be authenticated the way `/rpc` would, so its protocol refusal names no version at all. import type http from 'node:http'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; -import { isRecord } from '@agent-device/kernel/record'; import { readVersion } from '@agent-device/host-kit/version'; import { - checkedRpcProtocolRefusalError, + DAEMON_CHECKED_RPC_REASONS, DAEMON_HTTP_REFUSAL_HEADER, DAEMON_HTTP_REFUSALS, DAEMON_HTTP_RPC_PROTOCOL_HEADER, + DAEMON_RPC_PROTOCOL_VERSION, checkedRpcProtocolRefusal, - type DaemonHttpRefusal, + type CheckedRpcProtocolRefusal, } from '@agent-device/contracts/daemon-http'; -import { assertScriptArtifactsCapability } from '@agent-device/daemon-contracts/daemon-resolution'; -import type { DaemonRequest } from '../../core/daemon-request.ts'; -import { - enforceDaemonToken, - resolveToken, - runHttpAuthHook, - type HttpAuthHook, -} from './http-authorization.ts'; import { createRpcError, sendJson, type JsonRpcRequest } from './http-rpc-envelope.ts'; -/** - * Answers a checked call whose RPC protocol header is absent or names another protocol, and reports - * whether it did. It reads only the stable JSON-RPC framing, never this build's params decoding, so - * a caller on any protocol gets the refusal. It authenticates first, with the token and the auth hook, - * so an unauthenticated caller learns nothing about this daemon. - */ -export async function refuseCheckedRpcProtocol(params: { - req: http.IncomingMessage; - res: http.ServerResponse; - body: string; - authHook: HttpAuthHook | null; - expectedToken: string | undefined; -}): Promise { - const { req, res, body, authHook, expectedToken } = params; - const refusal = checkedRpcProtocolRefusal(req.headers[DAEMON_HTTP_RPC_PROTOCOL_HEADER]); - if (!refusal) return false; - const frame = readStableRpcFrame(body); - const token = resolveToken(frame.params, req.headers); - const tokenError = enforceDaemonToken(token, expectedToken); - if (tokenError) { - sendJson( - res, - createRpcError(frame.rpcRequest.id ?? null, -32000, tokenError.message, tokenError), - 401, - ); - return true; - } - const authResult = await runHttpAuthHook(authHook, { - headers: req.headers, - rpcRequest: frame.rpcRequest, - daemonRequest: { - token, - session: 'default', - command: typeof frame.params.command === 'string' ? frame.params.command : '', - positionals: [], - }, - }); - if (!authResult.ok) { - sendJson(res, authResult.response, authResult.statusCode); - return true; - } - sendCheckedRpcRefusal( - res, - frame.rpcRequest.id ?? null, - refusal, - checkedRpcProtocolRefusalError(refusal, { - service: 'agent-device-daemon', - version: readVersion(), - }), - ); - return true; +/** The protocol refusal a checked call has earned, or `undefined` on `/rpc` or a matching protocol. */ +export function readCheckedRpcProtocolRefusal( + req: http.IncomingMessage, + checked: boolean, +): CheckedRpcProtocolRefusal | undefined { + return checked + ? checkedRpcProtocolRefusal(req.headers[DAEMON_HTTP_RPC_PROTOCOL_HEADER]) + : undefined; } /** - * Answers an admitted checked call that this daemon cannot serve, and reports whether it did. A call - * that records a session script (`meta.scriptPublicationId`) needs the `script-artifacts` capability, - * so the requirement comes from the request itself and no header can remove it. + * Answers a protocol refusal. `authenticated` says whether the caller passed the `/rpc` gates: only + * then does the refusal name this daemon's service, version and protocol, so a client can name who + * must upgrade. Otherwise it carries the refusal and its reason alone. */ -export function refuseUnservedCheckedRequest( - res: http.ServerResponse, - rpcId: JsonRpcRequest['id'], - daemonRequest: DaemonRequest, - capabilities: readonly string[], -): boolean { - if (!daemonRequest.meta?.scriptPublicationId) return false; - try { - assertScriptArtifactsCapability(capabilities); - return false; - } catch (error) { - sendCheckedRpcRefusal(res, rpcId ?? null, DAEMON_HTTP_REFUSALS.scriptArtifacts, error); - return true; - } -} - -function sendCheckedRpcRefusal( +export function sendCheckedRpcProtocolRefusal( res: http.ServerResponse, rpcId: JsonRpcRequest['id'], - refusal: DaemonHttpRefusal, - error: unknown, + refusal: CheckedRpcProtocolRefusal, + authenticated: boolean, ): void { - const normalized = normalizeError( - error instanceof AppError ? error : new AppError('COMMAND_FAILED', String(error)), + const missing = refusal === DAEMON_HTTP_REFUSALS.protocolMissing; + const error = new AppError( + 'COMMAND_FAILED', + missing + ? `Checked RPC requires the ${DAEMON_HTTP_RPC_PROTOCOL_HEADER} header` + : 'The daemon speaks a different RPC protocol from the caller', + { + reason: missing + ? DAEMON_CHECKED_RPC_REASONS.protocolMissing.reason + : DAEMON_CHECKED_RPC_REASONS.protocolMismatch.reason, + dispatched: 'no', + ...(authenticated + ? { + service: 'agent-device-daemon', + version: readVersion(), + rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, + } + : {}), + }, ); + const normalized = normalizeError(error); res.setHeader(DAEMON_HTTP_REFUSAL_HEADER, refusal); sendJson(res, createRpcError(rpcId ?? null, -32001, normalized.message, normalized), 409); } - -/** The JSON-RPC framing every protocol shares: the call id, its method, and its params object. */ -function readStableRpcFrame(body: string): { - rpcRequest: JsonRpcRequest; - params: Record; -} { - let parsed: unknown; - try { - parsed = JSON.parse(body); - } catch { - parsed = undefined; - } - const frame = isRecord(parsed) ? parsed : {}; - const id = typeof frame.id === 'string' || typeof frame.id === 'number' ? frame.id : null; - const method = typeof frame.method === 'string' ? frame.method : ''; - const params = isRecord(frame.params) ? frame.params : {}; - return { rpcRequest: { jsonrpc: '2.0', id, method, params }, params }; -} diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 392c5397d4..3007bce609 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -35,6 +35,7 @@ import { DAEMON_HTTP_CHECKED_RPC_CAPABILITY, DAEMON_HTTP_CHECKED_RPC_ROUTE, DAEMON_HTTP_NETWORK_ACCESS_HEADER, + type CheckedRpcProtocolRefusal, DAEMON_REQUEST_MAX_BYTES, } from '@agent-device/contracts/daemon-http'; import { readVersion } from '@agent-device/host-kit/version'; @@ -83,7 +84,10 @@ import { type TenantTrustDecision, } from './tenant-trust.ts'; import { refuseStaleDaemonInstance } from './http-instance-precondition.ts'; -import { refuseCheckedRpcProtocol, refuseUnservedCheckedRequest } from './http-checked-rpc.ts'; +import { + readCheckedRpcProtocolRefusal, + sendCheckedRpcProtocolRefusal, +} from './http-checked-rpc.ts'; const MAX_HTTP_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; /** What this daemon serves over HTTP beyond the base RPC contract, as `/health` advertises it. */ @@ -321,18 +325,20 @@ async function handleRpcRequest(params: { expectedToken: string | undefined; instanceId: string; handleRequest: DaemonInvokeFn; - /** The call came on the checked route, so its protocol and capability are checked before dispatch. */ + /** The call came on the checked route, so its protocol is checked before dispatch. */ checked: boolean; }): Promise { const { req, res, body, authHook, expectedToken, instanceId, handleRequest, checked } = params; - // Ahead of the envelope checks: a caller on another protocol is told so before this build reads - // anything its own protocol defines, such as the method vocabulary. - if (checked && (await refuseCheckedRpcProtocol({ req, res, body, authHook, expectedToken }))) { - return; - } + // A checked call on another protocol takes the `/rpc` flow up to its auth gates, and is refused + // in place of any later answer. One this build cannot decode is refused without the version. + const protocolRefusal = readCheckedRpcProtocolRefusal(req, checked); const validated = validateRpcRequestEnvelope(body); if (!validated.ok) { - sendRpcRefusal(res, validated.refusal); + if (protocolRefusal) { + sendCheckedRpcProtocolRefusal(res, validated.refusal.response.id, protocolRefusal, false); + } else { + sendRpcRefusal(res, validated.refusal); + } return; } @@ -352,6 +358,7 @@ async function handleRpcRequest(params: { method: validated.method, params: validated.params, lifetime, + protocolRefusal, }); if (admission.outcome !== 'admitted') { if (admission.outcome === 'rejected') { @@ -359,17 +366,6 @@ async function handleRpcRequest(params: { } return; } - if ( - checked && - refuseUnservedCheckedRequest( - res, - validated.rpcRequest.id ?? null, - admission.daemonRequest, - DAEMON_HTTP_CAPABILITIES, - ) - ) { - return; - } lifetime.watchForClientDisconnect(); await invokeAdmittedRpcRequest({ @@ -384,7 +380,11 @@ 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 (protocolRefusal) { + sendCheckedRpcProtocolRefusal(res, validated.rpcRequest.id ?? null, protocolRefusal, false); + } else { + sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); + } } finally { lifetime.release(); } @@ -582,8 +582,8 @@ function beginRpcRequestLifetime(params: { // token is compared, and a stale daemon instance after it. /** - * The gate's answer for one validated call. `answered` is the stale-daemon-instance refusal, - * which writes its own 409 and mismatch header: nothing else may be written for the call. + * The gate's answer for one validated call. `answered` is a refusal that wrote its own 409 and + * header, the stale daemon instance or a checked call's protocol: nothing else may be written. */ type RpcRequestAdmission = | { outcome: 'admitted'; daemonRequest: DaemonRequest } @@ -607,11 +607,18 @@ async function admitRpcRequest(params: { method: string; params: Record; lifetime: RpcRequestLifetime; + /** A checked call's protocol refusal, answered once the caller passes the auth gates. */ + protocolRefusal: CheckedRpcProtocolRefusal | undefined; }): Promise { const { req, res, authHook, expectedToken, instanceId, rpcRequest, method, lifetime } = params; + const { protocolRefusal } = 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)) { + if (protocolRefusal) { + sendCheckedRpcProtocolRefusal(res, rpcRequest.id ?? null, protocolRefusal, false); + return { outcome: 'answered' }; + } return { outcome: 'rejected', refusal: rpcRefusal( @@ -651,6 +658,10 @@ async function admitRpcRequest(params: { if (tokenError) { return refused(rpcRequest, -32000, tokenError, 401); } + if (protocolRefusal) { + sendCheckedRpcProtocolRefusal(res, rpcRequest.id ?? null, protocolRefusal, true); + return { outcome: 'answered' }; + } if (refuseStaleDaemonInstance(req, res, rpcRequest.id ?? null, instanceId)) { return { outcome: 'answered' }; } diff --git a/packages/proxy/src/checked-rpc-admission.ts b/packages/proxy/src/checked-rpc-admission.ts new file mode 100644 index 0000000000..9a13c63f8f --- /dev/null +++ b/packages/proxy/src/checked-rpc-admission.ts @@ -0,0 +1,72 @@ +// The proxy's checked RPC admission (ADR 0006): its own protocol refusal, and the refusal header it +// carries back from the daemon behind it. Loaded only on the checked route. +import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { + checkedRpcProtocolRefusal, + DAEMON_CHECKED_RPC_REASONS, + DAEMON_HTTP_REFUSAL_HEADER, + DAEMON_HTTP_REFUSALS, + DAEMON_HTTP_RPC_PROTOCOL_HEADER, + DAEMON_RPC_PROTOCOL_VERSION, + type CheckedRpcProtocolRefusal, +} from '@agent-device/contracts/daemon-http'; + +/** + * Refuses an authenticated checked call whose RPC protocol header is absent or names another + * protocol. It runs after authentication and before the envelope check, the tenant method rules, + * and any forwarding. + */ +export async function refuseCheckedRpcProtocol( + request: Request, + rpcId: unknown, +): Promise { + const refusal = checkedRpcProtocolRefusal(request.headers.get(DAEMON_HTTP_RPC_PROTOCOL_HEADER)); + if (!refusal) return null; + const { readVersion } = await import('@agent-device/host-kit/version'); + const error = normalizeError(checkedRpcProtocolRefusalError(refusal, readVersion())); + return Response.json( + { jsonrpc: '2.0', id: rpcId, error: { code: -32001, message: error.message, data: error } }, + { status: 409, headers: { [DAEMON_HTTP_REFUSAL_HEADER]: refusal } }, + ); +} + +/** The refusal names this proxy in the `/health` vocabulary, so a client names who must upgrade. */ +function checkedRpcProtocolRefusalError( + refusal: CheckedRpcProtocolRefusal, + version: string, +): AppError { + const missing = refusal === DAEMON_HTTP_REFUSALS.protocolMissing; + return new AppError( + 'COMMAND_FAILED', + missing + ? `Checked RPC requires the ${DAEMON_HTTP_RPC_PROTOCOL_HEADER} header` + : 'The proxy speaks a different RPC protocol from the caller', + { + reason: missing + ? DAEMON_CHECKED_RPC_REASONS.protocolMissing.reason + : DAEMON_CHECKED_RPC_REASONS.protocolMismatch.reason, + dispatched: 'no', + service: 'agent-device-proxy', + version, + rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, + }, + ); +} + +/** + * The refusal header a checked call's 409 carries back through the proxy. A protocol refusal of the + * daemon behind the proxy says so, so the client names that daemon and not the proxy. Only the + * known values pass, and only on a 409 of the checked route. + */ +export function forwardedCheckedRpcRefusal(upstreamResponse: Response): string | undefined { + if (upstreamResponse.status !== 409) return undefined; + switch (upstreamResponse.headers.get(DAEMON_HTTP_REFUSAL_HEADER)) { + case DAEMON_HTTP_REFUSALS.protocolMismatch: + case DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch: + return DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch; + case DAEMON_HTTP_REFUSALS.protocolMissing: + return DAEMON_HTTP_REFUSALS.protocolMissing; + default: + return undefined; + } +} diff --git a/packages/proxy/src/daemon-proxy-checked-rpc.test.ts b/packages/proxy/src/daemon-proxy-checked-rpc.test.ts index f271592d2f..2261aa54d8 100644 --- a/packages/proxy/src/daemon-proxy-checked-rpc.test.ts +++ b/packages/proxy/src/daemon-proxy-checked-rpc.test.ts @@ -147,6 +147,32 @@ test('a refusal header the upstream sets on /rpc never reaches the client', asyn expect(response.headers.get(DAEMON_HTTP_REFUSAL_HEADER)).toBeNull(); }); +test.each([ + ['an unauthenticated caller', { authorization: 'Bearer wrong' }, 401, null], + ['a skewed caller', { [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: '999' }, 409, 'protocol-mismatch'], + ['a matching caller', { [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: PROTOCOL }, 400, null], +])( + 'a malformed checked body from %s is answered by auth, then protocol, then the envelope', + async (_name, headers, status, refusal) => { + const upstream = recordingUpstream(() => Response.json({})); + const response = await tokenProxy(upstream.fetch).handle( + new Request(`${PROXY_ORIGIN}/agent-device/rpc/checked`, { + method: 'POST', + headers: { + authorization: 'Bearer client-secret', + 'content-type': 'application/json', + ...headers, + }, + body: 'not json', + }), + ); + + expect(response.status).toBe(status); + expect(response.headers.get(DAEMON_HTTP_REFUSAL_HEADER)).toBe(refusal); + expect(upstream.requests).toHaveLength(0); + }, +); + test('proxy health advertises the checked route', async () => { const upstream = recordingUpstream(() => Response.json({ ok: true })); const response = await tokenProxy(upstream.fetch).handle( diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 3f9cc4520a..731d37f7db 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -22,11 +22,8 @@ import { DAEMON_HTTP_CHECKED_RPC_CAPABILITY, DAEMON_HTTP_CHECKED_RPC_ROUTE, DAEMON_HTTP_REFUSAL_HEADER, - DAEMON_HTTP_REFUSALS, DAEMON_HTTP_RPC_PROTOCOL_HEADER, DAEMON_RPC_PROTOCOL_VERSION, - checkedRpcProtocolRefusal, - checkedRpcProtocolRefusalError, } from '@agent-device/contracts/daemon-http'; import { carriesUnbackedHostPathInstallSource, @@ -210,7 +207,10 @@ async function handleProxyRequest( } catch (error) { return rpcErrorResponse(null, error); } - const envelopeRefusal = refuseInvalidRpcEnvelope(rpcBody); + // 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); @@ -230,8 +230,14 @@ async function handleDaemonRoute( if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } - const protocolRefusal = await refuseCheckedRpcProtocol(request, route, readJsonRpcId(rpcBody)); - if (protocolRefusal) return protocolRefusal; + 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 refusal = + (await refuseCheckedRpcProtocol(request, readJsonRpcId(rpcBody))) ?? + refuseInvalidRpcEnvelope(rpcBody ?? ''); + if (refusal) return refusal; + } if (caller.tenantId && !isRouteWithinTenant(route, caller.tenantId)) { return Response.json( { ok: false, error: 'Session is outside this tenant', code: 'UNAUTHORIZED' }, @@ -385,6 +391,11 @@ async function forwardProxyRequest(params: { ); const headers = copyProxyResponseHeaders(upstreamResponse, request, route); + if (route === DAEMON_HTTP_CHECKED_RPC_ROUTE) { + const { forwardedCheckedRpcRefusal } = await import('./checked-rpc-admission.ts'); + const refusal = forwardedCheckedRpcRefusal(upstreamResponse); + if (refusal) headers.set(DAEMON_HTTP_REFUSAL_HEADER, refusal); + } if (isUploadPreflightRoute(route)) { return await rewrittenUploadPreflightResponse({ request, @@ -433,31 +444,9 @@ function copyProxyResponseHeaders( if (value) headers.set(name, value); } if (!headers.has('x-request-id')) headers.set('x-request-id', resolveRequestId(request)); - const refusal = forwardedCheckedRpcRefusal(upstreamResponse, route); - if (refusal) headers.set(DAEMON_HTTP_REFUSAL_HEADER, refusal); return headers; } -/** - * The refusal header a checked call's 409 carries back through the proxy. A protocol refusal of the - * daemon behind the proxy says so, so the client names that daemon and not the proxy. Only the - * known values pass, and only on a 409 of the checked route. - */ -function forwardedCheckedRpcRefusal(upstreamResponse: Response, route: string): string | undefined { - if (route !== DAEMON_HTTP_CHECKED_RPC_ROUTE || upstreamResponse.status !== 409) return undefined; - switch (upstreamResponse.headers.get(DAEMON_HTTP_REFUSAL_HEADER)) { - case DAEMON_HTTP_REFUSALS.protocolMismatch: - case DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch: - return DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch; - case DAEMON_HTTP_REFUSALS.protocolMissing: - return DAEMON_HTTP_REFUSALS.protocolMissing; - case DAEMON_HTTP_REFUSALS.scriptArtifacts: - return DAEMON_HTTP_REFUSALS.scriptArtifacts; - default: - return undefined; - } -} - /** `content-length` stays off the preflight route because the proxy rewrites that body. */ function routeResponseHeaders(route: string): readonly string[] { if (route.startsWith('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/upload/direct/')) return FORWARDED_UPLOAD_CHUNK_RESPONSE_HEADERS; @@ -874,31 +863,6 @@ function sendInstanceMismatch(rpcId: unknown): Response { ); } -/** - * Refuses an authenticated checked call whose RPC protocol header is absent or names another - * protocol, before the proxy reads anything its own protocol defines or forwards a byte. - */ -async function refuseCheckedRpcProtocol( - request: Request, - route: string, - rpcId: unknown, -): Promise { - if (route !== DAEMON_HTTP_CHECKED_RPC_ROUTE) return null; - const refusal = checkedRpcProtocolRefusal(request.headers.get(DAEMON_HTTP_RPC_PROTOCOL_HEADER)); - if (!refusal) return null; - const { readVersion } = await import('@agent-device/host-kit/version'); - const error = normalizeError( - checkedRpcProtocolRefusalError(refusal, { - service: 'agent-device-proxy', - version: readVersion(), - }), - ); - return Response.json( - { jsonrpc: '2.0', id: rpcId, error: { code: -32001, message: error.message, data: error } }, - { status: 409, headers: { [DAEMON_HTTP_REFUSAL_HEADER]: refusal } }, - ); -} - function unauthorizedResponse(route: string, rpcId: unknown): Response { if (isRpcRoute(route)) { return Response.json( diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index c137bf7ed4..8778fda17e 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -199,19 +199,16 @@ "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_CHECKED_RPC_CAPABILITY": "sha256:1a240ea04287b52e304bd845e8a0344649ed2e0f754c9ec80f8ea3fb10b971e7", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_RPC_PROTOCOL_HEADER": "sha256:7ce3188527c391c6f08f069d38438e70ad6ecdc257e44613b8f46055c5037766", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_REFUSAL_HEADER": "sha256:914b491b3f169de831e6758269a363f85778629286afc542646373c48d3145d3", - "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_REFUSALS": "sha256:202d236bc4b854fc992e7b5efb930e60215d253b49c870b87027a1255c6c5c18", - "packages/contracts/src/daemon-http.ts#DaemonHttpRefusal": "sha256:7900a17fee213477f4199f9bb38032f0ccf98e2b6ab79e8339b18399ab8ab35b", - "packages/contracts/src/daemon-http.ts#readDaemonRpcProtocolHeader": "sha256:755934987d438c05ab5e0fa16270723730a6dd56f73663335fa5d21935166f29", - "packages/contracts/src/daemon-http.ts#checkedRpcProtocolRefusal": "sha256:1015f40e770d069c83512f1333a8849f3d068d33820e1e480f4baa7106ca9d83", - "packages/contracts/src/daemon-http.ts#checkedRpcProtocolRefusalError": "sha256:a10e59ba9ad68af096b1a3fd6f8bd433d9a3e71dde0e930151ddbb434459d7ff", - "packages/daemon/src/server/http/http-checked-rpc.ts#refuseCheckedRpcProtocol": "sha256:87ebbeb38e45182ab1bce146ec7f45934c4569fcdb4872111ff05d0b772e6c7e", - "packages/daemon/src/server/http/http-checked-rpc.ts#refuseUnservedCheckedRequest": "sha256:27693cf9bd251e8af0e725a394688b6b141755be8dee29b828640d21a4b598fa", - "packages/daemon/src/server/http/http-checked-rpc.ts#sendCheckedRpcRefusal": "sha256:0b5c6247382aa05a01fb6b6ac1a669008d3bbc46b6999f23aab58b968abd3146", - "packages/daemon/src/server/http/http-checked-rpc.ts#readStableRpcFrame": "sha256:41492bb873e3c3825c1e75e6247105271bbe6691c2a478211f6cf3690c23c3e6", + "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_REFUSALS": "sha256:99c46b14d91cc6f9eb6c55bfa96b8d89d33cc4087beac5313c5276ccdbecaf7d", + "packages/contracts/src/daemon-http.ts#checkedRpcProtocolRefusal": "sha256:a4efad68779436fa678c01e1c071ff45f52dcaa2e9902cd8be830937037174ef", + "packages/contracts/src/daemon-http.ts#CheckedRpcProtocolRefusal": "sha256:75b71253734f2a7e1bc34c42d4c9caca0c2eb25d809e5efb2ae0df58ae694202", + "packages/daemon/src/server/http/http-checked-rpc.ts#readCheckedRpcProtocolRefusal": "sha256:4c8924d8480a6af3acec96883d53636e33a199649bdd8ff63087dcf2ebaf4d29", + "packages/daemon/src/server/http/http-checked-rpc.ts#sendCheckedRpcProtocolRefusal": "sha256:d69a4d6b39cb747ca373bab42b753c14e00817d2cf6e6ca5529f2e232344b591", "packages/daemon/src/server/http/http-server.ts#DAEMON_HTTP_CAPABILITIES": "sha256:bac67f03945b928de4fece3a5e02386ebba9b7b957b1107f76c84bc8ca574f94", "packages/proxy/src/daemon-proxy.ts#isRpcRoute": "sha256:1bf3b68f6bc855bd87ee7c0bbdef467c3c76232238885ae6c67bcf245ce9b846", - "packages/proxy/src/daemon-proxy.ts#refuseCheckedRpcProtocol": "sha256:251a3dd674dbaea3fc40886ee3040ffbe50ff6b49ba38570e9f82d9b2e12d7b4", - "packages/proxy/src/daemon-proxy.ts#forwardedCheckedRpcRefusal": "sha256:ccb68925299f664ab18fff97b021c10b9a154a60a72055874868a24dad989399", + "packages/proxy/src/checked-rpc-admission.ts#refuseCheckedRpcProtocol": "sha256:96097745ef9845f473948e5b4a3a9fe872f034c4437ef08b722d9af69be21b00", + "packages/proxy/src/checked-rpc-admission.ts#checkedRpcProtocolRefusalError": "sha256:bb94640118109e802b5c73d943aec56e7aeff85f2cf88446bcd46c0e72d3c130", + "packages/proxy/src/checked-rpc-admission.ts#forwardedCheckedRpcRefusal": "sha256:be0fcba16fcee9e7592191325a6f0acb95316f9adbfa2f4a84c9a5240d62c691", "packages/proxy/src/daemon-proxy.ts#refuseStaleProxyInstance": "sha256:5c39c2b5a1b4bc897a2b01ac47c6856af47e787e8cc5798657f0ae24fd1c78e0", "packages/proxy/src/daemon-proxy.ts#sendInstanceMismatch": "sha256:a196304a18d0a37cb259d94dd67efeffe08afb6caf6a3461ab0870ef8c7bbda4", "packages/contracts/src/daemon-http.ts#buildDaemonInstanceMismatchRpcResponse": "sha256:24e50130bbd0c4a21dfc51005cabf118525b9121f918719a2c16f73fcfcfbcf9", @@ -232,7 +229,7 @@ "packages/proxy/src/daemon-proxy.ts#rewriteUploadDirectUrl": "sha256:b121db3ffb5a520b4b31810a2e28ff01c1a15d959514c9fbe2a61cd960d2af93", "packages/proxy/src/daemon-proxy.ts#rewriteUploadPreflightResponse": "sha256:332820b6f10e079632330c2c4996c4faa6f339e921f12f287bd83c9296df5ccd", "packages/proxy/src/daemon-proxy.ts#rewrittenUploadPreflightResponse": "sha256:21d633d947cd72f5008bcc886a8f3ecd4f778b594d0654b8d0741db8594003db", - "packages/daemon-contracts/src/daemon-resolution.ts#DAEMON_CAPABILITIES": "sha256:3478986d0e7b0e55e965c087a7b1dfd3cc018abdb372dba256cf90d27e63ed0b", + "packages/daemon-contracts/src/daemon-resolution.ts#DAEMON_CAPABILITIES": "sha256:4ff6eba594b923a1d8f46a5856c42132b7ecd3a63d40f26c42972e06cb5a0a04", "packages/daemon-contracts/src/daemon-resolution.ts#DaemonCapability": "sha256:2a5acf280a72e3d54c5ad7b52aece3ced37a30e4e721ef106a98e3bbd18ddbc3", "packages/daemon-contracts/src/daemon-resolution.ts#readDaemonCapabilities": "sha256:e410d36be74d307f7e5d8ddae63af5aae77f8eef77951ce9eeb7724f2fefae88", "packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts": "sha256:ba600575e06995bc903c107477b23f7853e920751452a50a9734fab6677326bf", @@ -676,6 +673,11 @@ "declaration": "packages/kernel/src/contracts.ts#DaemonInstallSource", "digest": "sha256:adfde90c81de72009bf0e092b95fcb41cece2ecd44e936dcb1f6beb220287f02", "rationale": "Removes the github-actions-artifact variant. A new client never sends it. A released client that sends it to a new daemon gets a normal INVALID_ARGS error (source.kind must be \"url\"), not a misread payload. No local daemon ever materialized it: it always failed with UNSUPPORTED_OPERATION. The url and path variants are unchanged." + }, + { + "declaration": "packages/daemon-contracts/src/daemon-resolution.ts#DAEMON_CAPABILITIES", + "digest": "sha256:4ff6eba594b923a1d8f46a5856c42132b7ecd3a63d40f26c42972e06cb5a0a04", + "rationale": "Adds the checked-rpc capability (ADR 0006). readDaemonCapabilities filters to known names, so a released client drops it, and a released daemon never lists it; a client treats an absent capability as cannot-do. The existing quiesce and script-artifacts entries are unchanged." } ] } diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index 3becea2d7b..cb201adc66 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -61,6 +61,7 @@ const CLIENT_RPC = 'packages/daemon-client/src/daemon-client-rpc.ts'; const CLIENT_PROGRESS = 'packages/daemon-client/src/daemon-client-progress.ts'; const CLIENT_TRANSPORT = 'packages/daemon-client/src/daemon-client-transport.ts'; const DAEMON_PROXY = 'packages/proxy/src/daemon-proxy.ts'; +const PROXY_CHECKED_RPC = 'packages/proxy/src/checked-rpc-admission.ts'; const UPLOAD_CLIENT = 'packages/remote/src/upload-client.ts'; const REMOTE_ARTIFACTS = 'packages/remote/src/daemon-artifacts.ts'; const ARTIFACT_DOWNLOAD = 'packages/remote/src/artifact-download.ts'; @@ -103,20 +104,18 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'DAEMON_HTTP_RPC_PROTOCOL_HEADER', 'DAEMON_HTTP_REFUSAL_HEADER', 'DAEMON_HTTP_REFUSALS', - 'DaemonHttpRefusal', - 'readDaemonRpcProtocolHeader', + 'CheckedRpcProtocolRefusal', 'checkedRpcProtocolRefusal', - 'checkedRpcProtocolRefusalError', ), + ...from(HTTP_CHECKED_RPC, 'readCheckedRpcProtocolRefusal', 'sendCheckedRpcProtocolRefusal'), + ...from(HTTP_SERVER, 'DAEMON_HTTP_CAPABILITIES'), + ...from(DAEMON_PROXY, 'isRpcRoute'), ...from( - HTTP_CHECKED_RPC, + PROXY_CHECKED_RPC, 'refuseCheckedRpcProtocol', - 'refuseUnservedCheckedRequest', - 'sendCheckedRpcRefusal', - 'readStableRpcFrame', + 'checkedRpcProtocolRefusalError', + 'forwardedCheckedRpcRefusal', ), - ...from(HTTP_SERVER, 'DAEMON_HTTP_CAPABILITIES'), - ...from(DAEMON_PROXY, 'isRpcRoute', 'refuseCheckedRpcProtocol', 'forwardedCheckedRpcRefusal'), ...from( DAEMON_PROXY, 'refuseStaleProxyInstance', diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 34c9e932ab..2bfcc12e69 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -899,7 +899,7 @@ These reasons can come from more than one command. | --- | --- | | `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 another RPC protocol than the caller; `details.service`, `details.version` and `details.rpcProtocolVersion` name the side that refused. | +| `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. | | `REMOTE_SESSION_REQUIRED` | A command on a leased remote connection, or one that would lease one, named no session. | | `CONNECTION_DEVICE_CONFLICT` | The connection is bound to another device, or its lease was allocated by another device spec; `details.keys` names the disagreeing keys, and is present only for a device-spec mismatch. | | `CONNECTION_PLATFORM_CONFLICT` | The connection is bound to another platform, or the request names one its lease backend does not rent. | From 8efd3fb3dd170e69422861863b46ec702cc7aedd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 09:09:17 +0100 Subject: [PATCH 3/5] test(daemon): expect checked-rpc in the published daemon capabilities Co-Authored-By: Claude Opus 5.5 --- packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts b/packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts index 1d7b93476f..97fc5baf2b 100644 --- a/packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts +++ b/packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts @@ -231,7 +231,7 @@ test('an idle daemon accepts a quiesce, drains and releases its state directory' const published = JSON.parse(fs.readFileSync(paths.infoPath, 'utf8')) as { capabilities?: unknown; }; - expect(published.capabilities).toEqual(['quiesce', 'script-artifacts']); + expect(published.capabilities).toEqual(['quiesce', 'script-artifacts', 'checked-rpc']); expect(await daemon.quiesce()).toEqual({ ok: true, data: { outcome: 'draining' } }); From 7be2a52c4a7c4c63435a43b65b23ae340e5cae0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 10:16:40 +0100 Subject: [PATCH 4/5] fix(daemon,proxy): verify the credential first and answer checked refusals from local values - The daemon checks a checked call's transport credential, read from the headers or the JSON frame, before it compares the protocol or decodes the method, so a wrong credential always gets 401. - The protocol refusal comes only after the auth hook, tenant and token gates pass; every earlier failure, a throwing hook included, gets the ordinary /rpc rejection. A refused call never reserves its request id. - Refusals echo only a bounded id, and are built by one data-only builder in contracts. The proxy rebuilds an upstream protocol refusal from validated, bounded values and never copies its body or headers. - The proxy never follows a redirect on the checked route; custom transports must honor request.redirect. - Proxy README and remote-proxy docs name /rpc/checked, its prefixed form and the protocol header; the ADR states the new ordering. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0006-daemon-rpc-protocol-version.md | 7 +- packages/contracts/src/daemon-http.ts | 65 ++++++++- .../src/server/http/http-checked-rpc.test.ts | 102 ++++++++++++-- .../src/server/http/http-checked-rpc.ts | 103 +++++++++----- .../daemon/src/server/http/http-server.ts | 30 ++-- packages/proxy/README.md | 20 ++- packages/proxy/src/checked-rpc-admission.ts | 131 ++++++++++++------ .../src/daemon-proxy-checked-rpc.test.ts | 95 +++++++++++++ packages/proxy/src/daemon-proxy.ts | 17 ++- test/wire-compat/ledger.json | 18 ++- test/wire-compat/surface.ts | 20 ++- website/docs/docs/remote-proxy.md | 4 +- 12 files changed, 483 insertions(+), 129 deletions(-) diff --git a/docs/adr/0006-daemon-rpc-protocol-version.md b/docs/adr/0006-daemon-rpc-protocol-version.md index 45f5710ef1..fe98175677 100644 --- a/docs/adr/0006-daemon-rpc-protocol-version.md +++ b/docs/adr/0006-daemon-rpc-protocol-version.md @@ -80,8 +80,11 @@ A missing header or another protocol gets HTTP 409, `x-agent-device-refusal: pro The daemon runs a checked call through the `/rpc` flow: the same envelope, decoding, auth hook, tenant-trust and token gates, from the same inputs. It answers the protocol refusal in place of any later answer, after those gates and before the instance precondition. Only then do the error details name the refusing `service`, its `version`, and its `rpcProtocolVersion`. -A call that this build cannot decode cannot be authenticated the way `/rpc` would, so its refusal carries no version. -A proxy authenticates, then checks the protocol, then the envelope; its authentication does not decode the body. +A daemon checks the transport credential, from the headers or the JSON frame's `params.token`, before it compares the protocol or decodes the method, so a wrong credential always gets 401. +A checked call that fails before every auth gate passes, including a hook that throws, gets the ordinary `/rpc` rejection, never the protocol refusal; a refused call never reserves its request id. +A proxy authenticates, then checks the protocol, then the envelope; its default token check reads `params.token` from the body, and `authenticate` may receive a body that is not JSON. +Every refusal is built from local values: a bounded id (a short token or a safe integer, else `null`), the reason, and validated diagnostic values; a proxy never copies an upstream refusal's body or headers. +A proxy never follows a redirect on the checked route, and a custom upstream transport must not either. A proxy admits `/rpc` and the checked route through one path: body limit, authentication, tenant method rules, credential rewriting, and public-only stamping. It forwards a checked call to the daemon's checked route, which checks again, and marks a forwarded daemon protocol refusal as `upstream-protocol-mismatch`. `/health` advertises `checked-rpc` on each link that serves the route. diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index e204eb2050..48075b263e 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -173,7 +173,7 @@ export type CheckedRpcProtocolRefusal = | typeof DAEMON_HTTP_REFUSALS.protocolMismatch; /** Why a checked RPC call failed. */ -export const DAEMON_CHECKED_RPC_REASONS = { +const DAEMON_CHECKED_RPC_REASONS = { // The checked RPC call named no RPC protocol. An intermediary that strips request headers causes // this. protocolMissing: { reason: 'remote_rpc_protocol_missing' }, @@ -197,6 +197,69 @@ export function checkedRpcProtocolRefusal( : DAEMON_HTTP_REFUSALS.protocolMismatch; } +/** + * The JSON-RPC id a checked-route refusal echoes: a bounded correlation token or a safe integer. + * Anything else, such as an object, a URL or a long string, is answered as `null`. + */ +export function checkedRpcRefusalId(id: unknown): string | number | null { + if (typeof id === 'number') return Number.isSafeInteger(id) ? id : null; + return typeof id === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(id) ? id : null; +} + +/** The refusing side of a protocol refusal, named in the `/health` vocabulary. */ +export type CheckedRpcRefusalSide = Pick< + DaemonHealthPayload, + 'service' | 'version' | 'rpcProtocolVersion' +>; + +/** The refusing side a protocol refusal names, or `undefined` unless every value is bounded and valid. */ +export function readCheckedRpcRefusalSide(details: unknown): CheckedRpcRefusalSide | undefined { + if (!details || typeof details !== 'object') return undefined; + const { service, version, rpcProtocolVersion } = details as Record; + if (service !== 'agent-device-daemon' && service !== 'agent-device-proxy') return undefined; + if ( + typeof version !== 'string' || + !/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]{1,48})?$/.test(version) + ) { + return undefined; + } + if (typeof rpcProtocolVersion !== 'number' || !Number.isSafeInteger(rpcProtocolVersion)) { + return undefined; + } + return { service, version, rpcProtocolVersion }; +} + +/** + * The JSON-RPC body of a protocol refusal, built from local values only: the refusal's reason, + * `dispatched: 'no'`, a bounded id, and the refusing side when the caller passed authentication. + */ +export function buildCheckedRpcProtocolRefusal( + id: unknown, + refusal: CheckedRpcProtocolRefusal | typeof DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch, + side?: CheckedRpcRefusalSide, +) { + const missing = refusal === DAEMON_HTTP_REFUSALS.protocolMissing; + const message = missing + ? `Checked RPC requires the ${DAEMON_HTTP_RPC_PROTOCOL_HEADER} header` + : 'The remote speaks a different RPC protocol from the caller'; + const reason = missing + ? DAEMON_CHECKED_RPC_REASONS.protocolMissing.reason + : DAEMON_CHECKED_RPC_REASONS.protocolMismatch.reason; + return { + jsonrpc: '2.0' as const, + id: checkedRpcRefusalId(id), + error: { + code: -32001, + message, + data: { + code: 'COMMAND_FAILED', + message, + details: { reason, dispatched: 'no', ...side }, + }, + }, + }; +} + export function buildDaemonInstanceMismatchRpcResponse( id: Id, message: string, diff --git a/packages/daemon/src/server/http/http-checked-rpc.test.ts b/packages/daemon/src/server/http/http-checked-rpc.test.ts index b16cfbdaa2..7f83a5639a 100644 --- a/packages/daemon/src/server/http/http-checked-rpc.test.ts +++ b/packages/daemon/src/server/http/http-checked-rpc.test.ts @@ -158,26 +158,110 @@ test('an unattested tenant gets the /rpc tenant refusal on the checked route, no } }); -test('a skewed call this build cannot decode is refused without the daemon version', async (t) => { +test('a wrong credential on the checked route gets 401 before the protocol or method is read', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const daemon = await checkedDaemon(); try { - const refused = await daemon.call({ + for (const body of [ + { jsonrpc: '2.0', id: 'req-3', method: 'agent_device.future_method', params: {} }, + { jsonrpc: '2.0', id: 'req-4', method: 'agent_device.command', params: {} }, + 'not json', + ]) { + const refused = await daemon.call({ protocol: '999', token: 'wrong-token', body }); + assert.equal(refused.status, 401); + assert.equal(refused.headers.get(DAEMON_HTTP_REFUSAL_HEADER), null); + } + } finally { + await daemon.close(); + } +}); + +test('a skewed call that fails before the auth hook passes gets the ordinary rejection, never the protocol 409', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const daemon = await checkedDaemon(); + try { + const undecodable = await daemon.call({ protocol: '999', - body: { jsonrpc: '2.0', id: 'req-3', method: 'agent_device.future_method', params: {} }, + body: { jsonrpc: '2.0', id: 'req-5', method: 'agent_device.future_method', params: {} }, }); - assert.equal(refused.status, 409); - assert.equal(refused.headers.get(DAEMON_HTTP_REFUSAL_HEADER), 'protocol-mismatch'); - const refusal = await details(refused); - assert.equal(refusal?.reason, 'remote_rpc_protocol_mismatch'); - assert.equal(refusal?.version, undefined); - assert.equal(refusal?.service, undefined); + assert.equal(undecodable.status, 404); + assert.equal(undecodable.headers.get(DAEMON_HTTP_REFUSAL_HEADER), null); + const noCommand = await daemon.call({ + protocol: '999', + body: { jsonrpc: '2.0', id: 'req-6', method: 'agent_device.command', params: {} }, + }); + assert.equal(noCommand.status, 400); + assert.equal(noCommand.headers.get(DAEMON_HTTP_REFUSAL_HEADER), null); assert.equal(daemon.handlerCalls(), 0); } finally { await daemon.close(); } }); +test('an auth hook that throws on a skewed checked call never yields the protocol 409', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const daemon = await checkedDaemon("export default () => { throw new Error('hook down'); };\n"); + try { + const refused = await daemon.call({ protocol: '999' }); + assert.notEqual(refused.status, 409); + assert.equal(refused.headers.get(DAEMON_HTTP_REFUSAL_HEADER), null); + } finally { + await daemon.close(); + } +}); + +test('a protocol refusal echoes only a bounded id', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const daemon = await checkedDaemon(); + try { + const refusalId = async (id: unknown) => { + const response = await daemon.call({ + protocol: '999', + body: { + jsonrpc: '2.0', + id, + method: 'agent_device.command', + params: { command: 'devices', positionals: [] }, + }, + }); + assert.equal(response.status, 409); + return ((await response.json()) as { id: unknown }).id; + }; + assert.equal(await refusalId('req-7'), 'req-7'); + assert.equal(await refusalId(42), 42); + assert.equal(await refusalId({ internal: true }), null); + assert.equal(await refusalId('http://10.0.0.1/private'), null); + assert.equal(await refusalId('x'.repeat(200)), null); + } finally { + await daemon.close(); + } +}); + +test('a refused checked call never reserves its request id from a concurrent /rpc call', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + // Holds only checked calls in the hook, so the /rpc call runs while the refusal is pending. + const daemon = await checkedDaemon( + 'export default async ({ headers }) => {\n' + + " if (headers['x-agent-device-rpc-protocol']) await new Promise((r) => setTimeout(r, 300));\n" + + " return { tenantId: 'tenant-a' };\n};\n", + ); + try { + const body = { + jsonrpc: '2.0', + id: 'rpc-1', + method: 'agent_device.command', + params: { command: 'devices', positionals: [], meta: { requestId: 'shared-id' } }, + }; + const refused = daemon.call({ protocol: '999', body }); + await new Promise((resolve) => setTimeout(resolve, 50)); + const legacy = await daemon.call({ route: '/rpc', body }); + assert.equal(legacy.status, 200); + assert.equal((await refused).status, 409); + } finally { + await daemon.close(); + } +}); + test('a matching checked call runs exactly like /rpc', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const daemon = await checkedDaemon(); diff --git a/packages/daemon/src/server/http/http-checked-rpc.ts b/packages/daemon/src/server/http/http-checked-rpc.ts index e4c4e26a56..df5d05e9aa 100644 --- a/packages/daemon/src/server/http/http-checked-rpc.ts +++ b/packages/daemon/src/server/http/http-checked-rpc.ts @@ -2,23 +2,25 @@ // refusal is a 409 with a typed refusal header, answered before dispatch, so the caller learns that // nothing ran. // -// The route reaches its protocol verdict inside the `/rpc` flow: the same envelope, the same -// decoding, and the same auth hook, tenant-trust and token gates, with the same inputs. Only a caller -// that passed all of them learns this daemon's version. A call that this build cannot decode cannot -// be authenticated the way `/rpc` would, so its protocol refusal names no version at all. +// A checked call first proves the transport credential, read from the headers and the JSON frame +// alone, never through the method decoder. It then takes the `/rpc` flow: the same envelope, +// decoding, auth hook, tenant-trust and token gates, from the same inputs. The protocol refusal is +// answered only after all of them pass; any earlier failure gets the ordinary `/rpc` rejection. import type http from 'node:http'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { readVersion } from '@agent-device/host-kit/version'; +import { resolveRequestTrackingId } from '@agent-device/host-kit/request'; import { - DAEMON_CHECKED_RPC_REASONS, + buildCheckedRpcProtocolRefusal, + checkedRpcProtocolRefusal, + checkedRpcRefusalId, DAEMON_HTTP_REFUSAL_HEADER, - DAEMON_HTTP_REFUSALS, DAEMON_HTTP_RPC_PROTOCOL_HEADER, DAEMON_RPC_PROTOCOL_VERSION, - checkedRpcProtocolRefusal, type CheckedRpcProtocolRefusal, } from '@agent-device/contracts/daemon-http'; -import { createRpcError, sendJson, type JsonRpcRequest } from './http-rpc-envelope.ts'; +import type { DaemonRequest } from '../../core/daemon-request.ts'; +import { enforceDaemonToken, resolveToken } from './http-authorization.ts'; +import { createRpcError, sendJson } from './http-rpc-envelope.ts'; /** The protocol refusal a checked call has earned, or `undefined` on `/rpc` or a matching protocol. */ export function readCheckedRpcProtocolRefusal( @@ -31,37 +33,66 @@ export function readCheckedRpcProtocolRefusal( } /** - * Answers a protocol refusal. `authenticated` says whether the caller passed the `/rpc` gates: only - * then does the refusal name this daemon's service, version and protocol, so a client can name who - * must upgrade. Otherwise it carries the refusal and its reason alone. + * Answers a checked call whose transport credential does not match, and reports whether it did. The + * token comes from the headers or the JSON frame's `params.token`, as `/rpc` reads it, before anything + * compares the protocol or decodes the method, so a wrong credential always gets 401. + */ +export function refuseCheckedRpcCredential( + req: http.IncomingMessage, + res: http.ServerResponse, + body: string, + expectedToken: string | undefined, +): boolean { + if (!expectedToken) return false; + const tokenError = enforceDaemonToken( + resolveToken(readFrameParams(body), req.headers), + expectedToken, + ); + if (!tokenError) return false; + sendJson(res, createRpcError(null, -32000, tokenError.message, tokenError), 401); + return true; +} + +/** + * The request a refused checked call shows the auth gates: its own tracking id stamped as admission + * would, but never registered, so the caller's id stays free for a call that can run. + */ +export function withUnregisteredTrackingId( + daemonRequest: DaemonRequest, + rpcId: unknown, +): DaemonRequest { + const requestId = resolveRequestTrackingId(daemonRequest.meta?.requestId, rpcId); + return { ...daemonRequest, meta: { ...daemonRequest.meta, requestId } }; +} + +/** + * Answers a protocol refusal for a caller that passed every `/rpc` gate, naming this daemon's + * service, version and protocol so the client can name who must upgrade. */ export function sendCheckedRpcProtocolRefusal( res: http.ServerResponse, - rpcId: JsonRpcRequest['id'], + rpcId: unknown, refusal: CheckedRpcProtocolRefusal, - authenticated: boolean, ): void { - const missing = refusal === DAEMON_HTTP_REFUSALS.protocolMissing; - const error = new AppError( - 'COMMAND_FAILED', - missing - ? `Checked RPC requires the ${DAEMON_HTTP_RPC_PROTOCOL_HEADER} header` - : 'The daemon speaks a different RPC protocol from the caller', - { - reason: missing - ? DAEMON_CHECKED_RPC_REASONS.protocolMissing.reason - : DAEMON_CHECKED_RPC_REASONS.protocolMismatch.reason, - dispatched: 'no', - ...(authenticated - ? { - service: 'agent-device-daemon', - version: readVersion(), - rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, - } - : {}), - }, - ); - const normalized = normalizeError(error); res.setHeader(DAEMON_HTTP_REFUSAL_HEADER, refusal); - sendJson(res, createRpcError(rpcId ?? null, -32001, normalized.message, normalized), 409); + sendJson( + res, + buildCheckedRpcProtocolRefusal(checkedRpcRefusalId(rpcId), refusal, { + service: 'agent-device-daemon', + version: readVersion(), + rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, + }), + 409, + ); +} + +function readFrameParams(body: string): Record { + try { + const parsed: unknown = JSON.parse(body); + const params = + parsed && typeof parsed === 'object' ? (parsed as { params?: unknown }).params : undefined; + return params && typeof params === 'object' ? (params as Record) : {}; + } catch { + return {}; + } } diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 3007bce609..4c855d569b 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -86,7 +86,9 @@ import { import { refuseStaleDaemonInstance } from './http-instance-precondition.ts'; import { readCheckedRpcProtocolRefusal, + refuseCheckedRpcCredential, sendCheckedRpcProtocolRefusal, + withUnregisteredTrackingId, } from './http-checked-rpc.ts'; const MAX_HTTP_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; @@ -329,16 +331,13 @@ async function handleRpcRequest(params: { checked: boolean; }): Promise { const { req, res, body, authHook, expectedToken, instanceId, handleRequest, checked } = params; - // A checked call on another protocol takes the `/rpc` flow up to its auth gates, and is refused - // in place of any later answer. One this build cannot decode is refused without the version. + // 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; const protocolRefusal = readCheckedRpcProtocolRefusal(req, checked); const validated = validateRpcRequestEnvelope(body); if (!validated.ok) { - if (protocolRefusal) { - sendCheckedRpcProtocolRefusal(res, validated.refusal.response.id, protocolRefusal, false); - } else { - sendRpcRefusal(res, validated.refusal); - } + sendRpcRefusal(res, validated.refusal); return; } @@ -380,11 +379,7 @@ 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(); - if (protocolRefusal) { - sendCheckedRpcProtocolRefusal(res, validated.rpcRequest.id ?? null, protocolRefusal, false); - } else { - sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); - } + sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); } finally { lifetime.release(); } @@ -615,10 +610,6 @@ async function admitRpcRequest(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)) { - if (protocolRefusal) { - sendCheckedRpcProtocolRefusal(res, rpcRequest.id ?? null, protocolRefusal, false); - return { outcome: 'answered' }; - } return { outcome: 'rejected', refusal: rpcRefusal( @@ -629,7 +620,10 @@ async function admitRpcRequest(params: { ), }; } - const daemonRequest = lifetime.admit(wireRequest); + // 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); // Captured before the hook runs: what the caller claimed is an input to the trust // decision, never an identity. @@ -659,7 +653,7 @@ async function admitRpcRequest(params: { return refused(rpcRequest, -32000, tokenError, 401); } if (protocolRefusal) { - sendCheckedRpcProtocolRefusal(res, rpcRequest.id ?? null, protocolRefusal, true); + sendCheckedRpcProtocolRefusal(res, rpcRequest.id, protocolRefusal); return { outcome: 'answered' }; } if (refuseStaleDaemonInstance(req, res, rpcRequest.id ?? null, instanceId)) { diff --git a/packages/proxy/README.md b/packages/proxy/README.md index d3083f41c7..5d92ac6894 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -7,8 +7,10 @@ The proxy: - authenticates clients with a token you choose, or with your own check, and never exposes the daemon's own token; -- forwards only the routes a remote client needs: `/health`, `/rpc`, uploads, artifacts, and - request diagnostics; +- forwards only the routes a remote client needs: `/health`, `/rpc`, `/rpc/checked`, uploads, + artifacts, and request diagnostics, each also under `/agent-device/`; +- refuses a `/rpc/checked` call whose `x-agent-device-rpc-protocol` header is missing or names + another RPC protocol, with a 409 before it forwards anything; - refuses install sources that name a file on the daemon host; - rewrites upload tickets so clients upload through the proxy, not to the daemon directly. @@ -152,6 +154,11 @@ const proxy = createDaemonProxy({ `upstreamFetch` receives a `Request` addressed to `upstreamBaseUrl` and must resolve with the daemon's `Response`. Abort the exchange when `request.signal` aborts. +Honor `request.redirect`. On `/rpc/checked` it is `'error'`: never follow a redirect there, because +a followed redirect resends the call with the daemon token, possibly to the unchecked `/rpc`. The +proxy refuses a checked answer that is a redirect or reports `redirected`, but it cannot undo a +request your transport already resent. + On transfer routes, the proxy bounds its wait for your transport and response body. It settles on your abort, your `upstreamTimeoutMs`, its 600-second aggregate and its demand-aware response-body inactivity limit. Work your transport starts can keep running if it ignores `request.signal`. The @@ -165,8 +172,9 @@ pull alone does not confirm that an outgoing byte was sent. ### Authenticate each client yourself One `clientToken` is shared by every client. To give each client its own credential, pass -`authenticate` instead. It receives each client request (with its JSON body on `/rpc`) and returns -the tenant the client acts as, or `null` to refuse it with a 401: +`authenticate` instead. It receives each client request (with its body on `/rpc` and +`/rpc/checked`) and returns the tenant the client acts as, or `null` to refuse it with a 401. On +`/rpc/checked` it runs before the envelope check, so the body may not be JSON: ```ts const proxy = createDaemonProxy({ @@ -182,8 +190,8 @@ const proxy = createDaemonProxy({ The proxy then sends every authenticated request to the daemon as that tenant, whatever tenant the client named, and isolates its sessions from other tenants' sessions. `GET /health` is not authenticated and carries no tenant. A tenant id is 1-128 letters, numbers, dots, underscores or -hyphens; any other id fails the request with a 500. On `/rpc` the proxy accepts only -`agent_device.command` and the `agent_device.lease.*` methods (or the same names spelled +hyphens; any other id fails the request with a 500. On `/rpc` and `/rpc/checked` the proxy accepts +only `agent_device.command` and the `agent_device.lease.*` methods (or the same names spelled `agent-device.command` and `agent-device.lease.*`), and refuses others with a 401. Clients upload files with a ticket that names the headers to send. The proxy builds that ticket diff --git a/packages/proxy/src/checked-rpc-admission.ts b/packages/proxy/src/checked-rpc-admission.ts index 9a13c63f8f..4e2b9f7028 100644 --- a/packages/proxy/src/checked-rpc-admission.ts +++ b/packages/proxy/src/checked-rpc-admission.ts @@ -1,16 +1,22 @@ -// The proxy's checked RPC admission (ADR 0006): its own protocol refusal, and the refusal header it -// carries back from the daemon behind it. Loaded only on the checked route. -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +// The proxy's checked RPC admission (ADR 0006): its own protocol refusal, and the answer it builds +// when the daemon behind it refuses one. Loaded only on the checked route. Every refusal here is +// built from local values: no upstream body or header value reaches the caller. +import { randomUUID } from 'node:crypto'; +import { AppError } from '@agent-device/kernel/errors'; import { + buildCheckedRpcProtocolRefusal, checkedRpcProtocolRefusal, - DAEMON_CHECKED_RPC_REASONS, + checkedRpcRefusalId, + readCheckedRpcRefusalSide, DAEMON_HTTP_REFUSAL_HEADER, DAEMON_HTTP_REFUSALS, DAEMON_HTTP_RPC_PROTOCOL_HEADER, DAEMON_RPC_PROTOCOL_VERSION, - type CheckedRpcProtocolRefusal, } from '@agent-device/contracts/daemon-http'; +/** The most of an upstream refusal body the proxy reads for its bounded diagnostic values. */ +const UPSTREAM_REFUSAL_MAX_BYTES = 64 * 1024; + /** * Refuses an authenticated checked call whose RPC protocol header is absent or names another * protocol. It runs after authentication and before the envelope check, the tenant method rules, @@ -23,50 +29,91 @@ export async function refuseCheckedRpcProtocol( const refusal = checkedRpcProtocolRefusal(request.headers.get(DAEMON_HTTP_RPC_PROTOCOL_HEADER)); if (!refusal) return null; const { readVersion } = await import('@agent-device/host-kit/version'); - const error = normalizeError(checkedRpcProtocolRefusalError(refusal, readVersion())); - return Response.json( - { jsonrpc: '2.0', id: rpcId, error: { code: -32001, message: error.message, data: error } }, - { status: 409, headers: { [DAEMON_HTTP_REFUSAL_HEADER]: refusal } }, - ); -} - -/** The refusal names this proxy in the `/health` vocabulary, so a client names who must upgrade. */ -function checkedRpcProtocolRefusalError( - refusal: CheckedRpcProtocolRefusal, - version: string, -): AppError { - const missing = refusal === DAEMON_HTTP_REFUSALS.protocolMissing; - return new AppError( - 'COMMAND_FAILED', - missing - ? `Checked RPC requires the ${DAEMON_HTTP_RPC_PROTOCOL_HEADER} header` - : 'The proxy speaks a different RPC protocol from the caller', - { - reason: missing - ? DAEMON_CHECKED_RPC_REASONS.protocolMissing.reason - : DAEMON_CHECKED_RPC_REASONS.protocolMismatch.reason, - dispatched: 'no', + return refusalResponse( + request, + refusal, + buildCheckedRpcProtocolRefusal(rpcId, refusal, { service: 'agent-device-proxy', - version, + version: readVersion(), rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, - }, + }), ); } /** - * The refusal header a checked call's 409 carries back through the proxy. A protocol refusal of the - * daemon behind the proxy says so, so the client names that daemon and not the proxy. Only the - * known values pass, and only on a 409 of the checked route. + * Answers the daemon's own checked refusal for it, or `null` when the upstream answer is not one. + * A protocol refusal of the daemon is marked `upstream-protocol-mismatch`, so the client names that + * daemon. Only the reason and the daemon's validated, bounded service, version and protocol pass; + * the body, the id and the headers are the proxy's. A redirect is never followed or passed on. */ -export function forwardedCheckedRpcRefusal(upstreamResponse: Response): string | undefined { - if (upstreamResponse.status !== 409) return undefined; - switch (upstreamResponse.headers.get(DAEMON_HTTP_REFUSAL_HEADER)) { - case DAEMON_HTTP_REFUSALS.protocolMismatch: - case DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch: - return DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch; - case DAEMON_HTTP_REFUSALS.protocolMissing: - return DAEMON_HTTP_REFUSALS.protocolMissing; - default: +export async function localCheckedRpcRefusal( + upstreamResponse: Response, + request: Request, + rpcId: unknown, +): Promise { + if ( + upstreamResponse.redirected || + (upstreamResponse.status >= 300 && upstreamResponse.status < 400) + ) { + await upstreamResponse.body?.cancel(); + throw new AppError('COMMAND_FAILED', 'The daemon answered a checked call with a redirect', { + hint: 'The proxy never follows a redirect on the checked route. Point upstreamBaseUrl at the daemon itself.', + }); + } + if (upstreamResponse.status !== 409) return null; + const refusal = upstreamResponse.headers.get(DAEMON_HTTP_REFUSAL_HEADER); + if (refusal === DAEMON_HTTP_REFUSALS.protocolMissing) { + await upstreamResponse.body?.cancel(); + return refusalResponse(request, refusal, buildCheckedRpcProtocolRefusal(rpcId, refusal)); + } + if ( + refusal !== DAEMON_HTTP_REFUSALS.protocolMismatch && + refusal !== DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch + ) { + return null; + } + const side = readCheckedRpcRefusalSide(await readUpstreamRefusalDetails(upstreamResponse)); + const upstream = DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch; + return refusalResponse(request, upstream, buildCheckedRpcProtocolRefusal(rpcId, upstream, side)); +} + +function refusalResponse(request: Request, refusal: string, body: unknown): Response { + return Response.json(body, { + status: 409, + headers: { + [DAEMON_HTTP_REFUSAL_HEADER]: refusal, + 'x-request-id': localRequestId(request), + }, + }); +} + +/** The caller's own correlation id when it is a bounded token, else a fresh one. */ +function localRequestId(request: Request): string { + const own = checkedRpcRefusalId(request.headers.get('x-request-id')); + return typeof own === 'string' ? own : randomUUID(); +} + +async function readUpstreamRefusalDetails(upstreamResponse: Response): Promise { + const reader = upstreamResponse.body?.getReader(); + if (!reader) return undefined; + const chunks: Uint8Array[] = []; + let bytes = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + bytes += value.byteLength; + if (bytes > UPSTREAM_REFUSAL_MAX_BYTES) { + await reader.cancel(); return undefined; + } + chunks.push(value); + } + try { + const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { + error?: { data?: { details?: unknown } }; + }; + return parsed.error?.data?.details; + } catch { + return undefined; } } diff --git a/packages/proxy/src/daemon-proxy-checked-rpc.test.ts b/packages/proxy/src/daemon-proxy-checked-rpc.test.ts index 2261aa54d8..7420239662 100644 --- a/packages/proxy/src/daemon-proxy-checked-rpc.test.ts +++ b/packages/proxy/src/daemon-proxy-checked-rpc.test.ts @@ -1,3 +1,4 @@ +import http from 'node:http'; import { expect, test } from 'vitest'; import { DAEMON_HTTP_CHECKED_RPC_CAPABILITY, @@ -182,3 +183,97 @@ test('proxy health advertises the checked route', async () => { const health = (await response.json()) as { capabilities: string[] }; expect(health.capabilities).toEqual([DAEMON_HTTP_CHECKED_RPC_CAPABILITY]); }); + +test('the proxy protocol refusal echoes only a bounded id', async () => { + const upstream = recordingUpstream(() => Response.json({})); + const response = await tokenProxy(upstream.fetch).handle( + checkedRequest( + { ...COMMAND, id: { internal: 'http://10.0.0.1/private' } }, + { [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: '999' }, + ), + ); + + expect(response.status).toBe(409); + expect(((await response.json()) as { id: unknown }).id).toBeNull(); +}); + +test('an upstream protocol refusal is rebuilt from validated values, never copied', async () => { + const upstream = recordingUpstream(() => + Response.json( + { + jsonrpc: '2.0', + id: 'upstream-id', + error: { + code: -32001, + message: 'see http://10.0.0.1/internal', + data: { + details: { + service: 'agent-device-daemon', + version: '9.0.0', + rpcProtocolVersion: 99, + internal: 'http://10.0.0.1/internal', + }, + }, + }, + }, + { + status: 409, + headers: { + [DAEMON_HTTP_REFUSAL_HEADER]: 'protocol-mismatch', + 'x-request-id': 'http://10.0.0.1/trace', + }, + }, + ), + ); + const response = await tokenProxy(upstream.fetch).handle(checkedRequest(COMMAND)); + + expect(response.status).toBe(409); + expect(response.headers.get(DAEMON_HTTP_REFUSAL_HEADER)).toBe('upstream-protocol-mismatch'); + expect(response.headers.get('x-request-id')).not.toContain('10.0.0.1'); + const text = await response.text(); + expect(text).not.toContain('10.0.0.1'); + expect(JSON.parse(text)).toMatchObject({ + id: 1, + error: { + data: { + details: { + reason: 'remote_rpc_protocol_mismatch', + dispatched: 'no', + service: 'agent-device-daemon', + version: '9.0.0', + rpcProtocolVersion: 99, + }, + }, + }, + }); +}); + +test('a checked call never follows an upstream redirect to /rpc', async () => { + let rpcHits = 0; + const daemon = http.createServer((req, res) => { + req.resume(); + if (req.url === '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/rpc/checked') { + res.writeHead(307, { location: '/rpc' }); + res.end(); + return; + } + rpcHits += 1; + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ jsonrpc: '2.0', id: 1, result: { ok: true, data: {} } })); + }); + try { + await new Promise((resolve) => daemon.listen(0, '127.0.0.1', resolve)); + const { port } = daemon.address() as { port: number }; + const proxy = createDaemonProxy({ + upstreamBaseUrl: `http://127.0.0.1:${port}`, + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + }); + const response = await proxy.handle(checkedRequest(COMMAND)); + + expect(response.status).not.toBe(200); + expect(rpcHits).toBe(0); + } finally { + await new Promise((resolve) => daemon.close(() => resolve())); + } +}); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 731d37f7db..5e1bb8d15e 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -21,7 +21,6 @@ import { DAEMON_INSTANCE_REASONS, DAEMON_HTTP_CHECKED_RPC_CAPABILITY, DAEMON_HTTP_CHECKED_RPC_ROUTE, - DAEMON_HTTP_REFUSAL_HEADER, DAEMON_HTTP_RPC_PROTOCOL_HEADER, DAEMON_RPC_PROTOCOL_VERSION, } from '@agent-device/contracts/daemon-http'; @@ -37,6 +36,9 @@ import { * transport, such as a WebSocket tunnel. Abort the exchange when `request.signal` aborts. * * A custom transport owns its phase guarantees and must observe `request.signal` on every route. + * It must also honor `request.redirect`: the checked RPC route sets `'error'`, so the transport must + * never follow a redirect there. The proxy refuses a checked answer that is a redirect or that + * reports `redirected`, but it cannot undo a resend the transport already made. * On transfer routes, the proxy bounds its own response and body waits, even if the transport * ignores cancellation. It cannot forcibly join work started by that transport. */ @@ -380,22 +382,25 @@ async function forwardProxyRequest(params: { }): Promise { const { request, route, options, rpcBody, caller } = params; const body = resolveUpstreamBody(request, route, rpcBody, options.upstreamToken, caller.tenantId); + const checked = route === DAEMON_HTTP_CHECKED_RPC_ROUTE; const upstreamResponse = await options.upstreamTransport( route, forwardedRequest(request, buildUpstreamUrl(options.upstreamBaseUrl, route, request.url), { method: request.method, headers: buildUpstreamHeaders(request.headers, options.upstreamToken, route, caller.tenantId), signal: upstreamSignal(request, options), + // A redirect would resend the call with the daemon token, possibly to unchecked `/rpc`. + ...(checked ? { redirect: 'error' as const } : {}), ...(body ? { body, duplex: 'half' as const } : {}), }), ); + if (checked) { + const { localCheckedRpcRefusal } = await import('./checked-rpc-admission.ts'); + const refusal = await localCheckedRpcRefusal(upstreamResponse, request, readJsonRpcId(rpcBody)); + if (refusal) return refusal; + } const headers = copyProxyResponseHeaders(upstreamResponse, request, route); - if (route === DAEMON_HTTP_CHECKED_RPC_ROUTE) { - const { forwardedCheckedRpcRefusal } = await import('./checked-rpc-admission.ts'); - const refusal = forwardedCheckedRpcRefusal(upstreamResponse); - if (refusal) headers.set(DAEMON_HTTP_REFUSAL_HEADER, refusal); - } if (isUploadPreflightRoute(route)) { return await rewrittenUploadPreflightResponse({ request, diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 8778fda17e..46947c49ef 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -201,14 +201,24 @@ "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_REFUSAL_HEADER": "sha256:914b491b3f169de831e6758269a363f85778629286afc542646373c48d3145d3", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_REFUSALS": "sha256:99c46b14d91cc6f9eb6c55bfa96b8d89d33cc4087beac5313c5276ccdbecaf7d", "packages/contracts/src/daemon-http.ts#checkedRpcProtocolRefusal": "sha256:a4efad68779436fa678c01e1c071ff45f52dcaa2e9902cd8be830937037174ef", + "packages/contracts/src/daemon-http.ts#checkedRpcRefusalId": "sha256:8c8cfcf83f06609109b85d8f66b4d8139447644263f2da0ac4bbfc3e53896d1a", + "packages/contracts/src/daemon-http.ts#CheckedRpcRefusalSide": "sha256:cc61050e901ed3706c75ffa27d48e8b05ef338a09804d43f4fdfa5978e82a1e9", + "packages/contracts/src/daemon-http.ts#readCheckedRpcRefusalSide": "sha256:dd9a413fa03ee17ec2f7508736aa5dbb6e226d72dba56dd76a0eb8ef7d59a816", + "packages/contracts/src/daemon-http.ts#buildCheckedRpcProtocolRefusal": "sha256:cce201d221956e0584d1474093c808a5e741cf0f2b5786a4a7937950bcacb397", + "packages/daemon/src/server/http/http-checked-rpc.ts#refuseCheckedRpcCredential": "sha256:5594a47e90079eaf31eeb335c709451f8e60616511a4ec84d7248722a37b93ea", + "packages/daemon/src/server/http/http-checked-rpc.ts#withUnregisteredTrackingId": "sha256:fffc54ad047879605f532801118868fd0aed1db38b74d671b65325551cc8fe0a", + "packages/daemon/src/server/http/http-checked-rpc.ts#readFrameParams": "sha256:8ccdb4a3b91a585be7c1518d198f34f608905c62b8eba9aad12b62a4107f5f31", + "packages/proxy/src/checked-rpc-admission.ts#localCheckedRpcRefusal": "sha256:017a05ac5b415d33030a30c99529a9dd58bb19aeae5649d15a6e00740fe84d95", + "packages/proxy/src/checked-rpc-admission.ts#refusalResponse": "sha256:10872cc1096a6c3262de9a2dccfb1fa447b67107322894a7289116575de9b4b7", + "packages/proxy/src/checked-rpc-admission.ts#localRequestId": "sha256:1bd486b7d70c727c2cab6330fc78f65e1922126be2e38d615f39c1b36acf9eb4", + "packages/proxy/src/checked-rpc-admission.ts#readUpstreamRefusalDetails": "sha256:4789d8cffbee31ce2c3c33184751bd11498365aa72e7b37e3b46c432e941920c", + "packages/proxy/src/checked-rpc-admission.ts#UPSTREAM_REFUSAL_MAX_BYTES": "sha256:c9546492158610bc037a2d6a6cad59f8580d3c63f1e1797283472e50dc2317c7", "packages/contracts/src/daemon-http.ts#CheckedRpcProtocolRefusal": "sha256:75b71253734f2a7e1bc34c42d4c9caca0c2eb25d809e5efb2ae0df58ae694202", "packages/daemon/src/server/http/http-checked-rpc.ts#readCheckedRpcProtocolRefusal": "sha256:4c8924d8480a6af3acec96883d53636e33a199649bdd8ff63087dcf2ebaf4d29", - "packages/daemon/src/server/http/http-checked-rpc.ts#sendCheckedRpcProtocolRefusal": "sha256:d69a4d6b39cb747ca373bab42b753c14e00817d2cf6e6ca5529f2e232344b591", + "packages/daemon/src/server/http/http-checked-rpc.ts#sendCheckedRpcProtocolRefusal": "sha256:0538d0374405a082b3c79b4225124ecbfab49dd0f53f44e401c155834c5518a5", "packages/daemon/src/server/http/http-server.ts#DAEMON_HTTP_CAPABILITIES": "sha256:bac67f03945b928de4fece3a5e02386ebba9b7b957b1107f76c84bc8ca574f94", "packages/proxy/src/daemon-proxy.ts#isRpcRoute": "sha256:1bf3b68f6bc855bd87ee7c0bbdef467c3c76232238885ae6c67bcf245ce9b846", - "packages/proxy/src/checked-rpc-admission.ts#refuseCheckedRpcProtocol": "sha256:96097745ef9845f473948e5b4a3a9fe872f034c4437ef08b722d9af69be21b00", - "packages/proxy/src/checked-rpc-admission.ts#checkedRpcProtocolRefusalError": "sha256:bb94640118109e802b5c73d943aec56e7aeff85f2cf88446bcd46c0e72d3c130", - "packages/proxy/src/checked-rpc-admission.ts#forwardedCheckedRpcRefusal": "sha256:be0fcba16fcee9e7592191325a6f0acb95316f9adbfa2f4a84c9a5240d62c691", + "packages/proxy/src/checked-rpc-admission.ts#refuseCheckedRpcProtocol": "sha256:dd63d879bf97d386889f1c4603b5722b9ad018a7f3415bcf72e44e3e8fefec48", "packages/proxy/src/daemon-proxy.ts#refuseStaleProxyInstance": "sha256:5c39c2b5a1b4bc897a2b01ac47c6856af47e787e8cc5798657f0ae24fd1c78e0", "packages/proxy/src/daemon-proxy.ts#sendInstanceMismatch": "sha256:a196304a18d0a37cb259d94dd67efeffe08afb6caf6a3461ab0870ef8c7bbda4", "packages/contracts/src/daemon-http.ts#buildDaemonInstanceMismatchRpcResponse": "sha256:24e50130bbd0c4a21dfc51005cabf118525b9121f918719a2c16f73fcfcfbcf9", diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index cb201adc66..46299c3625 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -106,15 +106,29 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'DAEMON_HTTP_REFUSALS', 'CheckedRpcProtocolRefusal', 'checkedRpcProtocolRefusal', + 'checkedRpcRefusalId', + 'CheckedRpcRefusalSide', + 'readCheckedRpcRefusalSide', + 'buildCheckedRpcProtocolRefusal', + ), + ...from( + HTTP_CHECKED_RPC, + 'readCheckedRpcProtocolRefusal', + 'refuseCheckedRpcCredential', + 'withUnregisteredTrackingId', + 'sendCheckedRpcProtocolRefusal', + 'readFrameParams', ), - ...from(HTTP_CHECKED_RPC, 'readCheckedRpcProtocolRefusal', 'sendCheckedRpcProtocolRefusal'), ...from(HTTP_SERVER, 'DAEMON_HTTP_CAPABILITIES'), ...from(DAEMON_PROXY, 'isRpcRoute'), ...from( PROXY_CHECKED_RPC, 'refuseCheckedRpcProtocol', - 'checkedRpcProtocolRefusalError', - 'forwardedCheckedRpcRefusal', + 'localCheckedRpcRefusal', + 'refusalResponse', + 'localRequestId', + 'readUpstreamRefusalDetails', + 'UPSTREAM_REFUSAL_MAX_BYTES', ), ...from( DAEMON_PROXY, diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 8685cee553..89f43c3074 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -287,7 +287,7 @@ start the daemon with a policy that requires one (`leases.require`, below). The by every client of the proxy, so a host serving several clients through one proxy authenticates each client itself and sets each request's tenant, session isolation, and lease before forwarding it. Embedding `@agent-device/proxy` with its `authenticate` option does the tenant and session -isolation part: the proxy sends each client's requests as the tenant `authenticate` returns. A tenant id is 1-128 letters, numbers, dots, underscores or hyphens; any other id fails the request with a 500. On `/rpc` the proxy accepts only `agent_device.command` and the `agent_device.lease.*` methods, and refuses others with a 401. Upload tickets carry the client's own `authorization` and `x-agent-device-token` headers, or the `uploadHeaders` that `authenticate` returns, and never the daemon's token. +isolation part: the proxy sends each client's requests as the tenant `authenticate` returns. A tenant id is 1-128 letters, numbers, dots, underscores or hyphens; any other id fails the request with a 500. On `/rpc` and `/rpc/checked` the proxy accepts only `agent_device.command` and the `agent_device.lease.*` methods, and refuses others with a 401. Upload tickets carry the client's own `authorization` and `x-agent-device-token` headers, or the `uploadHeaders` that `authenticate` returns, and never the daemon's token. ## Restrict what clients can do @@ -328,7 +328,7 @@ stop that daemon first. A denied request fails with `UNAUTHORIZED` and ## What the proxy exposes -The proxy serves only the daemon HTTP contract: `/health`, `/rpc`, `/upload` plus resumable `/upload/*` routes, and `/artifacts/*`, with the same routes also available under `/agent-device/*`. Health checks are unauthenticated; command, upload, and artifact routes require the bearer token. `GET /artifacts` lists the caller tenant's downloadable artifacts. An entry has `sessionName` when the daemon registered it outside a request reply, for example a recording kept when its leased session ended. +The proxy serves only the daemon HTTP contract: `/health`, `/rpc`, `/rpc/checked` (which requires the `x-agent-device-rpc-protocol` header), `/upload` plus resumable `/upload/*` routes, and `/artifacts/*`, with the same routes also available under `/agent-device/*`. Health checks are unauthenticated; command, upload, and artifact routes require the bearer token. `GET /artifacts` lists the caller tenant's downloadable artifacts. An entry has `sessionName` when the daemon registered it outside a request reply, for example a recording kept when its leased session ended. The proxy passes the daemon's HTTP status through. Most failed upload and artifact requests answer a JSON body `{ "ok": false, "error": "...", "code": "..." }`. When the daemon writes this body, it From 1633e100df3b44294861e34a96c55f2625fbd0ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 11:07:03 +0100 Subject: [PATCH 5/5] fix(contracts): cap the whole refusal version string before its syntax check A checked refusal's version is capped at the 64 characters the /health reader allows before the syntax test, so a version of many digits never reaches the proxy's rebuilt 409; the refusal keeps its reason without the diagnostic fields. Co-Authored-By: Claude Opus 5.5 --- packages/contracts/src/daemon-http.ts | 2 ++ .../src/daemon-proxy-checked-rpc.test.ts | 32 +++++++++++++++++++ test/wire-compat/ledger.json | 2 +- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 48075b263e..f53d09aaf2 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -217,8 +217,10 @@ export function readCheckedRpcRefusalSide(details: unknown): CheckedRpcRefusalSi if (!details || typeof details !== 'object') return undefined; const { service, version, rpcProtocolVersion } = details as Record; if (service !== 'agent-device-daemon' && service !== 'agent-device-proxy') return undefined; + // The whole string is capped first, at the length the `/health` reader allows a version. if ( typeof version !== 'string' || + version.length > 64 || !/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]{1,48})?$/.test(version) ) { return undefined; diff --git a/packages/proxy/src/daemon-proxy-checked-rpc.test.ts b/packages/proxy/src/daemon-proxy-checked-rpc.test.ts index 7420239662..60e76d32f5 100644 --- a/packages/proxy/src/daemon-proxy-checked-rpc.test.ts +++ b/packages/proxy/src/daemon-proxy-checked-rpc.test.ts @@ -277,3 +277,35 @@ test('a checked call never follows an upstream redirect to /rpc', async () => { await new Promise((resolve) => daemon.close(() => resolve())); } }); + +test('an upstream refusal with an oversized version keeps the protocol 409 without its diagnostics', async () => { + const upstream = recordingUpstream(() => + Response.json( + { + jsonrpc: '2.0', + id: 1, + error: { + code: -32001, + message: 'skew', + data: { + details: { + service: 'agent-device-daemon', + version: `${'9'.repeat(60_000)}.0.0`, + rpcProtocolVersion: 99, + }, + }, + }, + }, + { status: 409, headers: { [DAEMON_HTTP_REFUSAL_HEADER]: 'protocol-mismatch' } }, + ), + ); + const response = await tokenProxy(upstream.fetch).handle(checkedRequest(COMMAND)); + + expect(response.status).toBe(409); + expect(response.headers.get(DAEMON_HTTP_REFUSAL_HEADER)).toBe('upstream-protocol-mismatch'); + const text = await response.text(); + expect(text.length).toBeLessThan(2_000); + const details = (JSON.parse(text) as { error: { data: { details: Record } } }) + .error.data.details; + expect(details).toEqual({ reason: 'remote_rpc_protocol_mismatch', dispatched: 'no' }); +}); diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 46947c49ef..29bfc82186 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -203,7 +203,7 @@ "packages/contracts/src/daemon-http.ts#checkedRpcProtocolRefusal": "sha256:a4efad68779436fa678c01e1c071ff45f52dcaa2e9902cd8be830937037174ef", "packages/contracts/src/daemon-http.ts#checkedRpcRefusalId": "sha256:8c8cfcf83f06609109b85d8f66b4d8139447644263f2da0ac4bbfc3e53896d1a", "packages/contracts/src/daemon-http.ts#CheckedRpcRefusalSide": "sha256:cc61050e901ed3706c75ffa27d48e8b05ef338a09804d43f4fdfa5978e82a1e9", - "packages/contracts/src/daemon-http.ts#readCheckedRpcRefusalSide": "sha256:dd9a413fa03ee17ec2f7508736aa5dbb6e226d72dba56dd76a0eb8ef7d59a816", + "packages/contracts/src/daemon-http.ts#readCheckedRpcRefusalSide": "sha256:61c1b531a34e2876e3f8a5b2cf9ee38d437fbf9c1086b66dd771072d31676e67", "packages/contracts/src/daemon-http.ts#buildCheckedRpcProtocolRefusal": "sha256:cce201d221956e0584d1474093c808a5e741cf0f2b5786a4a7937950bcacb397", "packages/daemon/src/server/http/http-checked-rpc.ts#refuseCheckedRpcCredential": "sha256:5594a47e90079eaf31eeb335c709451f8e60616511a4ec84d7248722a37b93ea", "packages/daemon/src/server/http/http-checked-rpc.ts#withUnregisteredTrackingId": "sha256:fffc54ad047879605f532801118868fd0aed1db38b74d671b65325551cc8fe0a",