Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions packages/contracts/src/daemon-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,20 @@ export const DAEMON_RPC_PROTOCOL_VERSION = 3;
* worst-case escaping. It also bounds the memory one unauthenticated connection can hold.
*/
export const DAEMON_REQUEST_MAX_BYTES = 64 * 1024 * 1024;
/**
* How long an `/rpc` caller that has not authenticated yet may hold its connection, on the daemon
* and on the proxy: its body and its authentication must both finish inside this window.
*/
export const DAEMON_RPC_PREAUTH_TIMEOUT_MS = 30_000;
/** How many unauthenticated `/rpc` callers one daemon or one proxy holds at once. */
export const DAEMON_RPC_PREAUTH_SLOTS = 16;

/** Why a daemon or proxy refused an `/rpc` caller before it read the request body. */
export const DAEMON_RPC_PREAUTH_REASONS = {
// The daemon or proxy already holds its limit of callers that have not authenticated yet, so it
// answered HTTP 503 and closed the connection before it read the body. Retry after a short delay.
preauthBusy: { reason: 'remote_preauth_busy' },
} as const satisfies ReasonTable<'remote connection'>;

export const DAEMON_HTTP_INSTANCE_HEADER = 'x-agent-device-instance';
export const DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER = 'x-agent-device-upstream-instance';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ test('the rpc admission asks the auth hook before it compares the token', async
}
});

// The tracking id is registered ahead of the gate, so the loser of a duplicate-id race is
// refused by the registration and the operator's hook never sees it. The hook runs in this
// process, so it can count its own invocations and say so.
test('the rpc admission registers the tracking id before consulting the auth hook', async (t) => {
// Only an authenticated call registers its tracking id, so an unauthenticated caller can neither
// hold a tenant's id nor learn that it is in flight. The hook runs in this process, so it can
// count its own invocations and say so.
test('the rpc admission authenticates before it registers the tracking id', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;
const previousCalls = process.env[HOOK_CALLS_ENV];
Expand All @@ -75,16 +75,15 @@ test('the rpc admission registers the tracking id before consulting the auth hoo
try {
const first = postRpcCommand(port, DAEMON_TOKEN, 'req-admission');
await started;
assert.equal(hookCalls(), 1, 'the admitted call consulted the hook');

const unauthenticated = await postRpcCommand(port, 'wrong-token', 'req-admission');
assert.equal(unauthenticated.status, 401, 'an unauthenticated caller never meets the id');
assert.equal(unauthenticated.body.error?.code, -32000);

const duplicate = await postRpcCommand(port, DAEMON_TOKEN, 'req-admission');
assert.equal(duplicate.status, 400);
assert.equal(duplicate.body.error?.data?.details?.reason, 'duplicate_request_id');
assert.equal(
hookCalls(),
1,
'the auth hook must not see a call the tracking-id registration already refused',
);
assert.equal(hookCalls(), 3, 'every call authenticates before the id is registered');

release();
assert.equal((await first).status, 200);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
import { test, vi } from 'vitest';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import net from 'node:net';
import path from 'node:path';
import type { DaemonResponse } from '@agent-device/kernel/contracts';
import {
closeLoopbackServer,
listenOnLoopback,
mkdtempForTestSync,
skipWhenLoopbackUnavailable,
} from '@agent-device/test-kit';

// The real deadline, scaled down: the daemon's own timer runs on real time.
vi.mock('@agent-device/contracts/daemon-http', async (importOriginal) => ({
...(await importOriginal<typeof import('@agent-device/contracts/daemon-http')>()),
DAEMON_RPC_PREAUTH_TIMEOUT_MS: 200,
DAEMON_RPC_PREAUTH_SLOTS: 1,
}));

const RPC_HEAD = 'POST /rpc HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n';

async function startDaemon(env: NodeJS.ProcessEnv = process.env) {
const { createDaemonHttpServer } = await import('./http-server.ts');
const server = await createDaemonHttpServer({
token: 'daemon-secret',
handleRequest: async (): Promise<DaemonResponse> => ({ ok: true, data: {} }),
env,
cwd: process.cwd(),
});
return { server, port: await listenOnLoopback(server) };
}

function connect(port: number): net.Socket {
const socket = net.connect(port, '127.0.0.1');
socket.on('error', () => {});
return socket;
}

test('an unauthenticated rpc caller that stalls its body is closed at the pre-auth deadline', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const { createDaemonHttpServer } = await import('./http-server.ts');
let handlerCalls = 0;
const server = await createDaemonHttpServer({
token: 'daemon-secret',
handleRequest: async (): Promise<DaemonResponse> => {
handlerCalls += 1;
return { ok: true, data: {} };
},
env: process.env,
cwd: process.cwd(),
});
const port = await listenOnLoopback(server);
const socket = net.connect(port, '127.0.0.1');
socket.on('error', () => {});
try {
const closed = new Promise<void>((resolve) => socket.once('close', () => resolve()));
const startedAt = Date.now();
// No token header, so the token can only be in a body that never finishes.
socket.write(
'POST /rpc HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n' +
'Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"',
);
await closed;
assert.ok(Date.now() - startedAt < 2_000, 'the deadline, not a Node ceiling, closed it');
assert.equal(handlerCalls, 0);
} finally {
socket.destroy();
await closeLoopbackServer(server);
}
});

test('a caller over the pre-auth slot limit gets a retryable 503 and a closed connection', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const { server, port } = await startDaemon();
const holder = connect(port);
const excess = connect(port);
try {
const held = new Promise((resolve) => server.once('request', resolve));
holder.write(`${RPC_HEAD}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`);
await held;
let received = '';
excess.on('data', (chunk) => (received += chunk.toString('utf8')));
const closed = new Promise<void>((resolve) => excess.once('close', () => resolve()));
excess.write(`${RPC_HEAD}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`);
await closed;
assert.match(received, /^HTTP\/1\.1 503 /);
assert.match(received, /"reason":"remote_preauth_busy"/);
assert.match(received, /"retriable":true/);
} finally {
holder.destroy();
excess.destroy();
await closeLoopbackServer(server);
}
});

test('a caller that leaves while the auth hook runs aborts the hook signal', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const dir = mkdtempForTestSync('preauth-hook-');
const hookPath = path.join(dir, 'hook.mjs');
fs.writeFileSync(
hookPath,
`export default ({ signal }) => new Promise(() => {
globalThis.__preauthHook.started();
signal.addEventListener('abort', () => globalThis.__preauthHook.aborted());
});`,
);
const started = Promise.withResolvers<void>();
const aborted = Promise.withResolvers<void>();
Object.assign(globalThis, {
__preauthHook: { started: started.resolve, aborted: aborted.resolve },
});
const { server, port } = await startDaemon({
...process.env,
AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath,
});
const socket = connect(port);
try {
const body = JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'agent_device.command',
params: { command: 'devices' },
});
socket.write(`${RPC_HEAD}Content-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`);
await started.promise;
socket.destroy();
await aborted.promise;
} finally {
socket.destroy();
await closeLoopbackServer(server);
fs.rmSync(dir, { recursive: true, force: true });
Reflect.deleteProperty(globalThis, '__preauthHook');
}
});

test('a refusal queued behind an earlier answer frees its pre-auth slot before that answer', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const { createDaemonHttpServer } = await import('./http-server.ts');
const slowAnswer = Promise.withResolvers<void>();
const server = await createDaemonHttpServer({
token: 'daemon-secret',
handleRequest: async (): Promise<DaemonResponse> => {
await slowAnswer.promise;
return { ok: true, data: {} };
},
env: process.env,
cwd: process.cwd(),
});
const port = await listenOnLoopback(server);
const pipelined = connect(port);
const next = connect(port);
try {
const refused = new Promise<void>((resolve) => {
let requests = 0;
server.on('request', (req: NodeJS.ReadableStream) => {
if (++requests === 2) req.once('end', () => setImmediate(resolve));
});
});
const call = JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'agent_device.command',
params: { command: 'devices' },
});
pipelined.write(
`${RPC_HEAD}x-agent-device-token: daemon-secret\r\nContent-Length: ${call.length}\r\n\r\n${call}` +
`${RPC_HEAD}Content-Length: 1\r\n\r\nx`,
);
await refused;
let received = '';
next.on('data', (chunk) => (received += chunk.toString('utf8')));
const closed = new Promise<void>((resolve) => next.once('close', () => resolve()));
next.write(`${RPC_HEAD}Content-Length: 1024\r\n\r\n{"jsonrpc":"2.0"`);
await closed;
assert.doesNotMatch(received, /503/, 'the queued refusal held no slot');
} finally {
slowAnswer.resolve();
pipelined.destroy();
next.destroy();
await closeLoopbackServer(server);
}
});
Loading
Loading