Skip to content
Closed
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
4 changes: 4 additions & 0 deletions packages/contracts/src/daemon-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,10 @@ export const DAEMON_RPC_PROTOCOL_VERSION = 4;
* worst-case escaping. It also bounds the memory one unauthenticated connection can hold.
*/
export const DAEMON_REQUEST_MAX_BYTES = 64 * 1024 * 1024;
/** Time for receiving and authenticating an RPC before command execution begins. */
export const DAEMON_RPC_PREAUTH_TIMEOUT_MS = 5_000;
/** Maximum string ID length echoed in an RPC preauthorization timeout. */
export const DAEMON_RPC_PREAUTH_MAX_ID_LENGTH = 128;

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 @@ -9,7 +9,10 @@ const RPC_ANSWER_DEADLINE_MS = 1_000;

export type RpcErrorBody = {
id?: unknown;
error?: { code?: number; data?: { details?: { reason?: string } } };
error?: {
code?: number;
data?: { retriable?: boolean; details?: { reason?: string; dispatched?: string } };
};
};

/** One `agent_device.command` call over `/rpc`, as the daemon answered it. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,19 @@ test.each([
}),
);
});

test('a client-declared tenant does not make a local request remote', () => {
const request: DaemonRequest = {
token: 'test',
session: 'owned',
command: 'open',
positionals: [],
flags: { saveScript: '/host/a.ad' },
meta: { tenantId: 'tenant-a', scriptPublicationId: PUBLICATION_ID },
};
const result = restrictRemoteHttpRequest(request, false, undefined);

expect(result.meta?.tenantId).toBe('tenant-a');
expect(result.flags?.saveScript).toBe('/host/a.ad');
expect(result.internal?.publicNetworkOnly).toBeUndefined();
});
Comment thread
thymikee marked this conversation as resolved.
Resolved
184 changes: 176 additions & 8 deletions packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,176 @@
import http from 'node:http';
import assert from 'node:assert/strict';
import { test } from 'vitest';
import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit';
import { postRpcCommand, startRpcServer } from '../__tests__/http-server-rpc.fixtures.ts';
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { test, vi } from 'vitest';
import { createDaemonProxyServer } from '@agent-device/proxy';
import {
closeLoopbackServer,
listenOnLoopback,
mkdtempForTestSync,
skipWhenLoopbackUnavailable,
} from '@agent-device/test-kit';
import { createDaemonHttpServer } from './http-server.ts';
import {
postRpcCommand,
startRpcServer,
type RpcErrorBody,
} from '../__tests__/http-server-rpc.fixtures.ts';

test('unfinished RPC bodies exhaust a bounded ingress budget without dispatch', async (t) => {
test('preauthorization body deadline answers with a typed reason before dispatch', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
let dispatched = 0;
const { port, server } = await startRpcServer('budget-token', async () => {
dispatched += 1;
return { ok: true, data: {} };
});
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
const reached = new Promise<void>((resolve) => server.once('request', () => resolve()));
let request!: http.ClientRequest;
const response = new Promise<{ status: number; body: string }>((resolve, reject) => {
request = http.request({
host: '127.0.0.1',
port,
method: 'POST',
path: '/rpc',
headers: { 'content-type': 'application/json' },
});
request.on('response', (res) => {
const chunks: Buffer[] = [];
res.on('data', (chunk: Buffer) => chunks.push(chunk));
res.on('end', () =>
resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') }),
);
});
request.on('error', reject);
request.flushHeaders();
});
try {
await reached;
await vi.advanceTimersByTimeAsync(5_000);
const answered = await response;
const body = JSON.parse(answered.body) as {
error?: { data?: { details?: { reason?: string; dispatched?: string } } };
};
assert.equal(answered.status, 408);
assert.equal(body.error?.data?.details?.reason, 'RPC_PREAUTH_DEADLINE_EXCEEDED');
assert.equal(body.error?.data?.details?.dispatched, 'no');
assert.equal(dispatched, 0);
} finally {
vi.useRealTimers();
request.destroy();
await closeLoopbackServer(server);
}
});

test.for([
['proxy', 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', 0],
['daemon', 'RPC_PREAUTH_DEADLINE_EXCEEDED', 1],
] as const)(
'the %s auth deadline answers through the proxy and allows a fresh call',
async ([origin, reason, expectedDaemonCalls], t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const root = mkdtempForTestSync('rpc-preauth-id-');
const hookPath = path.join(root, 'auth-hook.mjs');
fs.writeFileSync(
hookPath,
`const entered = Promise.withResolvers();
const held = Promise.withResolvers();
export const authEntered = entered.promise;
export const releaseAuth = () => held.resolve({ tenantId: 'budget-tenant' });
export function holdAuth() {
entered.resolve();
return held.promise;
}
export default function authHook({ rpcRequest }) {
return rpcRequest.id === 'daemon-timeout' ? holdAuth() : { tenantId: 'budget-tenant' };
}
`,
);
const auth = (await import(pathToFileURL(hookPath).href)) as {
authEntered: Promise<void>;
holdAuth: () => Promise<{ tenantId: string }>;
releaseAuth: () => void;
};
let daemonCalls = 0;
let dispatched = 0;
const daemon = await createDaemonHttpServer({
token: 'budget-token',
env: { AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath },
cwd: process.cwd(),
handleRequest: async () => {
dispatched += 1;
return { ok: true, data: { reached: 'daemon-handler' } };
},
});
t.onTestFinished(() => closeLoopbackServer(daemon));
daemon.on('request', () => {
daemonCalls += 1;
});
const daemonPort = await listenOnLoopback(daemon);
const proxy = createDaemonProxyServer({
upstreamBaseUrl: `http://127.0.0.1:${daemonPort}`,
upstreamToken: 'budget-token',
authenticate: (request) =>
request.headers.get('x-request-id') === 'proxy-timeout'
? auth.holdAuth()
: { tenantId: 'budget-tenant' },
});
t.onTestFinished(() => closeLoopbackServer(proxy));
const proxyPort = await listenOnLoopback(proxy);
const post = (id: string) =>
fetch(`http://127.0.0.1:${proxyPort}/agent-device/rpc`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-request-id': id },
body: JSON.stringify({
jsonrpc: '2.0',
id,
method: 'agent_device.command',
params: { command: 'session_list' },
}),
signal: AbortSignal.timeout(2_000),
});

vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
t.onTestFinished(() => {
vi.useRealTimers();
auth.releaseAuth();
});
const id = `${origin}-timeout`;
const pending = post(id);
await Promise.race([
auth.authEntered,
pending.then((response) =>
assert.fail(`HTTP ${response.status} before entering ${origin} auth`),
),
]);
await vi.advanceTimersByTimeAsync(5_000);
const response = await pending;
assert.equal(response.status, 408);
const body = (await response.json()) as RpcErrorBody;
assert.equal(body.id, id);
assert.equal(body.error?.data?.details?.reason, reason);
assert.equal(body.error?.data?.details?.dispatched, 'no');
assert.equal(body.error?.data?.retriable, true);
assert.equal(daemonCalls, expectedDaemonCalls);
assert.equal(dispatched, 0);

vi.useRealTimers();
auth.releaseAuth();
const fresh = await post(`${origin}-fresh`);
assert.equal(fresh.status, 200);
assert.deepEqual(await fresh.json(), {
jsonrpc: '2.0',
id: `${origin}-fresh`,
result: { ok: true, data: { reached: 'daemon-handler' } },
});
assert.equal(daemonCalls, expectedDaemonCalls + 1);
assert.equal(dispatched, 1);
},
);

test('unfinished unauthenticated RPC bodies do not block authenticated dispatch', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
let dispatched = 0;
const { port, server } = await startRpcServer('budget-token', async () => {
Expand Down Expand Up @@ -34,10 +200,12 @@ test('unfinished RPC bodies exhaust a bounded ingress budget without dispatch',
held.push(request);
}
await ready;
const refused = await postRpcCommand(port, 'budget-token', 'overflow');
assert.equal(refused.status, 503);
assert.equal(refused.body.error?.data?.details?.reason, 'RPC_BODY_CAPACITY_EXCEEDED');
assert.equal(dispatched, 0);
const admitted = await postRpcCommand(port, 'budget-token', 'admitted');
assert.equal(admitted.status, 200);
assert.equal(dispatched, 1);
for (const request of held) request.destroy();
const afterDisconnect = await postRpcCommand(port, 'budget-token', 'after-disconnect');
Comment thread
thymikee marked this conversation as resolved.
Resolved
assert.equal(afterDisconnect.status, 200);
} finally {
for (const request of held) request.destroy();
await closeLoopbackServer(server);
Expand Down
Loading
Loading