diff --git a/docs/adr/0006-daemon-rpc-protocol-version.md b/docs/adr/0006-daemon-rpc-protocol-version.md index 46e27836b8..fe98175677 100644 --- a/docs/adr/0006-daemon-rpc-protocol-version.md +++ b/docs/adr/0006-daemon-rpc-protocol-version.md @@ -6,7 +6,8 @@ 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 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. @@ -70,6 +71,28 @@ 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 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. +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. @@ -77,6 +100,8 @@ 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. ## Consequences diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 78c6122085..f53d09aaf2 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -147,6 +147,121 @@ 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', +} as const; +/** 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 a checked RPC call failed. */ +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 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 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 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; +} + +/** + * 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; + // 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; + } + 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-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/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' } }); 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..7f83a5639a --- /dev/null +++ b/packages/daemon/src/server/http/http-checked-rpc.test.ts @@ -0,0 +1,277 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { createDaemonHttpServer } from './http-server.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'; + +type RpcError = { + error?: { data?: { code?: string; details?: Record } }; +}; + +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 (request) => { + handlerCalls += 1; + return { ok: true, data: { echoed: request.command } }; + }, + 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 health = (await (await fetch(`${daemon.endpoint}/health`)).json()) as { + capabilities: string[]; + }; + assert.ok(health.capabilities.includes(DAEMON_HTTP_CHECKED_RPC_CAPABILITY)); + + 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); + + const skewed = await daemon.call({ protocol: '999' }); + assert.equal(skewed.status, 409); + assert.equal(skewed.headers.get(DAEMON_HTTP_REFUSAL_HEADER), 'protocol-mismatch'); + 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 daemon.call({}); + assert.equal(missing.status, 409); + assert.equal(missing.headers.get(DAEMON_HTTP_REFUSAL_HEADER), 'protocol-missing'); + assert.equal(daemon.handlerCalls(), 0); + } finally { + await daemon.close(); + } +}); + +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; + // 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 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: [], meta: { tenantId: 'tenant-a' } }, + }, + }); + assert.equal(refused.status, 401); + assert.equal(refused.headers.get(DAEMON_HTTP_REFUSAL_HEADER), null); + } finally { + await daemon.close(); + } +}); + +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 { + 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-5', method: 'agent_device.future_method', params: {} }, + }); + 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(); + 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 new file mode 100644 index 0000000000..df5d05e9aa --- /dev/null +++ b/packages/daemon/src/server/http/http-checked-rpc.ts @@ -0,0 +1,98 @@ +// 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. +// +// 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 { readVersion } from '@agent-device/host-kit/version'; +import { resolveRequestTrackingId } from '@agent-device/host-kit/request'; +import { + buildCheckedRpcProtocolRefusal, + checkedRpcProtocolRefusal, + checkedRpcRefusalId, + DAEMON_HTTP_REFUSAL_HEADER, + DAEMON_HTTP_RPC_PROTOCOL_HEADER, + DAEMON_RPC_PROTOCOL_VERSION, + type CheckedRpcProtocolRefusal, +} from '@agent-device/contracts/daemon-http'; +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( + req: http.IncomingMessage, + checked: boolean, +): CheckedRpcProtocolRefusal | undefined { + return checked + ? checkedRpcProtocolRefusal(req.headers[DAEMON_HTTP_RPC_PROTOCOL_HEADER]) + : undefined; +} + +/** + * 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: unknown, + refusal: CheckedRpcProtocolRefusal, +): void { + res.setHeader(DAEMON_HTTP_REFUSAL_HEADER, refusal); + 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 47d031d661..4c855d569b 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -32,7 +32,10 @@ import { buildDaemonHealthPayload, normalizeDaemonPublicOrigin, nodeHttpRequestUrl, + 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'; @@ -81,8 +84,16 @@ import { type TenantTrustDecision, } from './tenant-trust.ts'; 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; +/** 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 +154,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 +235,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 +255,7 @@ export async function createDaemonHttpServer(options: { expectedToken: token, instanceId, handleRequest, + checked, }).catch((error: unknown) => { sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); }); @@ -314,8 +327,14 @@ async function handleRpcRequest(params: { expectedToken: string | undefined; instanceId: string; handleRequest: DaemonInvokeFn; + /** 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 } = params; + const { req, res, body, authHook, expectedToken, instanceId, handleRequest, checked } = params; + // A checked call proves its credential before anything reads its protocol or method. One on + // another protocol then takes the `/rpc` flow and is refused only once every auth gate passed. + if (checked && refuseCheckedRpcCredential(req, res, body, expectedToken)) return; + const protocolRefusal = readCheckedRpcProtocolRefusal(req, checked); const validated = validateRpcRequestEnvelope(body); if (!validated.ok) { sendRpcRefusal(res, validated.refusal); @@ -338,6 +357,7 @@ async function handleRpcRequest(params: { method: validated.method, params: validated.params, lifetime, + protocolRefusal, }); if (admission.outcome !== 'admitted') { if (admission.outcome === 'rejected') { @@ -557,8 +577,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 } @@ -582,8 +602,11 @@ 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)) { @@ -597,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. @@ -626,6 +652,10 @@ async function admitRpcRequest(params: { if (tokenError) { return refused(rpcRequest, -32000, tokenError, 401); } + if (protocolRefusal) { + sendCheckedRpcProtocolRefusal(res, rpcRequest.id, protocolRefusal); + return { outcome: 'answered' }; + } if (refuseStaleDaemonInstance(req, res, rpcRequest.id ?? null, instanceId)) { return { outcome: 'answered' }; } 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 new file mode 100644 index 0000000000..4e2b9f7028 --- /dev/null +++ b/packages/proxy/src/checked-rpc-admission.ts @@ -0,0 +1,119 @@ +// 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, + checkedRpcRefusalId, + readCheckedRpcRefusalSide, + DAEMON_HTTP_REFUSAL_HEADER, + DAEMON_HTTP_REFUSALS, + DAEMON_HTTP_RPC_PROTOCOL_HEADER, + DAEMON_RPC_PROTOCOL_VERSION, +} 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, + * 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'); + return refusalResponse( + request, + refusal, + buildCheckedRpcProtocolRefusal(rpcId, refusal, { + service: 'agent-device-proxy', + version: readVersion(), + rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, + }), + ); +} + +/** + * 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 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 new file mode 100644 index 0000000000..60e76d32f5 --- /dev/null +++ b/packages/proxy/src/daemon-proxy-checked-rpc.test.ts @@ -0,0 +1,311 @@ +import http from 'node:http'; +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.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( + new Request(`${PROXY_ORIGIN}/agent-device/health`), + ); + + 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())); + } +}); + +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/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 4710b7294b..5e1bb8d15e 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -19,6 +19,10 @@ import { normalizeDaemonPublicOrigin, DAEMON_REQUEST_MAX_BYTES, DAEMON_INSTANCE_REASONS, + DAEMON_HTTP_CHECKED_RPC_CAPABILITY, + DAEMON_HTTP_CHECKED_RPC_ROUTE, + DAEMON_HTTP_RPC_PROTOCOL_HEADER, + DAEMON_RPC_PROTOCOL_VERSION, } from '@agent-device/contracts/daemon-http'; import { carriesUnbackedHostPathInstallSource, @@ -32,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. */ @@ -190,7 +197,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 { @@ -202,7 +209,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); @@ -222,13 +232,21 @@ async function handleDaemonRoute( if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } + if (route === DAEMON_HTTP_CHECKED_RPC_ROUTE) { + // Loaded only on the checked route: authentication, then the protocol, then the envelope. + const { refuseCheckedRpcProtocol } = await import('./checked-rpc-admission.ts'); + const 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' }, { status: 401 }, ); } - if (caller.tenantId && route === '/rpc' && !isTenantStampedRpcMethod(rpcBody)) { + if (caller.tenantId && isRpcRoute(route) && !isTenantStampedRpcMethod(rpcBody)) { return tenantRpcMethodRefusedResponse(readJsonRpcId(rpcBody)); } @@ -331,6 +349,7 @@ async function proxyHealthResponse( upstream, instanceId, hostArch: await readHostCpuArch(), + capabilities: [DAEMON_HTTP_CHECKED_RPC_CAPABILITY], }), ); } @@ -363,15 +382,23 @@ 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 (isUploadPreflightRoute(route)) { @@ -604,8 +631,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 +704,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 +733,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 +847,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); @@ -833,7 +869,7 @@ function sendInstanceMismatch(rpcId: unknown): Response { } 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..29bfc82186 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -195,7 +195,31 @@ "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: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: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", + "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: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: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", "packages/proxy/src/daemon-proxy.ts#buildUpstreamInstancePreconditionHeaders": "sha256:9f5d76a1f761d65fabd7244fc67295fed5934a544e86a6455451ef8520cf1615", @@ -215,7 +239,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", @@ -313,7 +337,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 +426,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", @@ -659,6 +683,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 279ee27da5..46299c3625 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'; @@ -60,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'; @@ -93,6 +95,41 @@ 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', + 'CheckedRpcProtocolRefusal', + 'checkedRpcProtocolRefusal', + 'checkedRpcRefusalId', + 'CheckedRpcRefusalSide', + 'readCheckedRpcRefusalSide', + 'buildCheckedRpcProtocolRefusal', + ), + ...from( + HTTP_CHECKED_RPC, + 'readCheckedRpcProtocolRefusal', + 'refuseCheckedRpcCredential', + 'withUnregisteredTrackingId', + 'sendCheckedRpcProtocolRefusal', + 'readFrameParams', + ), + ...from(HTTP_SERVER, 'DAEMON_HTTP_CAPABILITIES'), + ...from(DAEMON_PROXY, 'isRpcRoute'), + ...from( + PROXY_CHECKED_RPC, + 'refuseCheckedRpcProtocol', + 'localCheckedRpcRefusal', + 'refusalResponse', + 'localRequestId', + 'readUpstreamRefusalDetails', + 'UPSTREAM_REFUSAL_MAX_BYTES', + ), ...from( DAEMON_PROXY, 'refuseStaleProxyInstance', diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index fffb4d5baa..2bfcc12e69 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 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. | 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