Skip to content

Commit 9bbde0e

Browse files
committed
test(daemon): pin the rpc admission order and the tracking id's lifetime
Both behaviors already hold, and no suite said so: the tenant-trust and instance-precondition suites refuse a bad tenant or token, but neither asks whether the operator's hook runs before the token comparison or whether a call whose tracking id is already in flight ever reaches the hook. The lifetime suite pins the release the token-gate refusal still owes.
1 parent b15c7c7 commit 9bbde0e

3 files changed

Lines changed: 182 additions & 0 deletions

File tree

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import fs from 'node:fs';
4+
import path from 'node:path';
5+
import type { DaemonRequest, DaemonResponse } from '../daemon-request.ts';
6+
import {
7+
closeLoopbackServer,
8+
skipWhenLoopbackUnavailable,
9+
} from '../../__tests__/test-utils/loopback.ts';
10+
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
11+
import { restoreEnv } from '../../__tests__/test-utils/env.ts';
12+
import { postRpcCommand, startRpcServer } from './http-server-rpc.fixtures.ts';
13+
14+
const DAEMON_TOKEN = 'admission-daemon-secret';
15+
const HOOK_CALLS_ENV = 'AGENT_DEVICE_TEST_HOOK_CALLS';
16+
const ATTESTING_HOOK = `export default () => {
17+
process.env.${HOOK_CALLS_ENV} = String(Number(process.env.${HOOK_CALLS_ENV} ?? 0) + 1);
18+
return { tenantId: 'tenant-admitted' };
19+
};
20+
`;
21+
const REJECTING_HOOK = "export default () => ({ ok: false, message: 'hook said no' });\n";
22+
23+
// What separates these from the sibling suites: `http-server-tenant-trust.test.ts` pins -32001
24+
// for an unattested tenant, `http-instance-precondition.test.ts` pins a bad token ahead of the
25+
// stale-instance 409. Neither says whether the operator's hook gets a turn before the token.
26+
test('the rpc admission asks the auth hook before it compares the token', async (t) => {
27+
if (await skipWhenLoopbackUnavailable(t)) return;
28+
const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;
29+
try {
30+
for (const [index, hookSource] of [REJECTING_HOOK, ATTESTING_HOOK].entries()) {
31+
const requestId = `req-hook-order-${index}`;
32+
const dispatched: DaemonRequest[] = [];
33+
const { port, server } = await startWithAuthHook(hookSource, async (request) => {
34+
dispatched.push(request);
35+
return { ok: true, data: {} };
36+
});
37+
try {
38+
const response = await postRpcCommand(port, 'wrong-token', requestId);
39+
assert.equal(response.status, 401);
40+
// A rejecting hook answers first; once it attests, the bad token is the gate left.
41+
assert.equal(response.body.error?.code, index === 0 ? -32001 : -32000);
42+
assert.equal(dispatched.length, 0, 'a refused call must never reach the router');
43+
} finally {
44+
await closeLoopbackServer(server);
45+
}
46+
}
47+
} finally {
48+
restoreEnv('AGENT_DEVICE_HTTP_AUTH_HOOK', previousHook);
49+
}
50+
});
51+
52+
// The tracking id is registered ahead of the gate, so the loser of a duplicate-id race is
53+
// refused by the registration and the operator's hook never sees it. The hook runs in this
54+
// process, so it can count its own invocations and say so.
55+
test('the rpc admission registers the tracking id before consulting the auth hook', async (t) => {
56+
if (await skipWhenLoopbackUnavailable(t)) return;
57+
const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;
58+
const previousCalls = process.env[HOOK_CALLS_ENV];
59+
delete process.env[HOOK_CALLS_ENV];
60+
61+
let markStarted: () => void = () => {};
62+
const started = new Promise<void>((resolve) => {
63+
markStarted = resolve;
64+
});
65+
let release: () => void = () => {};
66+
const { port, server } = await startWithAuthHook(ATTESTING_HOOK, async () => {
67+
markStarted();
68+
await new Promise<void>((resolve) => {
69+
release = resolve;
70+
});
71+
return { ok: true, data: {} };
72+
});
73+
74+
try {
75+
const first = postRpcCommand(port, DAEMON_TOKEN, 'req-admission');
76+
await started;
77+
assert.equal(hookCalls(), 1, 'the admitted call consulted the hook');
78+
79+
const duplicate = await postRpcCommand(port, DAEMON_TOKEN, 'req-admission');
80+
assert.equal(duplicate.status, 400);
81+
assert.equal(duplicate.body.error?.data?.details?.reason, 'duplicate_request_id');
82+
assert.equal(
83+
hookCalls(),
84+
1,
85+
'the auth hook must not see a call the tracking-id registration already refused',
86+
);
87+
88+
release();
89+
assert.equal((await first).status, 200);
90+
} finally {
91+
restoreEnv('AGENT_DEVICE_HTTP_AUTH_HOOK', previousHook);
92+
restoreEnv(HOOK_CALLS_ENV, previousCalls);
93+
release();
94+
await closeLoopbackServer(server);
95+
}
96+
});
97+
98+
function hookCalls(): number {
99+
return Number(process.env[HOOK_CALLS_ENV] ?? 0);
100+
}
101+
102+
async function startWithAuthHook(
103+
hookSource: string,
104+
handleRequest: (request: DaemonRequest) => Promise<DaemonResponse>,
105+
) {
106+
const hookPath = path.join(mkdtempForTestSync('agent-device-rpc-admission-'), 'hook.mjs');
107+
fs.writeFileSync(hookPath, hookSource);
108+
process.env.AGENT_DEVICE_HTTP_AUTH_HOOK = hookPath;
109+
return startRpcServer(DAEMON_TOKEN, handleRequest);
110+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import type { DaemonResponse } from '../daemon-request.ts';
4+
import { getRequestSignal } from '@agent-device/host-kit/request';
5+
import {
6+
closeLoopbackServer,
7+
skipWhenLoopbackUnavailable,
8+
} from '../../__tests__/test-utils/loopback.ts';
9+
import { postRpcCommand, startRpcServer } from './http-server-rpc.fixtures.ts';
10+
11+
const TOKEN = 'lifetime-token';
12+
13+
// Both cases end with the tracking id free, and the admitted case shows the handler running
14+
// against a live signal. A call that registered and never released would keep its id claimed, so
15+
// the rerun below would be refused as `duplicate_request_id`. The token gate refuses a call that
16+
// already registered — admission order is pinned in `http-server-rpc-admission.test.ts` — so
17+
// this is where that release is pinned. Disconnect and streaming releases live in
18+
// `daemon-http-server.test.ts` and `daemon-http-boundary-cancellation.test.ts`.
19+
test('an rpc request registers its tracking id while in flight and releases it once answered', async (t) => {
20+
if (await skipWhenLoopbackUnavailable(t)) return;
21+
const { port, server } = await startRpcServer(TOKEN, async (request) => {
22+
assert.ok(getRequestSignal(request.meta?.requestId), 'the handler must see its own signal');
23+
return { ok: true, data: {} } satisfies DaemonResponse;
24+
});
25+
try {
26+
for (const [scenario, bearerToken, expectedStatus] of [
27+
['answered', TOKEN, 200],
28+
['refused', 'wrong-token', 401],
29+
] as const) {
30+
const requestId = `req-lifetime-${scenario}`;
31+
assert.equal((await postRpcCommand(port, bearerToken, requestId)).status, expectedStatus);
32+
assert.equal(getRequestSignal(requestId), undefined, `${scenario}: id must be released`);
33+
assert.equal((await postRpcCommand(port, TOKEN, requestId)).status, 200);
34+
}
35+
} finally {
36+
await closeLoopbackServer(server);
37+
}
38+
});
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import type { Server } from 'node:http';
2+
import { createDaemonHttpServer } from '../server/http-server.ts';
3+
import type { DaemonRequest, DaemonResponse } from '../daemon-request.ts';
4+
import { listenOnLoopback } from '../../__tests__/test-utils/loopback.ts';
5+
6+
export type RpcErrorBody = { error?: { code?: number; data?: { details?: { reason?: string } } } };
7+
8+
/** One `agent_device.command` call over `/rpc`, as the daemon answered it. */
9+
export async function postRpcCommand(
10+
port: number,
11+
bearerToken: string,
12+
requestId: string,
13+
): Promise<{ status: number; body: RpcErrorBody }> {
14+
const response = await fetch(`http://127.0.0.1:${port}/rpc`, {
15+
method: 'POST',
16+
headers: { 'content-type': 'application/json', authorization: `Bearer ${bearerToken}` },
17+
body: JSON.stringify({
18+
jsonrpc: '2.0',
19+
id: requestId,
20+
method: 'agent_device.command',
21+
params: { command: 'session_list', meta: { requestId } },
22+
}),
23+
});
24+
return { status: response.status, body: (await response.json()) as RpcErrorBody };
25+
}
26+
27+
/** A daemon listening on loopback, with `handleRequest` answering every call. */
28+
export async function startRpcServer(
29+
token: string,
30+
handleRequest: (request: DaemonRequest) => Promise<DaemonResponse>,
31+
): Promise<{ port: number; server: Server }> {
32+
const server = await createDaemonHttpServer({ token, handleRequest });
33+
return { port: (await listenOnLoopback(server)) as number, server };
34+
}

0 commit comments

Comments
 (0)