Skip to content

Commit 2c7a8d0

Browse files
committed
refactor(11a-2c): fake the provider-credentials and provider-admission ports
Daemon suites treat the credential fingerprint as opaque — they assert refusal/reuse on equality, never digest content — so request-router-open, human-control-router-fixture, and the router fixture default now inject a package-local fixture at DaemonProviderCredentials that digests the given environment. The lease suite's provider-credentials family asserts the real reader's provider/manifest-aware digest semantics (and the plugin.fixtures manifest registry), so it moves to the root-owned composition subtree as lease-provider-credentials.test.ts. Provider ownership arrives through the daemon's own ProviderDeviceAdmission install point: snapshot-settings-handler and session-relaunch-close install a package-local admission over runtime fakes instead of the root ambient provider-runtime scope.
1 parent 72f2bfb commit 2c7a8d0

9 files changed

Lines changed: 321 additions & 237 deletions
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
import assert from 'node:assert/strict';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
4+
import { test } from 'vitest';
5+
import { handleLeaseCommands } from '../../../daemon/handlers/lease.ts';
6+
import { LeaseRegistry } from '../../../daemon/lease-registry.ts';
7+
import type { DaemonRequest } from '../../../daemon/daemon-request.ts';
8+
import { makeSessionStore } from '../../../daemon/__tests__/support/store-factory.ts';
9+
import { AppError } from '@agent-device/kernel/errors';
10+
import {
11+
providerCredentialFingerprint,
12+
readDaemonProviderCredentials,
13+
} from '../../../provider-credential-fingerprint.ts';
14+
import { pluginHome, selectPluginManifest } from '../../../plugins/plugin.fixtures.ts';
15+
16+
/**
17+
* Lease refusal compares the client's credential fingerprint against the digest the daemon
18+
* computes from its own startup environment through the real root fingerprint reader and the
19+
* installed-plugin manifest registry. Those digests and manifest lookups are the composition
20+
* this suite pins, so it lives root-owned; lease mechanics stay in the daemon suite.
21+
*/
22+
23+
function allocateRequest(): DaemonRequest {
24+
return {
25+
token: 'test-token',
26+
session: 'lease-ttl-test',
27+
command: 'lease_allocate',
28+
positionals: [],
29+
flags: {},
30+
meta: {
31+
tenantId: 'tenant-a',
32+
runId: 'run-a',
33+
clientId: 'client-a',
34+
leaseBackend: 'android-instance',
35+
leaseProvider: 'cloud',
36+
},
37+
};
38+
}
39+
40+
const LIMRUN_ATTACH_ENV = {
41+
LIMRUN_API_KEY: 'lim-key',
42+
LIM_IOS_INSTANCE_URL: 'https://region.limrun.example/v1/ios_x/api',
43+
LIM_IOS_INSTANCE_TOKEN: 'ios-token',
44+
};
45+
const BROWSERSTACK_ENV = { BROWSERSTACK_USERNAME: 'user', BROWSERSTACK_ACCESS_KEY: 'key-1' };
46+
47+
function providerAllocateRequest(
48+
leaseProvider: string,
49+
providerCredentialFingerprint: string | undefined,
50+
leaseBackend: 'ios-instance' | 'android-instance' = 'ios-instance',
51+
): DaemonRequest {
52+
const request = allocateRequest();
53+
return {
54+
...request,
55+
meta: {
56+
...request.meta,
57+
leaseProvider,
58+
leaseBackend,
59+
providerCredentialFingerprint,
60+
},
61+
};
62+
}
63+
64+
async function allocateWithDaemonEnv(
65+
req: DaemonRequest,
66+
daemonEnv: Record<string, string>,
67+
): Promise<{ allocations: number; error?: AppError }> {
68+
const registry = new LeaseRegistry();
69+
let allocations = 0;
70+
try {
71+
await handleLeaseCommands({
72+
req,
73+
sessionName: req.session,
74+
sessionStore: makeSessionStore('agent-device-provider-credentials-'),
75+
leaseRegistry: registry,
76+
providerCredentials: readDaemonProviderCredentials(daemonEnv, '/tmp/agent device state'),
77+
leaseLifecycleProvider: {
78+
allocate: async () => {
79+
allocations += 1;
80+
return {};
81+
},
82+
},
83+
});
84+
} catch (error) {
85+
assert.deepEqual(registry.listActiveLeases(), []);
86+
return { allocations, error: error as AppError };
87+
}
88+
return { allocations };
89+
}
90+
91+
test('a daemon started with only LIMRUN_API_KEY refuses a shell with instance variables before allocation', async () => {
92+
const outcome = await allocateWithDaemonEnv(
93+
providerAllocateRequest('limrun', providerCredentialFingerprint('limrun', LIMRUN_ATTACH_ENV)),
94+
{ LIMRUN_API_KEY: 'lim-key' },
95+
);
96+
97+
assert.equal(outcome.allocations, 0);
98+
assert.equal(outcome.error?.code, 'INVALID_ARGS');
99+
assert.equal(outcome.error?.details?.reason, 'provider-credentials-changed');
100+
assert.equal(outcome.error?.details?.provider, 'limrun');
101+
assert.match(
102+
String(outcome.error?.details?.hint),
103+
/agent-device daemon stop --state-dir '\/tmp\/agent device state'/,
104+
);
105+
});
106+
107+
test('a Limrun lease compares only the leased platform instance variables', async () => {
108+
const daemonEnv = {
109+
...LIMRUN_ATTACH_ENV,
110+
LIM_ANDROID_INSTANCE_URL: 'https://region.limrun.example/v1/android_x/api',
111+
LIM_ANDROID_INSTANCE_TOKEN: 'android-token',
112+
LIM_ANDROID_INSTANCE_ADB_URL: 'wss://region.limrun.example/v1/android_x/adb',
113+
};
114+
const shellEnv = { ...daemonEnv, LIM_ANDROID_INSTANCE_TOKEN: 'android-token-2' };
115+
const allocate = async (leaseBackend: 'ios-instance' | 'android-instance') =>
116+
await allocateWithDaemonEnv(
117+
providerAllocateRequest(
118+
'limrun',
119+
providerCredentialFingerprint('limrun', shellEnv, leaseBackend),
120+
leaseBackend,
121+
),
122+
daemonEnv,
123+
);
124+
125+
assert.equal((await allocate('ios-instance')).error, undefined);
126+
assert.equal(
127+
(await allocate('android-instance')).error?.details?.reason,
128+
'provider-credentials-changed',
129+
);
130+
});
131+
132+
test('a daemon holding rotated BrowserStack keys refuses before allocation', async () => {
133+
const outcome = await allocateWithDaemonEnv(
134+
providerAllocateRequest(
135+
'browserstack',
136+
providerCredentialFingerprint('browserstack', {
137+
...BROWSERSTACK_ENV,
138+
BROWSERSTACK_ACCESS_KEY: 'key-2',
139+
}),
140+
),
141+
BROWSERSTACK_ENV,
142+
);
143+
144+
assert.equal(outcome.allocations, 0);
145+
assert.equal(outcome.error?.details?.reason, 'provider-credentials-changed');
146+
assert.equal(outcome.error?.details?.provider, 'browserstack');
147+
});
148+
149+
test.for([
150+
['limrun', LIMRUN_ATTACH_ENV],
151+
['browserstack', BROWSERSTACK_ENV],
152+
] as const)(
153+
'a daemon holding the %s credentials of the shell allocates',
154+
async ([provider, env]) => {
155+
const outcome = await allocateWithDaemonEnv(
156+
providerAllocateRequest(provider, providerCredentialFingerprint(provider, env)),
157+
env,
158+
);
159+
160+
assert.equal(outcome.error, undefined);
161+
assert.equal(outcome.allocations, 1);
162+
},
163+
);
164+
165+
test('a daemon holding credentials allocates for a shell with none', async () => {
166+
const outcome = await allocateWithDaemonEnv(
167+
providerAllocateRequest('limrun', providerCredentialFingerprint('limrun', {})),
168+
{ LIMRUN_API_KEY: 'lim-key' },
169+
);
170+
171+
assert.equal(outcome.error, undefined);
172+
assert.equal(outcome.allocations, 1);
173+
});
174+
175+
test('a daemon started without BrowserStack credentials refuses a shell that has them', async () => {
176+
const outcome = await allocateWithDaemonEnv(
177+
providerAllocateRequest(
178+
'browserstack',
179+
providerCredentialFingerprint('browserstack', BROWSERSTACK_ENV),
180+
),
181+
{},
182+
);
183+
184+
assert.equal(outcome.allocations, 0);
185+
assert.equal(outcome.error?.details?.reason, 'provider-credentials-changed');
186+
assert.match(String(outcome.error?.message), /started without the browserstack credentials/);
187+
});
188+
189+
function testMuPluginEnv(): Record<string, string> {
190+
const manifest = path.resolve(
191+
import.meta.dirname,
192+
'../../../../packages/provider-testmu/package.json',
193+
);
194+
const { home, env } = pluginHome();
195+
selectPluginManifest(home, JSON.parse(fs.readFileSync(manifest, 'utf8')));
196+
return env;
197+
}
198+
199+
test('a daemon holding other TestMu AI credentials refuses before allocation', async () => {
200+
const home = testMuPluginEnv();
201+
const daemonEnv = { ...home, LT_USERNAME: 'user', LT_ACCESS_KEY: 'key-1' };
202+
const outcome = await allocateWithDaemonEnv(
203+
providerAllocateRequest(
204+
'testmu',
205+
providerCredentialFingerprint('testmu', { ...daemonEnv, LT_ACCESS_KEY: 'key-2' }),
206+
),
207+
daemonEnv,
208+
);
209+
210+
assert.equal(outcome.allocations, 0);
211+
assert.equal(outcome.error?.code, 'INVALID_ARGS');
212+
assert.equal(outcome.error?.details?.reason, 'provider-credentials-changed');
213+
assert.equal(outcome.error?.details?.provider, 'testmu');
214+
});
215+
216+
test('a daemon holding the TestMu AI credentials of the shell allocates', async () => {
217+
const env = { ...testMuPluginEnv(), LT_USERNAME: 'user', LT_ACCESS_KEY: 'key-1' };
218+
const outcome = await allocateWithDaemonEnv(
219+
providerAllocateRequest('testmu', providerCredentialFingerprint('testmu', env)),
220+
env,
221+
);
222+
223+
assert.equal(outcome.error, undefined);
224+
assert.equal(outcome.allocations, 1);
225+
});
226+
227+
test('a daemon started without TestMu AI credentials refuses a shell that has them', async () => {
228+
const home = testMuPluginEnv();
229+
const outcome = await allocateWithDaemonEnv(
230+
providerAllocateRequest(
231+
'testmu',
232+
providerCredentialFingerprint('testmu', {
233+
...home,
234+
LT_USERNAME: 'user',
235+
LT_ACCESS_KEY: 'key-1',
236+
}),
237+
),
238+
home,
239+
);
240+
241+
assert.equal(outcome.allocations, 0);
242+
assert.equal(outcome.error?.details?.reason, 'provider-credentials-changed');
243+
assert.match(String(outcome.error?.message), /started without the testmu credentials/);
244+
});

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { makeSessionStore } from './support/store-factory.ts';
88
import { buildSessionLeaseFromRequest } from '../lease-context.ts';
99
import { LeaseRegistry } from '../lease-registry.ts';
1010
import { createRequestHandler } from '../request-router.ts';
11-
import { readDaemonProviderCredentials } from '../../provider-credential-fingerprint.ts';
11+
import { providerCredentialsFixture } from './support/provider-credentials-fixture.ts';
1212
import { tenantScopedSessionName } from '../session-tenant-scope.ts';
1313
import { lifecycleDeviceRuntimeGateway } from './test-device-runtime-gateway.ts';
1414
import { HUMAN_CONTROL_LEASE_REQUEST, humanControlRequest } from './human-control-fixtures.ts';
@@ -33,7 +33,7 @@ export function createHumanControlHarness() {
3333
token: 'test-token',
3434
sessionStore,
3535
leaseRegistry: registry,
36-
providerCredentials: readDaemonProviderCredentials({}, '/tmp'),
36+
providerCredentials: providerCredentialsFixture({}, '/tmp'),
3737
deviceInventoryGateways: createTestDeviceInventoryGateways(),
3838
deviceRuntimeGateway: lifecycleDeviceRuntimeGateway,
3939
trackDownloadableArtifact: () => 'artifact-1',

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ import {
7777
lifecycleDeviceRuntimeGateway,
7878
} from './test-device-runtime-gateway.ts';
7979
import { createRequestHandler as createProductionRequestHandler } from '../request-router.ts';
80-
import { readDaemonProviderCredentials } from '../../provider-credential-fingerprint.ts';
80+
import { providerCredentialsFixture } from './support/provider-credentials-fixture.ts';
8181
import { resolveRequestExecutionLockPlan } from '../request-binding.ts';
8282
import { LeaseRegistry } from '../lease-registry.ts';
8383
import { ensureDeviceReady } from '../device/device-ready.ts';
@@ -501,7 +501,7 @@ test('close fails synchronously when root composition omits platform resource cl
501501
token: 'test-token',
502502
sessionStore,
503503
leaseRegistry: new LeaseRegistry(),
504-
providerCredentials: readDaemonProviderCredentials({}, '/tmp'),
504+
providerCredentials: providerCredentialsFixture({}, '/tmp'),
505505
deviceRuntimeGateway: lifecycleDeviceRuntimeGateway,
506506
deviceInventoryGateways: createTestDeviceInventoryGateways(),
507507
trackDownloadableArtifact: () => 'artifact-id',
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import crypto from 'node:crypto';
2+
import type { DaemonProviderCredentials } from '@agent-device/daemon-contracts/provider-credentials';
3+
4+
/**
5+
* The `DaemonProviderCredentials` port as the daemon suites need it. The daemon only compares
6+
* the fingerprint a client reports against the one this port computes from the daemon's startup
7+
* environment — the digests are opaque to daemon policy, which asserts refusal, reuse, and
8+
* passthrough, never digest content. The real reader's provider/manifest-aware variable
9+
* selection and digest semantics are pinned root-owned (request-router-provider-credentials,
10+
* lease-provider-credentials). This fixture digests the whole given environment so distinct
11+
* environments produce distinct fingerprints and an empty environment produces `undefined` —
12+
* the whole contract the daemon suites observe, without reading provider declarations.
13+
*/
14+
export function providerCredentialsFixture(
15+
env: Readonly<Record<string, string | undefined>> = {},
16+
stateDir = '/tmp',
17+
): DaemonProviderCredentials {
18+
const startupEnv = { ...env };
19+
return {
20+
fingerprint: () => digest(startupEnv),
21+
stateDir,
22+
};
23+
}
24+
25+
function digest(values: Readonly<Record<string, string | undefined>>): string | undefined {
26+
const pairs = Object.entries(values)
27+
.filter((pair): pair is [string, string] => pair[1] !== undefined)
28+
.sort(([left], [right]) => left.localeCompare(right));
29+
if (pairs.length === 0) return undefined;
30+
const hash = crypto.createHash('sha256').update(JSON.stringify(pairs)).digest('hex');
31+
return `v1:${hash.slice(0, 16)}`;
32+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import type { ProviderDeviceRuntime } from '@agent-device/contracts/device';
2+
import type { DeviceInfo } from '@agent-device/kernel/device';
3+
import { installProviderDeviceAdmission } from '../../provider-device-admission.ts';
4+
5+
/**
6+
* Provider ownership as the daemon consumes it: the `ProviderDeviceAdmission` port over a list
7+
* of runtime fakes, installed exactly the way root composition installs the real one. Daemon
8+
* suites flip which devices a provider lease currently owns and assert the daemon's branching
9+
* on that fact; which runtime module answers for a device is root composition's job, owned by
10+
* the provider-admission suites under `src/__tests__/daemon-composition/`.
11+
*/
12+
export function providerDeviceAdmissionFixture(runtimes: ProviderDeviceRuntime[] = []) {
13+
let activeRuntimes = [...runtimes];
14+
const admission = {
15+
isActive: (device: DeviceInfo) =>
16+
activeRuntimes.some((runtime) => runtime.ownsDevice(device)),
17+
};
18+
installProviderDeviceAdmission(admission);
19+
return {
20+
/** Same semantics as the production ambient scope: replaces the active runtime set. */
21+
setActive: (next: ProviderDeviceRuntime[]) => {
22+
activeRuntimes = [...next];
23+
},
24+
reset: () => {
25+
activeRuntimes = [];
26+
},
27+
};
28+
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import { clearAndroidObservationFixture } from './android-observation-fixture.ts
2828
import { daemonPlatformServicesFixture } from './platform-services-fixture.ts';
2929
import { createClaimRecoveryGateway } from '../../platform-runtime-claim-recovery.ts';
3030
import { platformResourceCleanup } from '../../platform-runtime-resource-cleanup.ts';
31-
import { readDaemonProviderCredentials } from '../../provider-credential-fingerprint.ts';
31+
import { providerCredentialsFixture } from './support/provider-credentials-fixture.ts';
3232

3333
const unavailable = Object.freeze({
3434
available: false as const,
@@ -237,7 +237,7 @@ export function createRequestHandler(
237237
) {
238238
const {
239239
deviceRuntimeGateway = unavailableDeviceRuntimeGateway,
240-
providerCredentials = readDaemonProviderCredentials({}, path.dirname(deps.logPath)),
240+
providerCredentials = providerCredentialsFixture({}, path.dirname(deps.logPath)),
241241
platformServices = daemonPlatformServicesFixture(),
242242
claimRecoveryGateway = createClaimRecoveryGateway,
243243
...rest

0 commit comments

Comments
 (0)