Skip to content

Commit 6352013

Browse files
committed
fix(daemon): refuse a non-object /rpc body before the flow reads it
A /rpc body that parses as JSON `null` reached `validateRpcRequestEnvelope`'s read of `jsonrpc`, which throws on a null root. The flow starts as a detached `void handleRpcRequest(...)`, so the rejection escaped to the daemon's `unhandledRejection` handler and that handler exits the process: any process that could reach the HTTP port could stop the daemon with one request body, ahead of the token check. Refuse a root that is not one object as the JSON-RPC Invalid Request (-32600, HTTP 400, `id: null`) before any property read, and give the detached call a `catch` that answers the request and records the failure in the request diagnostics, so no future flow rejection can spend the daemon either. Closes #3453
1 parent 1d15dac commit 6352013

4 files changed

Lines changed: 228 additions & 19 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import { AppError } from '@agent-device/kernel/errors';
4+
import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit/loopback';
5+
import { postRpcCommand, startRpcServer } from './http-server-rpc.fixtures.ts';
6+
7+
const TOKEN = 'throwing-handler-token';
8+
9+
// The property this PR depends on: a `/rpc` request never leaves a rejection for the detached
10+
// `void handleRpcRequest(...)` call to drop, because the daemon exits on `unhandledRejection`.
11+
// A rejecting handler is the closest reachable case, and the answer comes from the invocation's own
12+
// catch (`invokeAdmittedRpcRequest`), which answered it the same way before this PR — so this pins
13+
// existing behavior and the invariant the new detached `.catch` defends, not that `.catch` itself.
14+
// The flow's refusal for a body that is not a call has to reach the client with the call's own id
15+
// and typed reason, and the daemon must still serve the next request.
16+
test('a rejecting handler is answered for its own call id and never reaches the process', async (t) => {
17+
if (await skipWhenLoopbackUnavailable(t)) return;
18+
const rejections: string[] = [];
19+
const observeRejection = (reason: unknown) => {
20+
rejections.push(String(reason));
21+
};
22+
process.on('unhandledRejection', observeRejection);
23+
let dispatched = 0;
24+
const { port, server } = await startRpcServer(TOKEN, async () => {
25+
dispatched += 1;
26+
throw new AppError('COMMAND_FAILED', 'the handler could not finish', {
27+
reason: 'handler_probe',
28+
});
29+
});
30+
try {
31+
const first = await postRpcCommand(port, TOKEN, 'req-handler-throws');
32+
assert.equal(first.status, 500);
33+
assert.equal(first.body.id, 'req-handler-throws', 'the answer carries the call it answers');
34+
assert.equal(first.body.error?.code, -32000);
35+
assert.deepEqual(
36+
first.body.error?.data?.details?.reason,
37+
'handler_probe',
38+
'the typed reason survives to the client',
39+
);
40+
assert.equal(dispatched, 1);
41+
42+
// And the daemon is still a daemon: a later call on the same server runs and answers.
43+
const second = await postRpcCommand(port, TOKEN, 'req-after-handler-throws');
44+
assert.equal(second.body.error?.code, -32000, 'the second call reaches the same handler');
45+
assert.equal(dispatched, 2, 'the rejecting call left the request lifecycle usable');
46+
assert.deepEqual(rejections, [], 'a rejecting handler never reaches the process');
47+
} finally {
48+
process.off('unhandledRejection', observeRejection);
49+
await closeLoopbackServer(server);
50+
}
51+
});
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import http from 'node:http';
4+
import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit/loopback';
5+
import { postRpcCommand, postRpcRaw, startRpcServer } from './http-server-rpc.fixtures.ts';
6+
import type { DaemonResponse } from '../daemon-request.ts';
7+
8+
const TOKEN = 'invalid-body-token';
9+
10+
// What separates these from the sibling suites: `http-server-rpc-validation.test.ts` covers bodies
11+
// that ARE one object with unsound params, and `http-server-rpc-admission.test.ts` the order of the
12+
// gates a sound call passes. This covers the step in front of all of them: a body whose JSON root
13+
// is not one object at all. Such a body is not a call — it has no `id` to answer for and no method
14+
// to route — so it is refused before the token is compared. Refusing it is the whole difference
15+
// between a bad client and a daemon that dies: on `main` the `null` root threw while the flow read
16+
// `jsonrpc` off it, and that rejection reached the daemon's `unhandledRejection` handler, which
17+
// exits the process. Any process that could reach the port could stop the daemon without a token,
18+
// and a test server with no such process handler shows only a hung connection.
19+
20+
test('a /rpc body whose root is not one object is refused as -32600 without a token', async (t) => {
21+
if (await skipWhenLoopbackUnavailable(t)) return;
22+
let handlerCalls = 0;
23+
const { port, server } = await startRpcServer(TOKEN, async () => {
24+
handlerCalls += 1;
25+
return { ok: true, data: {} };
26+
});
27+
try {
28+
// `42`, `"x"` and `true` were already refused by reading `jsonrpc` off a value whose property
29+
// is simply undefined; `null` is the root that read throws on, and `[]` the one that reads as
30+
// an object, so every root shape is pinned rather than the one that happened to break.
31+
for (const [root, label] of [
32+
['null', 'null root'],
33+
['42', 'number root'],
34+
['"x"', 'string root'],
35+
['[]', 'array root'],
36+
['true', 'boolean root'],
37+
] as const) {
38+
// A BAD token on purpose: the refusal belongs ahead of the token gate, which is exactly why
39+
// an unauthenticated caller must not be able to make the daemon act on its body.
40+
const { status, body } = await postRpcRaw(port, 'wrong-token', root);
41+
assert.equal(status, 400, `${label}: refused with 400`);
42+
assert.equal(body.error?.code, -32600, `${label}: refused as Invalid Request`);
43+
assert.equal(
44+
(body as { id?: unknown }).id,
45+
null,
46+
`${label}: a body that is not a call has no id to answer for`,
47+
);
48+
}
49+
assert.equal(handlerCalls, 0, 'a body that is not a call must never reach the handler');
50+
} finally {
51+
await closeLoopbackServer(server);
52+
}
53+
});
54+
55+
// The refusal is only half of the guarantee; the other half is that the daemon is still there
56+
// afterwards with no rejection escaping to the process. Every body here is posted with a
57+
// client-side deadline, so a regression that answers nothing reports the missing answer rather
58+
// than a suite timeout. The bodies that never parse share the socket's -32700 path and must not
59+
// cost the daemon either.
60+
test('the daemon keeps serving after the bodies that never became a call', async (t) => {
61+
if (await skipWhenLoopbackUnavailable(t)) return;
62+
const rejections: string[] = [];
63+
const observeRejection = (reason: unknown) => {
64+
rejections.push(String(reason));
65+
};
66+
process.on('unhandledRejection', observeRejection);
67+
const { port, server } = await startRpcServer(TOKEN, async (): Promise<DaemonResponse> => ({
68+
ok: true,
69+
data: {},
70+
}));
71+
try {
72+
assert.equal(await postRpcWithDeadline(port, 'null'), 400, 'the null root is answered');
73+
for (const root of ['{oops', '']) {
74+
assert.equal(
75+
await postRpcWithDeadline(port, root),
76+
400,
77+
`${root}: a body that never parsed is answered`,
78+
);
79+
}
80+
assert.equal(
81+
(await postRpcCommand(port, TOKEN, 'req-after-invalid-body')).status,
82+
200,
83+
'a valid call after the refusals still runs',
84+
);
85+
assert.deepEqual(rejections, [], 'no /rpc body may escape the flow as an unhandled rejection');
86+
} finally {
87+
process.off('unhandledRejection', observeRejection);
88+
await closeLoopbackServer(server);
89+
}
90+
});
91+
92+
/** `/rpc` POST that gives up after a second: a daemon which never answers fails the caller. */
93+
async function postRpcWithDeadline(port: number, rawBody: string): Promise<number> {
94+
return await new Promise((resolve, reject) => {
95+
const req = http.request(
96+
{
97+
host: '127.0.0.1',
98+
port,
99+
method: 'POST',
100+
path: '/rpc',
101+
headers: { 'content-type': 'application/json', authorization: `Bearer ${TOKEN}` },
102+
},
103+
(res) => {
104+
res.resume();
105+
res.on('end', () => resolve(res.statusCode ?? 0));
106+
},
107+
);
108+
req.setTimeout(1_000, () => {
109+
req.destroy(new Error('the daemon never answered the request'));
110+
});
111+
req.on('error', reject);
112+
req.end(rawBody);
113+
});
114+
}

‎src/daemon/__tests__/http-server-rpc.fixtures.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ import { createDaemonHttpServer } from '../server/http-server.ts';
33
import type { DaemonRequest, DaemonResponse } from '../daemon-request.ts';
44
import { listenOnLoopback } from '@agent-device/test-kit/loopback';
55

6-
export type RpcErrorBody = { error?: { code?: number; data?: { details?: { reason?: string } } } };
6+
export type RpcErrorBody = {
7+
id?: unknown;
8+
error?: { code?: number; data?: { details?: { reason?: string } } };
9+
};
710

811
/** One `agent_device.command` call over `/rpc`, as the daemon answered it. */
912
export async function postRpcCommand(
@@ -24,6 +27,20 @@ export async function postRpcCommand(
2427
return { status: response.status, body: (await response.json()) as RpcErrorBody };
2528
}
2629

30+
/** One `/rpc` POST of a caller-chosen body, exactly as the daemon answered it. */
31+
export async function postRpcRaw(
32+
port: number,
33+
bearerToken: string,
34+
rawBody: string,
35+
): Promise<{ status: number; body: RpcErrorBody }> {
36+
const response = await fetch(`http://127.0.0.1:${port}/rpc`, {
37+
method: 'POST',
38+
headers: { 'content-type': 'application/json', authorization: `Bearer ${bearerToken}` },
39+
body: rawBody,
40+
});
41+
return { status: response.status, body: (await response.json()) as RpcErrorBody };
42+
}
43+
2744
/** A daemon listening on loopback, with `handleRequest` answering every call. */
2845
export async function startRpcServer(
2946
token: string,

‎src/daemon/server/http-server.ts‎

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { randomUUID } from 'node:crypto';
1010
import type { DiagnosticsRecordRef, NormalizedError } from '@agent-device/kernel/errors';
1111
import { normalizeError } from '@agent-device/kernel/errors';
1212
import { LEASE_BACKENDS } from '@agent-device/kernel/contracts';
13+
import { isRecord } from '@agent-device/kernel/record';
1314
import type { DaemonInvokeFn, DaemonRequest, DaemonResponse } from '../daemon-request.ts';
1415
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
1516
import {
@@ -178,6 +179,10 @@ export async function createDaemonHttpServer(options: {
178179
}
179180

180181
readRpcRequestBody(req, res, (body) => {
182+
// The flow owns this request's lifetime, so this call site must neither hold lifetime state
183+
// nor re-run it; the `catch` only answers. That answer is load-bearing: the daemon exits on
184+
// an `unhandledRejection`, so a rejection dropped here would let any process that reaches
185+
// the port stop the daemon with one request body.
181186
void handleRpcRequest({
182187
req,
183188
res,
@@ -186,6 +191,8 @@ export async function createDaemonHttpServer(options: {
186191
expectedToken: token,
187192
instanceId,
188193
handleRequest,
194+
}).catch((error: unknown) => {
195+
sendUnownedRpcRequestFailure(res, normalizeError(error));
189196
});
190197
});
191198
});
@@ -242,7 +249,8 @@ async function handleRpcRequest(params: {
242249
const lifetime = beginRpcRequestLifetime({ req, res, rpcId: validated.rpcRequest.id });
243250
// The `finally` below is the flow's only cleanup for a call that never reached an
244251
// invocation: unsound method params or a duplicate tracking id. An invoked request
245-
// releases its own lifetime as the last step of answering.
252+
// releases its own lifetime as the last step of answering, before anything observing the
253+
// socket gets a turn.
246254
try {
247255
const admission = await admitRpcRequest({
248256
req,
@@ -275,7 +283,7 @@ async function handleRpcRequest(params: {
275283
// or a duplicate tracking id. The failure answer is on its way, so a socket closing
276284
// after it is not a client walking out on work still in flight.
277285
lifetime.markHandlerCompleted();
278-
sendRpcRequestFailure(res, validated.rpcRequest, error);
286+
sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error));
279287
} finally {
280288
lifetime.release();
281289
}
@@ -310,15 +318,25 @@ type RpcEnvelopeVerdict =
310318

311319
/**
312320
* Parses and validates one `/rpc` body. A body that is not JSON gets the same -32700 answer
313-
* the socket's `error` listener gives a stream that breaks before it ends.
321+
* the socket's `error` listener gives a stream that breaks before it ends. A body that parses as
322+
* anything but one object — `null`, a number, a string, an array — is refused as -32600 before
323+
* anything reads a property off it: reading through `null` throws, and that throw has no call to
324+
* answer for.
314325
*/
315326
function validateRpcRequestEnvelope(body: string): RpcEnvelopeVerdict {
316-
let rpcRequest: JsonRpcRequest;
327+
let parsed: unknown;
317328
try {
318-
rpcRequest = JSON.parse(body) as JsonRpcRequest;
329+
parsed = JSON.parse(body);
319330
} catch {
320331
return { ok: false, refusal: rpcParseErrorRefusal() };
321332
}
333+
if (!isRecord(parsed)) {
334+
return {
335+
ok: false,
336+
refusal: rpcRefusal(null, INVALID_REQUEST, 'Invalid Request', 400),
337+
};
338+
}
339+
const rpcRequest = parsed as JsonRpcRequest;
322340

323341
const refused = (code: number, message: string, statusCode: number): RpcEnvelopeVerdict => ({
324342
ok: false,
@@ -493,7 +511,7 @@ async function admitRpcRequest(params: {
493511
outcome: 'rejected',
494512
refusal: rpcRefusal(
495513
rpcRequest.id ?? null,
496-
-32602,
514+
INVALID_PARAMS,
497515
'Invalid params: command is required',
498516
400,
499517
),
@@ -636,34 +654,43 @@ async function invokeAdmittedRpcRequest(params: {
636654
writeRpcResponseEnvelope(res, rpcAnswerFor(rpcRequest, daemonResponse));
637655
} catch (error) {
638656
lifetime.markHandlerCompleted();
639-
sendRpcRequestFailure(res, rpcRequest, error);
657+
sendRpcRequestFailure(res, rpcRequest.id, normalizeError(error));
640658
} finally {
641659
lifetime.release();
642660
}
643661
}
644662

645663
/**
646-
* Answers a call that failed before an answer could be written — malformed wire input the
647-
* method vocabulary refused, or a handler that threw. A status code goes only to a call
648-
* that has not started answering; a stream already opened answers with its envelope.
664+
* Last-resort answer for a `/rpc` flow rejection: no call id is known, so the refusal carries none.
665+
* The reason goes to the daemon's error stream — the sink `unhandledRejection` used, and the only
666+
* one guaranteed here, since the request's diagnostics scope opens later, inside `handleRequest`.
667+
*/
668+
function sendUnownedRpcRequestFailure(res: http.ServerResponse, failure: NormalizedError): void {
669+
process.stderr.write(`Daemon error: ${failure.message}\n`);
670+
if (!res.writableEnded) sendRpcRequestFailure(res, null, failure);
671+
}
672+
673+
/**
674+
* Answers a call that failed before an answer could be written — malformed wire input the method
675+
* vocabulary refused, a handler that threw, or a flow that rejected outright. A status code goes
676+
* only to a call that has not started answering; a stream already opened answers with its envelope.
649677
*/
650678
function sendRpcRequestFailure(
651679
res: http.ServerResponse,
652-
rpcRequest: JsonRpcRequest,
653-
error: unknown,
680+
requestId: JsonRpcRequest['id'],
681+
failure: NormalizedError,
654682
): void {
655-
const normalized = normalizeError(error);
656683
const response = createRpcError(
657-
rpcRequest.id ?? null,
658-
jsonRpcCodeForNormalizedError(normalized.code),
659-
normalized.message,
660-
normalized,
684+
requestId ?? null,
685+
jsonRpcCodeForNormalizedError(failure.code),
686+
failure.message,
687+
failure,
661688
);
662689
if (res.headersSent) {
663690
writeRpcResponseEnvelope(res, response);
664691
return;
665692
}
666-
sendJson(res, response, statusCodeForNormalizedError(normalized.code));
693+
sendJson(res, response, statusCodeForNormalizedError(failure.code));
667694
}
668695

669696
function rpcAnswerFor(rpcRequest: JsonRpcRequest, daemonResponse: DaemonResponse): JsonRpcResponse {

0 commit comments

Comments
 (0)