Skip to content

Commit eb67f3b

Browse files
committed
fix(plugins): enforce connection provider admission (#4636)
* fix(plugins): admit connection providers from their host registry * test(plugins): cover routed connection admission * test(plugins): use explicit remote session fixtures * test(plugins): verify routed admission and cleanup * fix(connection): pass host environment through capability decisions * test(connection): isolate stored status output assertions * test(connection): register providers in lease fixtures * test(connection): colocate provider lease fixture
1 parent 99ce048 commit eb67f3b

13 files changed

Lines changed: 463 additions & 128 deletions

‎scripts/__tests__/help-conformance-sample-producers.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -498,7 +498,8 @@ export const SAMPLE_PRODUCERS: SampleProducer[] = [
498498
} satisfies ConnectVerification;
499499
return renderConnectSuccess({
500500
state,
501-
readiness: presentConnectReadiness(state, facts),
501+
readiness: presentConnectReadiness(state, facts, process.env),
502+
env: process.env,
502503
});
503504
} finally {
504505
restoreEnv('AGENT_DEVICE_HOME', previousHome);

‎src/__tests__/remote-connection.test.ts‎

Lines changed: 0 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1321,74 +1321,6 @@ test('deferred materialization allocates pending lease for devices', async () =>
13211321
fs.rmSync(tempRoot, { recursive: true, force: true });
13221322
});
13231323

1324-
test('deferred provider materialization forwards provider profile fields to lease allocation', async () => {
1325-
const { tempRoot, stateDir } = connectionWorkspace('agent-device-provider-lease-flags-');
1326-
const remoteConfigPath = path.join(tempRoot, 'browserstack.json');
1327-
fs.writeFileSync(
1328-
remoteConfigPath,
1329-
JSON.stringify({
1330-
tenant: 'browserstack',
1331-
runId: 'browserstack-run',
1332-
leaseProvider: 'browserstack',
1333-
leaseBackend: 'android-instance',
1334-
platform: 'android',
1335-
device: 'Google Pixel 8',
1336-
providerOsVersion: '14.0',
1337-
providerApp: '/tmp/WikipediaSample.apk',
1338-
providerProject: 'agent-device',
1339-
providerBuild: 'live-smoke',
1340-
}),
1341-
);
1342-
seedConnectionState({
1343-
stateDir,
1344-
state: {
1345-
session: 'adc-browserstack',
1346-
remoteConfigPath,
1347-
tenant: 'browserstack',
1348-
runId: 'browserstack-run',
1349-
leaseBackend: 'android-instance',
1350-
leaseProvider: 'browserstack',
1351-
platform: 'android',
1352-
},
1353-
});
1354-
const allocate = recordedLeaseAllocate({
1355-
leaseId: 'lease-browserstack',
1356-
backend: 'android-instance',
1357-
});
1358-
1359-
const materialized = await materializeRemoteConnectionForCommand({
1360-
command: 'open',
1361-
flags: {
1362-
json: true,
1363-
help: false,
1364-
version: false,
1365-
stateDir,
1366-
remoteConfig: remoteConfigPath,
1367-
tenant: 'browserstack',
1368-
runId: 'browserstack-run',
1369-
session: 'adc-browserstack',
1370-
leaseBackend: 'android-instance',
1371-
platform: 'android',
1372-
device: 'Google Pixel 8',
1373-
providerOsVersion: '14.0',
1374-
providerApp: '/tmp/WikipediaSample.apk',
1375-
providerProject: 'agent-device',
1376-
providerBuild: 'live-smoke',
1377-
},
1378-
client: createTestClient({ allocate: allocate.stub }),
1379-
});
1380-
1381-
assert.equal(materialized.flags.leaseId, 'lease-browserstack');
1382-
assert.equal(allocate.request?.platform, 'android');
1383-
assert.equal(allocate.request?.device, 'Google Pixel 8');
1384-
assert.equal(allocate.request?.providerApp, '/tmp/WikipediaSample.apk');
1385-
assert.equal(allocate.request?.providerOsVersion, '14.0');
1386-
assert.equal(allocate.request?.providerProject, 'agent-device');
1387-
assert.equal(allocate.request?.providerBuild, 'live-smoke');
1388-
1389-
fs.rmSync(tempRoot, { recursive: true, force: true });
1390-
});
1391-
13921324
test('deferred materialization reallocates when the persisted lease is inactive', async () => {
13931325
const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace(
13941326
'agent-device-connect-stale-lease-',

‎src/cli/commands/connection-lease-policy.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ vi.mock('../connection/provider-policy.ts', () => ({
3333

3434
function ttlFor(leaseProvider: string): number | undefined {
3535
const state = { leaseProvider } as RemoteConnectionState;
36-
return connectionLeasePolicyForState(state).ttlMs(state);
36+
return connectionLeasePolicyForState(state, {}).ttlMs(state, {});
3737
}
3838

3939
test.each([

‎src/cli/commands/connection-lease-policy.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,11 @@ const leaseDeferredCommands = new Set([
1919
'session',
2020
'shutdown',
2121
]);
22-
function remoteLeaseTtlMs(state: RemoteConnectionState): number | undefined {
23-
const capabilities = connectionProviderCapabilities(state.leaseProvider);
22+
function remoteLeaseTtlMs(
23+
state: RemoteConnectionState,
24+
env: NodeJS.ProcessEnv,
25+
): number | undefined {
26+
const capabilities = connectionProviderCapabilities(state.leaseProvider, env);
2427
return capabilities.leaseKind === 'proxy' ||
2528
capabilities.usesCloudWebDriverLease ||
2629
capabilities.holdsCloudDevice === true
@@ -30,7 +33,7 @@ function remoteLeaseTtlMs(state: RemoteConnectionState): number | undefined {
3033

3134
export type ConnectionLeasePolicy = {
3235
shouldAllocate(command: string): boolean;
33-
ttlMs(state: RemoteConnectionState): number | undefined;
36+
ttlMs(state: RemoteConnectionState, env: NodeJS.ProcessEnv): number | undefined;
3437
/** The id this client names a new lease with; without it the daemon mints one. */
3538
newLeaseId?(): string;
3639
resolveLeaseState(options: {
@@ -42,9 +45,12 @@ export type ConnectionLeasePolicy = {
4245
}): Promise<ResolvedLeaseState>;
4346
};
4447

45-
export function connectionLeasePolicyForState(state: RemoteConnectionState): ConnectionLeasePolicy {
48+
export function connectionLeasePolicyForState(
49+
state: RemoteConnectionState,
50+
env: NodeJS.ProcessEnv,
51+
): ConnectionLeasePolicy {
4652
if (state.leaseBackend === 'macos-app') return MACOS_APP_CONNECTION_LEASE_POLICY;
47-
const capabilities = connectionProviderCapabilities(state.leaseProvider);
53+
const capabilities = connectionProviderCapabilities(state.leaseProvider, env);
4854
if (capabilities.leaseKind === 'proxy') {
4955
return PROXY_CONNECTION_LEASE_POLICY;
5056
}

‎src/cli/commands/connection-lease-transaction.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,15 +114,17 @@ export async function acquireConnectionLease(options: {
114114
nextFlags: CliFlags;
115115
positionals?: string[];
116116
leaseLedger: LeaseLedger;
117+
env: NodeJS.ProcessEnv;
117118
}): Promise<{ state: RemoteConnectionState; changed: boolean }> {
118119
const { command, client, state, nextFlags, leaseLedger } = options;
119120
const deferredAppSelection = connectionProviderCapabilities(
120121
state.leaseProvider,
122+
options.env,
121123
).supportsDeferredAppSelection;
122124
const initialApp =
123125
deferredAppSelection && command === PUBLIC_COMMANDS.open ? options.positionals?.[0] : undefined;
124126
if (deferredAppSelection) delete nextFlags.providerApp;
125-
const leasePolicy = connectionLeasePolicyForState(state);
127+
const leasePolicy = connectionLeasePolicyForState(state, options.env);
126128
let nextState = state;
127129
let changed = false;
128130
if (leasePolicy.shouldAllocate(command)) {
@@ -135,6 +137,7 @@ export async function acquireConnectionLease(options: {
135137
initialApp,
136138
policy: leasePolicy,
137139
leaseLedger,
140+
env: options.env,
138141
});
139142
nextState = materialized.state;
140143
changed = materialized.changed;
@@ -184,6 +187,7 @@ async function materializeLeaseForCommand(options: {
184187
initialApp?: string;
185188
policy: ConnectionLeasePolicy;
186189
leaseLedger: LeaseLedger;
190+
env: NodeJS.ProcessEnv;
187191
}): Promise<{ state: RemoteConnectionState; changed: boolean }> {
188192
const { command, client, state, nextFlags, policy, leaseLedger } = options;
189193
const preliminaryLeaseBackend = state.leaseBackend ?? resolveRequestedLeaseBackend(nextFlags);
@@ -218,6 +222,7 @@ async function materializeLeaseForCommand(options: {
218222
options.initialApp,
219223
resolvedLeaseState.allocateBySpec,
220224
leaseLedger,
225+
options.env,
221226
);
222227
if (resolvedLeaseState.allocateBySpec) {
223228
const bound = await bindLeaseNamedDevice({
@@ -237,6 +242,7 @@ async function materializeLeaseForCommand(options: {
237242
options.initialApp,
238243
undefined,
239244
leaseLedger,
245+
options.env,
240246
),
241247
});
242248
nextState = bound.state;
@@ -357,6 +363,7 @@ async function allocateOrReuseLease(
357363
initialApp: string | undefined,
358364
allocateBySpec: boolean | undefined,
359365
leaseLedger: LeaseLedger,
366+
env: NodeJS.ProcessEnv,
360367
): Promise<{ lease: Lease; acquired: boolean }> {
361368
const connection = buildRemoteConnectionRequestMetadata(state);
362369
if (state.leaseId && state.leaseBackend === leaseBackend) {
@@ -365,7 +372,7 @@ async function allocateOrReuseLease(
365372
runId: state.runId,
366373
leaseBackend,
367374
...connection,
368-
ttlMs: policy.ttlMs(state),
375+
ttlMs: policy.ttlMs(state, env),
369376
});
370377
if (existing) return { lease: existing, acquired: false };
371378
}
@@ -386,7 +393,7 @@ async function allocateOrReuseLease(
386393
leaseBackend,
387394
...connection,
388395
...(allocateBySpec ? { deviceKey: undefined } : {}),
389-
ttlMs: policy.ttlMs(state),
396+
ttlMs: policy.ttlMs(state, env),
390397
...providerFlags,
391398
platform: state.platform ?? flags.platform,
392399
target: state.target ?? flags.target,
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
import assert from 'node:assert/strict';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
4+
import { afterEach, test, vi } from 'vitest';
5+
import { runCli } from '../../cli.ts';
6+
import { runCliCapture } from '../../__tests__/cli-capture.ts';
7+
import {
8+
hashRemoteConfigFile,
9+
readRemoteConnectionState,
10+
writeRemoteConnectionState,
11+
} from '@agent-device/remote/remote-connection-state';
12+
import {
13+
beginStdoutCapture,
14+
pluginHome,
15+
selectV2Plugin,
16+
v2RegistrationSource,
17+
} from '@agent-device/test-kit';
18+
19+
const provider = 'browserstack';
20+
const packageName = '@agent-device/browserstack';
21+
const capabilities = {
22+
leaseKind: 'direct-device-provider',
23+
requiresAppAttachment: false,
24+
requiresRemoteDaemon: false,
25+
supportsArtifacts: false,
26+
supportsDeferredAppSelection: false,
27+
supportsDirectPortReverse: false,
28+
usesCloudWebDriverLease: true,
29+
};
30+
31+
afterEach(() => vi.unstubAllEnvs());
32+
33+
function fixture(home: string, leaseProvider = provider) {
34+
const stateDir = path.join(home, 'state');
35+
const remoteConfigPath = path.join(home, 'remote.json');
36+
fs.writeFileSync(
37+
remoteConfigPath,
38+
JSON.stringify({
39+
tenant: 'team',
40+
runId: 'run-1',
41+
leaseProvider,
42+
leaseBackend: 'android-instance',
43+
platform: 'android',
44+
...(leaseProvider === 'ordinary-remote'
45+
? { daemonBaseUrl: 'https://daemon.example.test' }
46+
: {}),
47+
}),
48+
);
49+
return { stateDir, remoteConfigPath };
50+
}
51+
52+
function seedState(f: ReturnType<typeof fixture>, leaseProvider = provider) {
53+
const now = new Date().toISOString();
54+
writeRemoteConnectionState({
55+
stateDir: f.stateDir,
56+
state: {
57+
version: 1,
58+
session: 'default',
59+
remoteConfigPath: f.remoteConfigPath,
60+
remoteConfigHash: hashRemoteConfigFile(f.remoteConfigPath),
61+
tenant: 'team',
62+
runId: 'run-1',
63+
leaseProvider,
64+
leaseBackend: 'android-instance',
65+
platform: 'android',
66+
connectedAt: now,
67+
updatedAt: now,
68+
},
69+
});
70+
}
71+
72+
test.each(['missing', 'failed'] as const)(
73+
'routed %s vetted plugin fails before capability-based actions',
74+
async (kind) => {
75+
const { home, env } = pluginHome();
76+
if (kind === 'failed')
77+
selectV2Plugin(home, packageName, 'throw new Error("registration failed")');
78+
const f = fixture(home);
79+
const opts = { cwd: home, env: { ...env, AGENT_DEVICE_SESSION: 'default' } };
80+
const expected = kind === 'missing' ? 'plugin-not-installed' : 'plugin-unavailable';
81+
const connect = await runCliCapture(
82+
['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'],
83+
opts,
84+
);
85+
seedState(f);
86+
const status = await runCliCapture(
87+
['connection', 'status', '--state-dir', f.stateDir, '--json'],
88+
opts,
89+
);
90+
const snapshot = await runCliCapture(
91+
['snapshot', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'],
92+
opts,
93+
);
94+
const disconnected = await runCliCapture(
95+
['disconnect', '--state-dir', f.stateDir, '--json'],
96+
opts,
97+
);
98+
assert.equal(disconnected.code, null);
99+
assert.equal(readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' }), null);
100+
for (const result of [connect, status, snapshot]) {
101+
const parsed = JSON.parse(result.stdout);
102+
assert.equal(result.code, 1, result.stdout);
103+
assert.equal(parsed.error?.code, 'UNSUPPORTED_OPERATION', result.stdout);
104+
assert.equal(parsed.error?.details?.reason, expected, result.stdout);
105+
assert.deepEqual(result.calls, []);
106+
assert.doesNotMatch(result.stdout, /install-from-source|leaseId.*pending/);
107+
}
108+
},
109+
);
110+
111+
test('a generic remote profile remains connectable without a plugin', async () => {
112+
const { home, env } = pluginHome();
113+
const f = fixture(home, 'ordinary-remote');
114+
const result = await runCliCapture(
115+
['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'],
116+
{ cwd: home, env: { ...env, AGENT_DEVICE_SESSION: 'default' } },
117+
);
118+
assert.equal(result.code, null);
119+
assert.equal(
120+
readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' })?.leaseProvider,
121+
'ordinary-remote',
122+
);
123+
});
124+
125+
test('routed status uses capabilities from the supplied host store rather than the process store', async () => {
126+
const { home } = pluginHome();
127+
const ambient = pluginHome();
128+
vi.stubEnv('AGENT_DEVICE_HOME', ambient.home);
129+
selectV2Plugin(
130+
home,
131+
packageName,
132+
v2RegistrationSource(provider, {
133+
extra: `connection: { capabilities: ${JSON.stringify(capabilities)}, resolve() {}, verify() { return { provider: 'browserstack', service: 'BrowserStack', verificationMessage: 'verified' }; } },`,
134+
}),
135+
);
136+
const f = fixture(home);
137+
const capture = beginStdoutCapture();
138+
const sendToDaemon = vi.fn(async () => {
139+
throw new Error('unexpected daemon access');
140+
});
141+
try {
142+
const suppliedHost = {
143+
cwd: home,
144+
env: {
145+
AGENT_DEVICE_HOME: home,
146+
AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1',
147+
AGENT_DEVICE_SESSION: 'default',
148+
},
149+
};
150+
await runCli(
151+
['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir],
152+
{ sendToDaemon },
153+
suppliedHost,
154+
);
155+
assert.equal(
156+
readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' })?.leaseProvider,
157+
provider,
158+
);
159+
const statusOutputStart = capture.read().length;
160+
await runCli(
161+
['connection', 'status', '--state-dir', f.stateDir],
162+
{ sendToDaemon },
163+
suppliedHost,
164+
);
165+
const statusOutput = capture.read().slice(statusOutputStart);
166+
assert.match(statusOutput, /The first device command shown below will allocate one/);
167+
assert.doesNotMatch(statusOutput, /install-from-source/);
168+
assert.equal(sendToDaemon.mock.calls.length, 0);
169+
} finally {
170+
capture.restore();
171+
}
172+
});

0 commit comments

Comments
 (0)