Skip to content

Commit 27dd43a

Browse files
committed
fix(providers): skip the credential check for a shell without provider credentials
A client sends no provider credential fingerprint when its environment sets none of the provider's variables, so a daemon that holds the secrets keeps serving agent shells and Node workers that have none. A daemon started without credentials still refuses a shell that has them. The request router now requires the daemon's provider credentials, so daemon composition cannot drop them, and tests cover the client transport, the HTTP surface, and the router path.
1 parent e9cc283 commit 27dd43a

14 files changed

Lines changed: 326 additions & 19 deletions

‎src/commands/schema/cli-help.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -667,7 +667,7 @@ Rules:
667667
Use agent-device proxy for direct tunnel access to a Mac you control. Expose the printed proxy URL through cloudflared/ngrok, then run agent-device connect proxy with the tunnel URL and printed token before normal commands.
668668
Use Limrun, BrowserStack, and AWS Device Farm through local provider profiles; they do not accept a remote agent-device daemon URL.
669669
Device cloud credentials must be available before the command starts. Limrun uses LIMRUN_API_KEY, or the LIM_*_INSTANCE_* variables for an existing instance. BrowserStack uses BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY. AWS Device Farm uses the AWS CLI credential chain, including CI-provided AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/AWS_SESSION_TOKEN, AWS profiles, or web identity role variables.
670-
A local daemon keeps the Limrun and BrowserStack credentials it started with. When the shell holds different ones, the first command that allocates a lease refuses with reason provider-credentials-changed; run agent-device daemon stop with the same --state-dir, then rerun it.
670+
A local daemon keeps the Limrun and BrowserStack credentials it started with. When the shell holds different ones, the first command that allocates a lease refuses with reason provider-credentials-changed; run agent-device daemon stop with the same --state-dir, then rerun it. A shell that sets none of them uses the daemon's.
671671
Direct-provider connect performs read-only provider calls and saves active connection state only after verification succeeds. It never creates a device, instance, App Automate session, or AWS remote access session.
672672
connect without --session always creates a fresh remote session and prints that session in its next-step commands. Concurrent callers must pass the returned --session on every command; the ambient active connection is only a single-workflow convenience.
673673
To replace an existing connection, pass its returned session explicitly with --session <name> --force. --force without --session creates another fresh session and does not release or overwrite an unrelated active connection.
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
import { afterEach, expect, test, vi } from 'vitest';
2+
import fs from 'node:fs';
3+
import net from 'node:net';
4+
import { readProcessStartTime } from '@agent-device/host-kit/process';
5+
import { readVersion } from '@agent-device/host-kit/version';
6+
import { sendToDaemon } from '../daemon-client.ts';
7+
import { resolveDaemonPaths } from '../../daemon-resolution.ts';
8+
import {
9+
currentDaemonCodeSignature,
10+
startHttpDaemonFixture,
11+
} from '../../__tests__/test-utils/daemon-http-fixture.ts';
12+
import {
13+
closeLoopbackServer,
14+
listenOnLoopback,
15+
supportsLoopbackBind,
16+
} from '../../__tests__/test-utils/loopback.ts';
17+
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
18+
import { providerCredentialFingerprint } from '../../provider-credential-fingerprint.ts';
19+
import { LIMRUN_CREDENTIAL_VARIABLES } from '../../provider-limrun-credentials.ts';
20+
21+
const API_KEY = 'lim-secret-key';
22+
23+
afterEach(() => {
24+
vi.unstubAllEnvs();
25+
});
26+
27+
type CapturedDaemon = { bodies: string[]; close: () => Promise<void> };
28+
29+
test.sequential.for(['socket', 'http'] as const)(
30+
'a local %s daemon gets a fingerprint, never the key, only on lease_allocate with credentials',
31+
async (transport, t) => {
32+
if (!(await supportsLoopbackBind())) {
33+
t.skip('loopback listeners are not permitted in this environment');
34+
return;
35+
}
36+
clearCredentialEnv();
37+
vi.stubEnv('AGENT_DEVICE_DAEMON_BASE_URL', undefined);
38+
vi.stubEnv('AGENT_DEVICE_DAEMON_AUTH_TOKEN', undefined);
39+
const stateDir = mkdtempForTestSync('agent-device-provider-credentials-daemon-');
40+
const daemon = await startLocalDaemon(stateDir, transport);
41+
const send = (command: string) =>
42+
sendToDaemon({
43+
session: 'default',
44+
command,
45+
positionals: [],
46+
flags: { stateDir, daemonTransport: transport },
47+
meta: { requestId: `req-${command}`, leaseProvider: 'limrun', tenantId: 'tenant-a' },
48+
});
49+
50+
try {
51+
vi.stubEnv('LIMRUN_API_KEY', API_KEY);
52+
await send('lease_allocate');
53+
await send('devices');
54+
vi.stubEnv('LIMRUN_API_KEY', undefined);
55+
await send('lease_allocate');
56+
} finally {
57+
await daemon.close();
58+
fs.rmSync(stateDir, { recursive: true, force: true });
59+
}
60+
61+
expect(daemon.bodies.map(readFingerprint)).toEqual([
62+
providerCredentialFingerprint('limrun', { LIMRUN_API_KEY: API_KEY }),
63+
undefined,
64+
undefined,
65+
]);
66+
for (const body of daemon.bodies) expect(body).not.toContain(API_KEY);
67+
},
68+
);
69+
70+
test.sequential('a remote daemon gets no provider credential fingerprint', async (t) => {
71+
if (!(await supportsLoopbackBind())) {
72+
t.skip('loopback listeners are not permitted in this environment');
73+
return;
74+
}
75+
clearCredentialEnv();
76+
vi.stubEnv('LIMRUN_API_KEY', API_KEY);
77+
const remote = await startHttpDaemonFixture({});
78+
vi.stubEnv('AGENT_DEVICE_DAEMON_BASE_URL', `http://127.0.0.1:${remote.port}`);
79+
vi.stubEnv('AGENT_DEVICE_DAEMON_AUTH_TOKEN', 'remote-secret');
80+
81+
try {
82+
await sendToDaemon({
83+
session: 'default',
84+
command: 'lease_allocate',
85+
positionals: [],
86+
meta: { requestId: 'req-remote-lease', leaseProvider: 'limrun', tenantId: 'tenant-a' },
87+
});
88+
} finally {
89+
await closeLoopbackServer(remote.server);
90+
}
91+
92+
expect(remote.rpcRequests.map((rpc) => rpc.method)).toEqual(['agent_device.lease.allocate']);
93+
const body = JSON.stringify(remote.rpcRequests[0]);
94+
expect(readFingerprint(body)).toBe(undefined);
95+
expect(body).not.toContain(API_KEY);
96+
});
97+
98+
function readFingerprint(body: string): unknown {
99+
const parsed = JSON.parse(body) as {
100+
meta?: { providerCredentialFingerprint?: unknown };
101+
params?: { providerCredentialFingerprint?: unknown; meta?: Record<string, unknown> };
102+
};
103+
return (
104+
parsed.meta?.providerCredentialFingerprint ??
105+
parsed.params?.providerCredentialFingerprint ??
106+
parsed.params?.meta?.providerCredentialFingerprint
107+
);
108+
}
109+
110+
function clearCredentialEnv(): void {
111+
for (const name of LIMRUN_CREDENTIAL_VARIABLES) vi.stubEnv(name, undefined);
112+
}
113+
114+
async function startLocalDaemon(
115+
stateDir: string,
116+
transport: 'socket' | 'http',
117+
): Promise<CapturedDaemon> {
118+
if (transport === 'http') {
119+
const daemon = await startHttpDaemonFixture({});
120+
writeDaemonInfo(stateDir, { httpPort: daemon.port, transport });
121+
return {
122+
get bodies() {
123+
return daemon.rpcRequests.map((rpc) => JSON.stringify(rpc));
124+
},
125+
close: () => closeLoopbackServer(daemon.server),
126+
};
127+
}
128+
const bodies: string[] = [];
129+
const server = net.createServer((socket) => {
130+
socket.setEncoding('utf8');
131+
let body = '';
132+
socket.on('data', (chunk) => {
133+
body += chunk;
134+
if (!body.includes('\n')) return;
135+
bodies.push(body.trim());
136+
socket.end(`${JSON.stringify({ ok: true, data: {} })}\n`);
137+
});
138+
});
139+
writeDaemonInfo(stateDir, { port: await listenOnLoopback(server), transport });
140+
return { bodies, close: () => closeLoopbackServer(server) };
141+
}
142+
143+
function writeDaemonInfo(stateDir: string, endpoint: Record<string, unknown>): void {
144+
const paths = resolveDaemonPaths(stateDir);
145+
fs.mkdirSync(paths.baseDir, { recursive: true });
146+
fs.writeFileSync(
147+
paths.infoPath,
148+
`${JSON.stringify({
149+
...endpoint,
150+
token: 'local-secret',
151+
pid: process.pid,
152+
version: readVersion(),
153+
codeSignature: currentDaemonCodeSignature(),
154+
processStartTime: readProcessStartTime(process.pid) ?? undefined,
155+
})}\n`,
156+
'utf8',
157+
);
158+
}

‎src/daemon/__tests__/http-server-rpc-validation.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,54 @@ test('only local command RPC keeps the client developer dir', async (t) => {
366366
}
367367
});
368368

369+
test('only local lease allocation RPC keeps the provider credential fingerprint', async (t) => {
370+
if (await skipWhenLoopbackUnavailable(t)) return;
371+
const root = mkdtempForTestSync('agent-device-http-provider-credentials-');
372+
const fingerprintSeenBy = async (env: NodeJS.ProcessEnv): Promise<unknown> => {
373+
const received: DaemonRequest[] = [];
374+
const server = await createDaemonHttpServer({
375+
env,
376+
handleRequest: async (request): Promise<DaemonResponse> => {
377+
received.push(request);
378+
return { ok: true, data: {} };
379+
},
380+
});
381+
try {
382+
const response = await fetch(`http://127.0.0.1:${await listenOnLoopback(server)}/rpc`, {
383+
method: 'POST',
384+
headers: { 'content-type': 'application/json' },
385+
body: JSON.stringify({
386+
jsonrpc: '2.0',
387+
id: 'lease-allocate-fingerprint',
388+
method: 'agent_device.lease.allocate',
389+
params: {
390+
tenantId: 'tenant-test',
391+
runId: 'run-a',
392+
backend: 'ios-instance',
393+
provider: 'limrun',
394+
providerCredentialFingerprint: 'v1:0123456789abcdef',
395+
},
396+
}),
397+
});
398+
assert.equal(response.status, 200);
399+
assert.equal(received[0]?.command, 'lease_allocate');
400+
return received[0]?.meta?.providerCredentialFingerprint;
401+
} finally {
402+
await closeLoopbackServer(server);
403+
}
404+
};
405+
406+
try {
407+
assert.equal(await fingerprintSeenBy(localHttpEnvironment()), 'v1:0123456789abcdef');
408+
assert.equal(
409+
await fingerprintSeenBy(remoteHttpEnvironment(writeAllowingAuthHook(root))),
410+
undefined,
411+
);
412+
} finally {
413+
fs.rmSync(root, { recursive: true, force: true });
414+
}
415+
});
416+
369417
function writeAllowingAuthHook(root: string): string {
370418
const hookPath = path.join(root, 'auth-hook.mjs');
371419
fs.writeFileSync(hookPath, "export default () => ({ tenantId: 'tenant-test' });\n");

‎src/daemon/__tests__/human-control-router-fixture.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
44
import { buildSessionLeaseFromRequest } from '../lease-context.ts';
55
import { LeaseRegistry } from '../lease-registry.ts';
66
import { createRequestHandler } from '../request-router.ts';
7+
import { readDaemonProviderCredentials } from '../../provider-credential-fingerprint.ts';
78
import { tenantScopedSessionName } from '../session-tenant-scope.ts';
89
import { lifecycleDeviceRuntimeGateway } from './test-device-runtime-gateway.ts';
910
import { HUMAN_CONTROL_LEASE_REQUEST, humanControlRequest } from './human-control-fixtures.ts';
@@ -24,6 +25,7 @@ export function createHumanControlHarness() {
2425
token: 'test-token',
2526
sessionStore,
2627
leaseRegistry: registry,
28+
providerCredentials: readDaemonProviderCredentials({}, '/tmp'),
2729
deviceInventoryGateways: createTestDeviceInventoryGateways(),
2830
deviceRuntimeGateway: lifecycleDeviceRuntimeGateway,
2931
trackDownloadableArtifact: () => 'artifact-1',

‎src/daemon/__tests__/request-router-open.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ import {
7272
lifecycleDeviceRuntimeGateway,
7373
} from './test-device-runtime-gateway.ts';
7474
import { createRequestHandler as createProductionRequestHandler } from '../request-router.ts';
75+
import { readDaemonProviderCredentials } from '../../provider-credential-fingerprint.ts';
7576
import { resolveRequestExecutionLockPlan } from '../request-binding.ts';
7677
import { LeaseRegistry } from '../lease-registry.ts';
7778
import { ensureDeviceReady } from '../device/device-ready.ts';
@@ -443,6 +444,7 @@ test('close fails synchronously when root composition omits platform resource cl
443444
token: 'test-token',
444445
sessionStore,
445446
leaseRegistry: new LeaseRegistry(),
447+
providerCredentials: readDaemonProviderCredentials({}, '/tmp'),
446448
deviceRuntimeGateway: lifecycleDeviceRuntimeGateway,
447449
deviceInventoryGateways: createTestDeviceInventoryGateways(),
448450
trackDownloadableArtifact: () => 'artifact-id',
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import path from 'node:path';
2+
import { expect, test } from 'vitest';
3+
import { createTestDeviceInventoryGateways } from '../../__tests__/test-utils/device-inventory-gateways.ts';
4+
import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
5+
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
6+
import {
7+
providerCredentialFingerprint,
8+
readDaemonProviderCredentials,
9+
} from '../../provider-credential-fingerprint.ts';
10+
import { LeaseRegistry } from '../lease-registry.ts';
11+
import { createRequestHandler } from './test-device-runtime-gateway.ts';
12+
13+
const DAEMON_ENV = { LIMRUN_API_KEY: 'lim-key' };
14+
15+
test.for([
16+
[{ LIMRUN_API_KEY: 'lim-rotated' }, 'provider-credentials-changed', 0],
17+
[DAEMON_ENV, undefined, 1],
18+
] as const)(
19+
'the router hands the daemon provider credentials to lease allocation (shell %j)',
20+
async ([shellEnv, reason, allocations]) => {
21+
const stateDir = mkdtempForTestSync('agent-device-router-provider-credentials-');
22+
let allocated = 0;
23+
const handler = createRequestHandler({
24+
logPath: path.join(stateDir, 'daemon.log'),
25+
token: 'test-token',
26+
sessionStore: makeSessionStore('agent-device-router-provider-credentials-store-'),
27+
leaseRegistry: new LeaseRegistry(),
28+
deviceInventoryGateways: createTestDeviceInventoryGateways(),
29+
providerCredentials: readDaemonProviderCredentials(DAEMON_ENV, stateDir),
30+
leaseLifecycleProvider: {
31+
allocate: async () => {
32+
allocated += 1;
33+
return {};
34+
},
35+
},
36+
trackDownloadableArtifact: () => 'artifact-id',
37+
});
38+
39+
const response = await handler({
40+
token: 'test-token',
41+
session: 'default',
42+
command: 'lease_allocate',
43+
positionals: [],
44+
flags: {},
45+
meta: {
46+
requestId: 'req-provider-credentials',
47+
tenantId: 'tenant-a',
48+
runId: 'run-a',
49+
clientId: 'client-a',
50+
leaseBackend: 'ios-instance',
51+
leaseProvider: 'limrun',
52+
providerCredentialFingerprint: providerCredentialFingerprint('limrun', shellEnv),
53+
},
54+
});
55+
56+
expect(response.ok ? undefined : response.error.details?.reason).toBe(reason);
57+
expect(allocated).toBe(allocations);
58+
},
59+
);

‎src/daemon/__tests__/test-device-runtime-gateway.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import path from 'node:path';
12
import { vi } from 'vitest';
23
import {
34
type ApplicationLifecycleOperationFacts,
@@ -25,6 +26,7 @@ import { withClientReplayScriptSources } from '../../__tests__/test-utils/replay
2526
import type { DaemonInvokeFn } from '../daemon-request.ts';
2627
import { clearAndroidObservationFixture } from './android-observation-fixture.ts';
2728
import { platformResourceCleanup } from '../../platform-runtime-resource-cleanup.ts';
29+
import { readDaemonProviderCredentials } from '../../provider-credential-fingerprint.ts';
2830

2931
const unavailable = Object.freeze({
3032
available: false as const,
@@ -220,15 +222,20 @@ export const unavailableBindExactDevice: BindExactDeviceRuntime = async (
220222
);
221223

222224
export function createRequestHandler(
223-
deps: Omit<RequestRouterDeps, 'deviceRuntimeGateway'> &
224-
Partial<Pick<RequestRouterDeps, 'deviceRuntimeGateway'>>,
225+
deps: Omit<RequestRouterDeps, 'deviceRuntimeGateway' | 'providerCredentials'> &
226+
Partial<Pick<RequestRouterDeps, 'deviceRuntimeGateway' | 'providerCredentials'>>,
225227
) {
226-
const { deviceRuntimeGateway = unavailableDeviceRuntimeGateway, ...rest } = deps;
228+
const {
229+
deviceRuntimeGateway = unavailableDeviceRuntimeGateway,
230+
providerCredentials = readDaemonProviderCredentials({}, path.dirname(deps.logPath)),
231+
...rest
232+
} = deps;
227233
const handle = createProductionRequestHandler({
228234
androidObservation: clearAndroidObservationFixture,
229235
platformResourceCleanup,
230236
...rest,
231237
deviceRuntimeGateway,
238+
providerCredentials,
232239
});
233240
// #1802: stand in for the client that reads a replay script and sends its content, so router
234241
// cases keep naming a path while the daemon still sees only bundled sources.

‎src/daemon/handlers/__tests__/lease.test.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -279,11 +279,22 @@ test.for([
279279
},
280280
);
281281

282-
test('a request without a fingerprint is not checked', async () => {
283-
const outcome = await allocateWithDaemonEnv(providerAllocateRequest('limrun', undefined), {
284-
LIMRUN_API_KEY: 'lim-key',
285-
});
282+
test('a daemon holding credentials allocates for a shell with none', async () => {
283+
const outcome = await allocateWithDaemonEnv(
284+
providerAllocateRequest('limrun', providerCredentialFingerprint('limrun', {})),
285+
{ LIMRUN_API_KEY: 'lim-key' },
286+
);
286287

287288
assert.equal(outcome.error, undefined);
288289
assert.equal(outcome.allocations, 1);
289290
});
291+
292+
test('a daemon started without credentials refuses a shell that has them', async () => {
293+
const outcome = await allocateWithDaemonEnv(
294+
providerAllocateRequest('limrun', providerCredentialFingerprint('limrun', LIMRUN_ATTACH_ENV)),
295+
{},
296+
);
297+
298+
assert.equal(outcome.allocations, 0);
299+
assert.equal(outcome.error?.details?.reason, 'provider-credentials-changed');
300+
});

‎src/daemon/request-router.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ export type RequestRouterDeps = {
107107
hostDiagnostics?: HostDiagnostics;
108108
providerRuntimeIds?: readonly string[];
109109
providerRuntimeRequiredIds?: readonly string[];
110-
providerCredentials?: DaemonProviderCredentials;
110+
providerCredentials: DaemonProviderCredentials;
111111
leaseLifecycleProvider?: LeaseLifecycleProvider;
112112
cloudArtifactProvider?: CloudArtifactProvider;
113113
providerAppCatalog?: ProviderAppCatalog;

0 commit comments

Comments
 (0)