Skip to content

Commit a0ac012

Browse files
committed
fix(providers): read each provider's credentials once and load the fingerprint lazily
- The fingerprint hashes the exact values each provider's own reader uses (BrowserStack values as read, Limrun values trimmed), so a credential that differs only in whitespace cannot pass as the daemon's. - providers.ts is a leaf again: it holds the BrowserStack variable names and their non-throwing reader; the throwing require moves next to its consumers. - The client loads the fingerprint module only for a local lease_allocate, keeping both eager-closure budgets. - Provider lookup uses a Map, so inherited object keys are not providers. - A daemon without a provider's credentials records none and says so in the refusal; the hint gives the exact stop command once. - Document that a daemon with an HTTP auth hook treats every caller as remote. - Tests: exact-value hashing, inherited keys, a reachable no-credentials case, and a startup-level test that the daemon compares against its own env.
1 parent 27dd43a commit a0ac012

17 files changed

Lines changed: 181 additions & 80 deletions

‎packages/provider-webdriver/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import type { CloudWebDriverRuntime } from './runtime.ts';
2020
export { CLOUD_WEBDRIVER_PROVIDERS };
2121
export { readAwsDeviceFarmRegionFromArn };
2222
export { parseBrowserStackAppReference } from './browserstack.ts';
23+
export { requireBrowserStackCredentials } from './provider-definitions.ts';
2324
export { rejectBrowserStackOnlyDeviceFeatures } from './browserstack-device-features.ts';
2425
export type { CloudWebDriverKnownProviderName } from './providers.ts';
2526
export type { ProviderWebDriverDependencies, RunHostCommand } from './dependencies.ts';

‎packages/provider-webdriver/src/provider-definitions.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,9 @@ import {
2323
rejectBrowserStackOnlyDeviceFeatures,
2424
} from './browserstack-device-features.ts';
2525
import {
26+
BROWSERSTACK_CREDENTIAL_VARIABLES,
2627
CLOUD_WEBDRIVER_PROVIDERS,
27-
requireBrowserStackCredentials,
28+
readBrowserStackCredentials,
2829
type CloudWebDriverKnownProviderName,
2930
} from './providers.ts';
3031
import { readAwsDeviceFarmRegionFromArn } from './connection-verification.ts';
@@ -301,3 +302,15 @@ function readAwsInteractionMode(
301302
function dasherize(value: string): string {
302303
return value.replaceAll(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
303304
}
305+
306+
export function requireBrowserStackCredentials(
307+
env: Readonly<Record<string, string | undefined>>,
308+
consumer: string,
309+
): { username: string; accessKey: string } {
310+
const { username, accessKey } = readBrowserStackCredentials(env);
311+
if (username && accessKey) return { username, accessKey };
312+
const missing = username
313+
? BROWSERSTACK_CREDENTIAL_VARIABLES.accessKey
314+
: BROWSERSTACK_CREDENTIAL_VARIABLES.username;
315+
throw new AppError('INVALID_ARGS', `${consumer} requires ${missing} in the environment.`);
316+
}

‎packages/provider-webdriver/src/providers.ts‎

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import { AppError } from '@agent-device/kernel/errors';
2-
31
export const CLOUD_WEBDRIVER_PROVIDERS = {
42
browserStack: 'browserstack',
53
awsDeviceFarm: 'aws-device-farm',
@@ -22,19 +20,13 @@ export const BROWSERSTACK_CREDENTIAL_VARIABLES = {
2220
accessKey: 'BROWSERSTACK_ACCESS_KEY',
2321
} as const;
2422

25-
/** The one reader of BrowserStack credentials in the environment. */
26-
export function requireBrowserStackCredentials(
23+
/** The BrowserStack credentials in the environment, exactly as every consumer and the fingerprint use them. */
24+
export function readBrowserStackCredentials(
2725
env: Readonly<Record<string, string | undefined>>,
28-
consumer: string,
29-
): { username: string; accessKey: string } {
30-
const read = (name: string): string => {
31-
const value = env[name];
32-
if (value) return value;
33-
throw new AppError('INVALID_ARGS', `${consumer} requires ${name} in the environment.`);
34-
};
26+
): Readonly<{ username?: string; accessKey?: string }> {
3527
return {
36-
username: read(BROWSERSTACK_CREDENTIAL_VARIABLES.username),
37-
accessKey: read(BROWSERSTACK_CREDENTIAL_VARIABLES.accessKey),
28+
username: env[BROWSERSTACK_CREDENTIAL_VARIABLES.username] || undefined,
29+
accessKey: env[BROWSERSTACK_CREDENTIAL_VARIABLES.accessKey] || undefined,
3830
};
3931
}
4032

‎src/cli/connection/cloud-webdriver-profile.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ import {
33
parseBrowserStackAppReference,
44
readAwsDeviceFarmRegionFromArn,
55
rejectBrowserStackOnlyDeviceFeatures,
6+
requireBrowserStackCredentials,
67
type CloudWebDriverKnownProviderName,
78
} from '@agent-device/provider-webdriver';
8-
import { requireBrowserStackCredentials } from '@agent-device/provider-webdriver/providers';
99
import type { RemoteConfigProfile } from '../../remote/remote-config-schema.ts';
1010
import { AppError } from '@agent-device/kernel/errors';
1111
import type { PlatformSelector } from '@agent-device/kernel/device';

‎src/cli/connection/connect-provider-adapters.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { CliFlags } from '@agent-device/contracts/command';
22
import type { ProviderConnectionVerification } from '@agent-device/contracts/remote';
33
import { verifyLimrunConnection } from '@agent-device/provider-limrun';
44
import { AppError } from '@agent-device/kernel/errors';
5-
import { requireBrowserStackCredentials } from '@agent-device/provider-webdriver/providers';
5+
import { requireBrowserStackCredentials } from '@agent-device/provider-webdriver';
66
import { providerWebDriver } from '../../provider-webdriver.ts';
77
import { resolveRemoteConfigProfile } from '../../remote/remote-config.ts';
88
import { readVersion } from '@agent-device/host-kit/version';

‎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. A shell that sets none of them uses the daemon's.
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 the command. A shell that sets none of them uses the daemon's. A daemon with an HTTP auth hook serves remote callers and does not compare.
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.

‎src/daemon-client/daemon-client.ts‎

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ import {
3131
import { sendRequest } from './daemon-client-transport.ts';
3232
import { isRemoteDaemon, type DaemonInfo } from './daemon-client-metadata.ts';
3333
import { leaseScopeFromRequest } from '@agent-device/contracts/lease-scope';
34-
import { providerCredentialFingerprint } from '../provider-credential-fingerprint.ts';
3534

3635
export type DaemonRequest = SharedDaemonRequest;
3736
export type DaemonResponse = SharedDaemonResponse;
@@ -80,6 +79,7 @@ export async function sendToDaemon(
8079
info,
8180
requestId,
8281
debug,
82+
await readLocalProviderCredentialFingerprint(requestWithoutAuthFlag, info),
8383
);
8484
emitDiagnostic({
8585
level: 'info',
@@ -123,6 +123,7 @@ function buildTransportRequest(
123123
info: DaemonInfo,
124124
requestId: string,
125125
debug: boolean,
126+
providerCredentialFingerprint: string | undefined,
126127
): DaemonRequest {
127128
return {
128129
...request,
@@ -131,30 +132,32 @@ function buildTransportRequest(
131132
token: info.token,
132133
meta: {
133134
...buildTransportRequestMeta(request, preparedRemoteRequest, requestId, debug),
134-
...buildLocalHostEnvMeta(request, info),
135+
...buildLocalHostEnvMeta(info),
136+
providerCredentialFingerprint,
135137
},
136138
};
137139
}
138140

139-
// A developer dir is a path on the client's host, and a remote daemon reads provider credentials
140-
// from its own host, so only a local daemon receives either.
141-
function buildLocalHostEnvMeta(
141+
// A remote daemon reads provider credentials from its own host, so only a local daemon is asked
142+
// to compare them, and only when a lease is allocated.
143+
async function readLocalProviderCredentialFingerprint(
142144
request: Omit<DaemonRequest, 'token'>,
143145
info: DaemonInfo,
144-
): Pick<NonNullable<DaemonRequest['meta']>, 'developerDir' | 'providerCredentialFingerprint'> {
145-
if (isRemoteDaemon(info)) {
146-
return { developerDir: undefined, providerCredentialFingerprint: undefined };
147-
}
146+
): Promise<string | undefined> {
147+
if (isRemoteDaemon(info) || request.command !== 'lease_allocate') return undefined;
148+
const provider = leaseScopeFromRequest(request).leaseProvider;
149+
if (!provider) return undefined;
150+
const { providerCredentialFingerprint } = await import('../provider-credential-fingerprint.ts');
151+
return providerCredentialFingerprint(provider, process.env);
152+
}
153+
154+
// A developer dir is a path on the client's host, so only a local daemon can use it.
155+
function buildLocalHostEnvMeta(
156+
info: DaemonInfo,
157+
): Pick<NonNullable<DaemonRequest['meta']>, 'developerDir'> {
148158
const developerDir = process.env.DEVELOPER_DIR;
149-
const leaseProvider =
150-
request.command === 'lease_allocate' ? leaseScopeFromRequest(request).leaseProvider : undefined;
151-
const fingerprint = leaseProvider
152-
? providerCredentialFingerprint(leaseProvider, process.env)
153-
: undefined;
154-
return {
155-
...(developerDir !== undefined ? { developerDir } : {}),
156-
providerCredentialFingerprint: fingerprint,
157-
};
159+
if (isRemoteDaemon(info)) return { developerDir: undefined };
160+
return developerDir !== undefined ? { developerDir } : {};
158161
}
159162

160163
function buildTransportRequestMeta(

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -289,12 +289,16 @@ test('a daemon holding credentials allocates for a shell with none', async () =>
289289
assert.equal(outcome.allocations, 1);
290290
});
291291

292-
test('a daemon started without credentials refuses a shell that has them', async () => {
292+
test('a daemon started without BrowserStack credentials refuses a shell that has them', async () => {
293293
const outcome = await allocateWithDaemonEnv(
294-
providerAllocateRequest('limrun', providerCredentialFingerprint('limrun', LIMRUN_ATTACH_ENV)),
294+
providerAllocateRequest(
295+
'browserstack',
296+
providerCredentialFingerprint('browserstack', BROWSERSTACK_ENV),
297+
),
295298
{},
296299
);
297300

298301
assert.equal(outcome.allocations, 0);
299302
assert.equal(outcome.error?.details?.reason, 'provider-credentials-changed');
303+
assert.match(String(outcome.error?.message), /started without the browserstack credentials/);
300304
});

‎src/daemon/handlers/lease.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -283,15 +283,18 @@ function assertProviderCredentialsUnchanged(
283283
requested: string | undefined,
284284
daemon: DaemonProviderCredentials | undefined,
285285
): void {
286-
const current = provider ? daemon?.fingerprints[provider] : undefined;
287-
if (!daemon || !requested || !current || requested === current) return;
286+
if (!daemon || !provider || !requested) return;
287+
const current = daemon.fingerprints[provider];
288+
if (requested === current) return;
288289
throw new AppError(
289290
'INVALID_ARGS',
290-
`The running daemon holds different ${provider} credentials than this shell.`,
291+
current
292+
? `The running daemon holds different ${provider} credentials than this shell.`
293+
: `The running daemon was started without the ${provider} credentials this shell holds.`,
291294
{
292295
reason: 'provider-credentials-changed',
293296
provider,
294-
hint: `The daemon was started with different credentials than this shell. Stop it (agent-device daemon stop --state-dir ${shellQuoteIfNeeded(daemon.stateDir)}), then rerun the command so a daemon starts with the current environment.`,
297+
hint: `Stop it with agent-device daemon stop --state-dir ${shellQuoteIfNeeded(daemon.stateDir)}, then rerun the command so a new daemon starts with this shell's environment.`,
295298
},
296299
);
297300
}

‎src/daemon/server/daemon-runtime-interactor-composition.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { setActiveProviderDeviceRuntimes } from '../../provider-device-runtime.t
66
import { IOS_SIMULATOR } from '../../__tests__/test-utils/device-fixtures.ts';
77
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
88
import { createDaemonProviderRuntimeComposition } from '../../provider-device-runtimes.ts';
9+
import { providerCredentialFingerprint } from '../../provider-credential-fingerprint.ts';
910
import {
1011
DAEMON_STARTUP_EXIT_CODES,
1112
tryAcquireDaemonRegistration,
@@ -89,6 +90,55 @@ test('daemon startup composes the interactor resolution the daemon resolves thro
8990
}
9091
});
9192

93+
test('daemon startup compares lease credentials with its own startup environment', async () => {
94+
const stateDir = mkdtempForTestSync('agent-device-daemon-credential-composition-');
95+
const daemonEnv = { BROWSERSTACK_USERNAME: 'user', BROWSERSTACK_ACCESS_KEY: 'key-1' };
96+
const runtime = await startDaemonRuntime({
97+
env: {
98+
...process.env,
99+
...daemonEnv,
100+
AGENT_DEVICE_STATE_DIR: stateDir,
101+
AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0',
102+
AGENT_DEVICE_DAEMON_SERVER_MODE: 'http',
103+
},
104+
exit: () => {},
105+
registerProcessHandlers: false,
106+
stderr: { write: () => {} },
107+
stdout: { write: () => {} },
108+
});
109+
try {
110+
const { httpPort, token } = JSON.parse(
111+
fs.readFileSync(resolveDaemonPaths(stateDir).infoPath, 'utf8'),
112+
) as { httpPort: number; token: string };
113+
const allocate = async (env: Record<string, string>) =>
114+
await (
115+
await fetch(`http://127.0.0.1:${httpPort}/rpc`, {
116+
method: 'POST',
117+
headers: { 'content-type': 'application/json' },
118+
body: JSON.stringify({
119+
jsonrpc: '2.0',
120+
id: 1,
121+
method: 'agent_device.lease.allocate',
122+
params: {
123+
token,
124+
tenantId: 'tenant',
125+
runId: 'run',
126+
leaseProvider: 'browserstack',
127+
providerCredentialFingerprint: providerCredentialFingerprint('browserstack', env),
128+
},
129+
}),
130+
})
131+
).text();
132+
133+
expect(await allocate({ ...daemonEnv, BROWSERSTACK_ACCESS_KEY: 'key-2' })).toContain(
134+
'provider-credentials-changed',
135+
);
136+
expect(await allocate(daemonEnv)).not.toContain('provider-credentials-changed');
137+
} finally {
138+
await runtime?.shutdown();
139+
}
140+
});
141+
92142
test('a daemon attempt losing the lock shuts down every constructed provider', async () => {
93143
const stateDir = mkdtempForTestSync('daemon-held-lock-');
94144
const held = await tryAcquireDaemonRegistration(resolveDaemonPaths(stateDir));

0 commit comments

Comments
 (0)