Skip to content

Commit a51e934

Browse files
committed
fix(daemon): fail closed when the auth hook is silent about tenant
An auth hook that ran but returned no tenantId opted the deployment into tenant attestation; falling back to the client's own claim (RPC body meta.tenantId, aux-route x-agent-device-tenant header) let a holder of one valid shared token impersonate any tenant on /rpc and on the diagnostics/ upload/download routes. resolveTrustedTenant() in the new src/daemon/server/tenant-trust.ts is now the single seam both surfaces go through and the only place that computes the resulting identity: hook attests -> use it; no hook configured -> keep today's client-declared behavior (loopback/dev unchanged); hook configured but silent with a client-declared tenant -> refuse (401) instead of trusting the claim, and no raw client-declared metadata survives into the dispatched request in that case either. Fixes #2095
1 parent 4454aef commit a51e934

8 files changed

Lines changed: 428 additions & 17 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,13 @@
22

33
## Unreleased
44

5+
- Security (daemon, remote/proxy HTTP only): when `AGENT_DEVICE_HTTP_AUTH_HOOK` is configured and a
6+
request's hook result does not attest a `tenantId`, the daemon no longer falls back to trusting a
7+
client-declared tenant — RPC body `meta.tenantId`, or the `x-agent-device-tenant` header on the
8+
upload/artifact-download/diagnostics routes. That request is now refused (401) instead of running
9+
as whichever tenant the caller claimed, closing a shared-token impersonation path in multi-tenant
10+
deployments. Deployments with no hook configured (the local loopback CLI) are unaffected. A hook
11+
that needs per-request tenant scoping must attest `tenantId` in its own return value.
512
- Breaking (0.21): removed aggregate performance compatibility (`perf`, `perf sample`, `perf metrics`, the `metrics` alias, optionless `client.observability.perf()`, and SDK `area: 'metrics'`). Use `perf frames`, `perf memory sample`, `perf cpu profile start|stop|report`, or `perf trace start|stop`; removed CLI and raw daemon forms fail with this migration guidance.
613
- Breaking (0.21): removed legacy batch JSON steps with `positionals`/`flags`. Use `{"command":"...","input":{...}}`; rejected steps now include a concrete structured example.
714
- Breaking (0.21): removed the deprecated Node client `command.rotate` wrapper and its `RotateCommandOptions` / `RotateCommandResult` exports. Use `command.orientation`; the already-removed CLI `rotate` form keeps its targeted migration error.

‎src/__tests__/test-utils/env.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/** Restores a `process.env` entry a test changed, from the value captured before the change. */
2+
export function restoreEnv(key: string, previous: string | undefined): void {
3+
if (previous === undefined) delete process.env[key];
4+
else process.env[key] = previous;
5+
}
Lines changed: 347 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,347 @@
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 { createDaemonHttpServer } from '../server/http-server.ts';
6+
import { resolveSessionRequestLogPath } from '../session-store.ts';
7+
import { safeSessionName } from '../session-paths.ts';
8+
import { DAEMON_HTTP_TENANT_HEADER } from '../http-contract.ts';
9+
import type { DaemonRequest, DaemonResponse } from '../types.ts';
10+
import {
11+
closeLoopbackServer,
12+
listenOnLoopback,
13+
skipWhenLoopbackUnavailable,
14+
} from '../../__tests__/test-utils/loopback.ts';
15+
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
16+
import { restoreEnv } from '../../__tests__/test-utils/env.ts';
17+
18+
const DAEMON_TOKEN = 'daemon-secret';
19+
const DIAGNOSTICS_RECORD = '{"phase":"request_start"}\n{"phase":"request_failed"}\n';
20+
21+
function writeSilentAuthHook(root: string): string {
22+
const hookPath = path.join(root, 'silent-auth-hook.mjs');
23+
fs.writeFileSync(hookPath, 'export default function authHook() { return { ok: true }; }\n');
24+
return hookPath;
25+
}
26+
27+
const ATTESTED_TENANT_ID = 'tenant-real';
28+
29+
function writeAttestingAuthHook(root: string): string {
30+
const hookPath = path.join(root, 'attesting-auth-hook.mjs');
31+
fs.writeFileSync(
32+
hookPath,
33+
"export default function authHook() { return { tenantId: 'tenant-real' }; }\n",
34+
);
35+
return hookPath;
36+
}
37+
38+
async function withRpcServer(
39+
hookPath: string | undefined,
40+
run: (ctx: { baseUrl: string; observedRequests: DaemonRequest[] }) => Promise<void>,
41+
): Promise<void> {
42+
const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;
43+
if (hookPath) process.env.AGENT_DEVICE_HTTP_AUTH_HOOK = hookPath;
44+
else delete process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;
45+
46+
const observedRequests: DaemonRequest[] = [];
47+
const server = await createDaemonHttpServer({
48+
token: DAEMON_TOKEN,
49+
handleRequest: async (req): Promise<DaemonResponse> => {
50+
observedRequests.push(req);
51+
return { ok: true, data: { meta: req.meta } };
52+
},
53+
});
54+
try {
55+
const port = await listenOnLoopback(server);
56+
await run({ baseUrl: `http://127.0.0.1:${port}`, observedRequests });
57+
} finally {
58+
await closeLoopbackServer(server);
59+
restoreEnv('AGENT_DEVICE_HTTP_AUTH_HOOK', previousHook);
60+
}
61+
}
62+
63+
async function callRpc(
64+
baseUrl: string,
65+
payload: Record<string, unknown>,
66+
): Promise<{ status: number; body: Record<string, any> }> {
67+
const response = await fetch(`${baseUrl}/rpc`, {
68+
method: 'POST',
69+
headers: {
70+
authorization: `Bearer ${DAEMON_TOKEN}`,
71+
'content-type': 'application/json',
72+
},
73+
body: JSON.stringify(payload),
74+
});
75+
return { status: response.status, body: (await response.json()) as Record<string, any> };
76+
}
77+
78+
async function withDiagnosticsHookServer(
79+
hookPath: string | undefined,
80+
run: (ctx: { baseUrl: string; sessionsDir: string }) => Promise<void>,
81+
): Promise<void> {
82+
const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;
83+
if (hookPath) process.env.AGENT_DEVICE_HTTP_AUTH_HOOK = hookPath;
84+
else delete process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;
85+
86+
const stateDir = mkdtempForTestSync('agent-device-tenant-trust-diagnostics-');
87+
const sessionsDir = path.join(stateDir, 'sessions');
88+
const server = await createDaemonHttpServer({
89+
token: DAEMON_TOKEN,
90+
handleRequest: async (): Promise<DaemonResponse> => ({ ok: true, data: {} }),
91+
resolveRequestDiagnosticsPath: (ref) =>
92+
resolveSessionRequestLogPath(
93+
path.join(sessionsDir, safeSessionName(ref.session)),
94+
ref.requestId,
95+
),
96+
});
97+
try {
98+
const port = await listenOnLoopback(server);
99+
await run({ baseUrl: `http://127.0.0.1:${port}`, sessionsDir });
100+
} finally {
101+
await closeLoopbackServer(server);
102+
restoreEnv('AGENT_DEVICE_HTTP_AUTH_HOOK', previousHook);
103+
fs.rmSync(stateDir, { recursive: true, force: true });
104+
}
105+
}
106+
107+
function writeDiagnosticsRecord(sessionsDir: string, session: string, requestId: string): void {
108+
const recordPath = resolveSessionRequestLogPath(
109+
path.join(sessionsDir, safeSessionName(session)),
110+
requestId,
111+
);
112+
fs.mkdirSync(path.dirname(recordPath), { recursive: true });
113+
fs.writeFileSync(recordPath, DIAGNOSTICS_RECORD);
114+
}
115+
116+
function diagnosticsUrl(baseUrl: string, session: string, requestId: string): string {
117+
return `${baseUrl}/sessions/${encodeURIComponent(session)}/requests/${encodeURIComponent(requestId)}/diagnostics`;
118+
}
119+
120+
// --- RPC surface ---------------------------------------------------------
121+
122+
test('RPC: a hook configured but silent on tenant refuses a client-declared meta.tenantId', async (t) => {
123+
if (await skipWhenLoopbackUnavailable(t)) return;
124+
const root = mkdtempForTestSync('agent-device-tenant-trust-rpc-');
125+
try {
126+
const hookPath = writeSilentAuthHook(root);
127+
await withRpcServer(hookPath, async ({ baseUrl, observedRequests }) => {
128+
const response = await callRpc(baseUrl, {
129+
jsonrpc: '2.0',
130+
id: 'rpc-impersonate',
131+
method: 'agent_device.command',
132+
params: {
133+
command: 'session_list',
134+
positionals: [],
135+
meta: { tenantId: 'victim' },
136+
},
137+
});
138+
assert.equal(response.status, 401);
139+
assert.equal(response.body.error?.code, -32001);
140+
assert.equal(
141+
observedRequests.length,
142+
0,
143+
'the handler must never see the impersonated request',
144+
);
145+
});
146+
} finally {
147+
fs.rmSync(root, { recursive: true, force: true });
148+
}
149+
});
150+
151+
test('RPC: a hook configured but silent on tenant refuses a client-declared lease tenantId', async (t) => {
152+
if (await skipWhenLoopbackUnavailable(t)) return;
153+
const root = mkdtempForTestSync('agent-device-tenant-trust-rpc-lease-');
154+
try {
155+
const hookPath = writeSilentAuthHook(root);
156+
await withRpcServer(hookPath, async ({ baseUrl, observedRequests }) => {
157+
const response = await callRpc(baseUrl, {
158+
jsonrpc: '2.0',
159+
id: 'rpc-impersonate-lease',
160+
method: 'agent_device.lease.allocate',
161+
params: {
162+
tenantId: 'victim',
163+
runId: 'run-1',
164+
ttlMs: 60000,
165+
backend: 'android-instance',
166+
},
167+
});
168+
assert.equal(response.status, 401);
169+
assert.equal(response.body.error?.code, -32001);
170+
assert.equal(
171+
observedRequests.length,
172+
0,
173+
'the handler must never see the impersonated request',
174+
);
175+
});
176+
} finally {
177+
fs.rmSync(root, { recursive: true, force: true });
178+
}
179+
});
180+
181+
test('RPC: a hook that attests a tenant wins over a mismatched client-declared meta.tenantId', async (t) => {
182+
if (await skipWhenLoopbackUnavailable(t)) return;
183+
const root = mkdtempForTestSync('agent-device-tenant-trust-rpc-attest-');
184+
try {
185+
const hookPath = writeAttestingAuthHook(root);
186+
await withRpcServer(hookPath, async ({ baseUrl, observedRequests }) => {
187+
const response = await callRpc(baseUrl, {
188+
jsonrpc: '2.0',
189+
id: 'rpc-attested',
190+
method: 'agent_device.command',
191+
params: {
192+
command: 'session_list',
193+
positionals: [],
194+
meta: { tenantId: 'victim' },
195+
},
196+
});
197+
assert.equal(response.status, 200);
198+
assert.equal(observedRequests[0]?.meta?.tenantId, ATTESTED_TENANT_ID);
199+
});
200+
} finally {
201+
fs.rmSync(root, { recursive: true, force: true });
202+
}
203+
});
204+
205+
test('RPC: no hook configured keeps a client-declared meta.tenantId unchanged (regression)', async (t) => {
206+
if (await skipWhenLoopbackUnavailable(t)) return;
207+
await withRpcServer(undefined, async ({ baseUrl, observedRequests }) => {
208+
const response = await callRpc(baseUrl, {
209+
jsonrpc: '2.0',
210+
id: 'rpc-loopback',
211+
method: 'agent_device.command',
212+
params: {
213+
command: 'session_list',
214+
positionals: [],
215+
meta: { tenantId: 'tenant-x' },
216+
},
217+
});
218+
assert.equal(response.status, 200);
219+
assert.equal(observedRequests[0]?.meta?.tenantId, 'tenant-x');
220+
});
221+
});
222+
223+
// --- Auxiliary routes (request diagnostics) -------------------------------
224+
225+
test('aux route: a hook configured but silent on tenant refuses a client-declared header claiming another tenant', async (t) => {
226+
if (await skipWhenLoopbackUnavailable(t)) return;
227+
const root = mkdtempForTestSync('agent-device-tenant-trust-aux-');
228+
try {
229+
const hookPath = writeSilentAuthHook(root);
230+
await withDiagnosticsHookServer(hookPath, async ({ baseUrl, sessionsDir }) => {
231+
writeDiagnosticsRecord(sessionsDir, 'victim-tenant:default', 'abc123');
232+
const response = await fetch(diagnosticsUrl(baseUrl, 'victim-tenant:default', 'abc123'), {
233+
headers: {
234+
authorization: `Bearer ${DAEMON_TOKEN}`,
235+
[DAEMON_HTTP_TENANT_HEADER]: 'victim-tenant',
236+
},
237+
});
238+
assert.equal(response.status, 401);
239+
assert.equal((await response.text()).includes('request_start'), false);
240+
});
241+
} finally {
242+
fs.rmSync(root, { recursive: true, force: true });
243+
}
244+
});
245+
246+
test('aux route: a hook that attests a tenant wins over a mismatched client-declared header', async (t) => {
247+
if (await skipWhenLoopbackUnavailable(t)) return;
248+
const root = mkdtempForTestSync('agent-device-tenant-trust-aux-attest-');
249+
try {
250+
const hookPath = writeAttestingAuthHook(root);
251+
await withDiagnosticsHookServer(hookPath, async ({ baseUrl, sessionsDir }) => {
252+
writeDiagnosticsRecord(sessionsDir, `${ATTESTED_TENANT_ID}:default`, 'abc123');
253+
const owner = await fetch(
254+
diagnosticsUrl(baseUrl, `${ATTESTED_TENANT_ID}:default`, 'abc123'),
255+
{
256+
headers: {
257+
authorization: `Bearer ${DAEMON_TOKEN}`,
258+
[DAEMON_HTTP_TENANT_HEADER]: 'victim-tenant',
259+
},
260+
},
261+
);
262+
assert.equal(owner.status, 200);
263+
assert.equal(await owner.text(), DIAGNOSTICS_RECORD);
264+
});
265+
} finally {
266+
fs.rmSync(root, { recursive: true, force: true });
267+
}
268+
});
269+
270+
test('aux route: no hook configured keeps the header-declared tenant unchanged (regression)', async (t) => {
271+
if (await skipWhenLoopbackUnavailable(t)) return;
272+
await withDiagnosticsHookServer(undefined, async ({ baseUrl, sessionsDir }) => {
273+
writeDiagnosticsRecord(sessionsDir, 'tenant-a:default', 'abc123');
274+
const owner = await fetch(diagnosticsUrl(baseUrl, 'tenant-a:default', 'abc123'), {
275+
headers: {
276+
authorization: `Bearer ${DAEMON_TOKEN}`,
277+
[DAEMON_HTTP_TENANT_HEADER]: 'tenant-a',
278+
},
279+
});
280+
assert.equal(owner.status, 200);
281+
const otherTenant = await fetch(diagnosticsUrl(baseUrl, 'tenant-a:default', 'abc123'), {
282+
headers: {
283+
authorization: `Bearer ${DAEMON_TOKEN}`,
284+
[DAEMON_HTTP_TENANT_HEADER]: 'tenant-b',
285+
},
286+
});
287+
assert.equal(otherTenant.status, 401);
288+
});
289+
});
290+
291+
// --- Auxiliary routes (upload) --------------------------------------------
292+
293+
test('aux route (upload): a hook configured but silent on tenant refuses a client-declared header', async (t) => {
294+
if (await skipWhenLoopbackUnavailable(t)) return;
295+
const root = mkdtempForTestSync('agent-device-tenant-trust-upload-');
296+
const previousHook = process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;
297+
process.env.AGENT_DEVICE_HTTP_AUTH_HOOK = writeSilentAuthHook(root);
298+
const server = await createDaemonHttpServer({
299+
token: DAEMON_TOKEN,
300+
handleRequest: async (): Promise<DaemonResponse> => ({ ok: true, data: {} }),
301+
});
302+
try {
303+
const port = await listenOnLoopback(server);
304+
const response = await fetch(`http://127.0.0.1:${port}/upload`, {
305+
method: 'POST',
306+
headers: {
307+
authorization: `Bearer ${DAEMON_TOKEN}`,
308+
[DAEMON_HTTP_TENANT_HEADER]: 'victim-tenant',
309+
'x-artifact-type': 'file',
310+
'x-artifact-filename': 'demo.apk',
311+
'content-type': 'application/octet-stream',
312+
},
313+
body: Buffer.from('fake-apk'),
314+
});
315+
assert.equal(response.status, 401);
316+
} finally {
317+
await closeLoopbackServer(server);
318+
restoreEnv('AGENT_DEVICE_HTTP_AUTH_HOOK', previousHook);
319+
fs.rmSync(root, { recursive: true, force: true });
320+
}
321+
});
322+
323+
// --- Normalization parity between the two surfaces ------------------------
324+
325+
test('RPC: a whitespace-only meta.tenantId is admitted untenanted, not forwarded raw, under a silent hook', async (t) => {
326+
if (await skipWhenLoopbackUnavailable(t)) return;
327+
const root = mkdtempForTestSync('agent-device-tenant-trust-rpc-blank-');
328+
try {
329+
const hookPath = writeSilentAuthHook(root);
330+
await withRpcServer(hookPath, async ({ baseUrl, observedRequests }) => {
331+
const response = await callRpc(baseUrl, {
332+
jsonrpc: '2.0',
333+
id: 'rpc-blank-tenant',
334+
method: 'agent_device.command',
335+
params: {
336+
command: 'session_list',
337+
positionals: [],
338+
meta: { tenantId: ' ' },
339+
},
340+
});
341+
assert.equal(response.status, 200);
342+
assert.equal(observedRequests[0]?.meta?.tenantId, undefined);
343+
});
344+
} finally {
345+
fs.rmSync(root, { recursive: true, force: true });
346+
}
347+
});

0 commit comments

Comments
 (0)