Repository navigation
Expand file tree
/
Copy pathlease.test.ts
More file actions
403 lines (383 loc) · 13.3 KB
/
Copy pathlease.test.ts
File metadata and controls
403 lines (383 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import assert from 'node:assert/strict';
import { test } from 'vitest';
import { handleLeaseCommands } from '../lease.ts';
import { LeaseRegistry } from '../../lease-registry.ts';
import type { DaemonRequest } from '../../daemon-request.ts';
import { makeSessionStore } from '../../__tests__/support/store-factory.ts';
import type { DeviceLease } from '@agent-device/contracts/device';
import { AppError } from '@agent-device/kernel/errors';
import {
clearRequestCanceled,
markRequestCanceled,
registerRequestAbort,
} from '@agent-device/host-kit/request';
import {
HUMAN_CONTROL_LEASE_REQUEST,
HUMAN_CONTROL_SCOPE,
createControlLatch,
humanControlRequest,
} from '../../__tests__/human-control-fixtures.ts';
for (const operation of ['allocate', 'release'] as const) {
test(`host activation drains provider lease ${operation} before reporting active`, async () => {
const registry = new LeaseRegistry();
const lease = registry.allocateLease(HUMAN_CONTROL_LEASE_REQUEST);
const started = createControlLatch();
const finish = createControlLatch();
const request = humanControlRequest(lease, `lease_${operation}`, []);
const mutation = handleLeaseCommands({
req: request,
sessionName: request.session,
sessionStore: makeSessionStore('agent-device-held-provider-'),
leaseRegistry: registry,
leaseLifecycleProvider: {
[operation]: async () => {
started.resolve();
await finish.promise;
return {};
},
},
});
await started.promise;
let active = false;
const activation = registry
.putHumanControlHold({ kind: 'host' }, 'host', { scope: HUMAN_CONTROL_SCOPE })
.then(() => {
active = true;
});
await Promise.resolve();
assert.equal(active, false);
finish.resolve();
assert.equal((await mutation)?.ok, true);
await activation;
assert.equal(active, true);
});
}
test('lease_release still releases a retainOnClose lease through the provider', async () => {
const registry = new LeaseRegistry();
const lease = registry.allocateLease({
tenantId: 'tenant-a',
runId: 'run-1',
clientId: 'client-a',
retainOnClose: true,
});
const released: DeviceLease[] = [];
const request: DaemonRequest = {
token: 'test-token',
session: 'default',
command: 'lease_release',
positionals: [],
meta: { tenantId: 'tenant-a', runId: 'run-1', leaseId: lease.leaseId, clientId: 'client-a' },
};
const response = await handleLeaseCommands({
req: request,
sessionName: 'default',
sessionStore: makeSessionStore('agent-device-retained-release-'),
leaseRegistry: registry,
leaseLifecycleProvider: {
release: async (active) => {
released.push(active);
return { providerSessionId: 'provider-1' };
},
},
});
assert.equal(response?.ok, true);
assert.deepEqual(
released.map((active) => active.leaseId),
[lease.leaseId],
);
assert.equal(registry.listActiveLeases().length, 0);
});
test('lease_release refuses a host-allocated macos-app lease and keeps it', async () => {
const registry = new LeaseRegistry();
const lease = registry.putHostLease('a1b2c3d4e5f60718293a4b5c6d7e8f90', {
tenantId: 'tenant-a',
runId: 'run-1',
clientId: 'client-a',
leaseBackend: 'macos-app' as const,
deviceKey: 'com.example.app@4242',
});
const released: DeviceLease[] = [];
const meta = {
tenantId: 'tenant-a',
runId: 'run-1',
leaseId: lease.leaseId,
clientId: 'client-a',
leaseBackend: 'macos-app' as const,
deviceKey: 'com.example.app@4242',
};
const run = (command: 'lease_release' | 'lease_heartbeat') =>
handleLeaseCommands({
req: { token: 'test-token', session: 'default', command, positionals: [], meta },
sessionName: 'default',
sessionStore: makeSessionStore('agent-device-macos-app-release-'),
leaseRegistry: registry,
leaseLifecycleProvider: {
release: async (active) => {
released.push(active);
return {};
},
},
});
await assert.rejects(run('lease_release'), (error: AppError) => {
assert.equal(error.code, 'UNAUTHORIZED');
assert.equal(error.details?.reason, 'MACOS_APP_LEASE_HOST_OWNED');
return true;
});
assert.deepEqual(released, []);
assert.equal(registry.listActiveLeases().length, 1);
assert.equal((await run('lease_heartbeat'))?.ok, true);
});
test('lease_allocate stores retainOnClose from the request meta', async () => {
const registry = new LeaseRegistry();
const request: DaemonRequest = {
token: 'test-token',
session: 'default',
command: 'lease_allocate',
positionals: [],
meta: { tenantId: 'tenant-a', runId: 'run-1', leaseRetainOnClose: true },
};
const response = await handleLeaseCommands({
req: request,
sessionName: 'default',
sessionStore: makeSessionStore('agent-device-retained-allocate-'),
leaseRegistry: registry,
});
assert.equal(response?.ok, true);
assert.equal(registry.listActiveLeases()[0]?.retainOnClose, true);
});
test('activation drains canceled provider allocation and its release cleanup', async () => {
const registry = new LeaseRegistry();
const lease = registry.allocateLease(HUMAN_CONTROL_LEASE_REQUEST);
const started = createControlLatch();
const finish = createControlLatch();
const request = humanControlRequest(lease, 'lease_allocate', []);
const requestId = 'held-canceled-allocation';
request.meta = { ...request.meta, requestId };
let providerReleased = false;
const mutation = handleLeaseCommands({
req: request,
sessionName: request.session,
sessionStore: makeSessionStore('agent-device-held-canceled-provider-'),
leaseRegistry: registry,
leaseLifecycleProvider: {
allocate: async () => {
started.resolve();
await finish.promise;
markRequestCanceled(requestId);
return {};
},
release: async () => {
assert.equal(registry.listHumanControlHolds({ kind: 'host' })[0]?.state, 'activating');
providerReleased = true;
return {};
},
},
});
await started.promise;
const activation = registry.putHumanControlHold({ kind: 'host' }, 'host', {
scope: HUMAN_CONTROL_SCOPE,
});
finish.resolve();
try {
await assert.rejects(
mutation,
(error: unknown) => error instanceof AppError && error.details?.released === true,
);
await activation;
assert.equal(providerReleased, true);
assert.equal(registry.listActiveLeases().length, 0);
} finally {
clearRequestCanceled(requestId);
}
});
function allocateRequest(): DaemonRequest {
return {
token: 'test-token',
session: 'lease-ttl-test',
command: 'lease_allocate',
positionals: [],
flags: {},
meta: {
tenantId: 'tenant-a',
runId: 'run-a',
clientId: 'client-a',
leaseBackend: 'android-instance',
leaseProvider: 'cloud',
},
};
}
// A hosted provider can spend longer creating its session than the lease's inactivity
// TTL. Stamping the TTL when the registry record is created handed the client a lease
// that was already expired, and the paid session behind it was orphaned.
test('a lease whose provider allocation outlasts its TTL is active when allocation returns', async () => {
let now = 0;
const registry = new LeaseRegistry({ now: () => now, defaultLeaseTtlMs: 60_000 });
const response = await handleLeaseCommands({
req: allocateRequest(),
sessionName: 'lease-ttl-test',
sessionStore: makeSessionStore('agent-device-slow-provider-'),
leaseRegistry: registry,
leaseLifecycleProvider: {
allocate: async (lease) => {
now = 80_000;
assert.deepEqual(
registry.consumeExpiredLeases(),
[],
'the sweeper must not reap a lease mid-allocation',
);
now = 90_000;
return { providerSessionId: `session-${lease.leaseId}` };
},
},
});
assert.equal(response?.ok, true);
const lease = (response?.ok ? response.data?.lease : undefined) as DeviceLease;
assert.equal(lease.expiresAt, 150_000);
assert.deepEqual(
registry.listActiveLeases().map((entry) => [entry.leaseId, entry.expiresAt]),
[[lease.leaseId, 150_000]],
);
now = 149_999;
registry.assertLeaseAdmission({
leaseId: lease.leaseId,
tenantId: lease.tenantId,
runId: lease.runId,
leaseBackend: lease.backend,
leaseProvider: lease.leaseProvider,
});
});
test('a lease allocated without a provider keeps the TTL it was created with', async () => {
let now = 5_000;
const registry = new LeaseRegistry({
now: () => (now += 1_000),
defaultLeaseTtlMs: 60_000,
});
const response = await handleLeaseCommands({
req: allocateRequest(),
sessionName: 'lease-ttl-test',
sessionStore: makeSessionStore('agent-device-no-provider-'),
leaseRegistry: registry,
});
assert.equal(response?.ok, true);
const lease = (response?.ok ? response.data?.lease : undefined) as DeviceLease;
assert.ok(now > lease.createdAt, 'the clock advanced while the lease was allocated');
assert.equal(lease.heartbeatAt, lease.createdAt);
assert.equal(lease.expiresAt, lease.createdAt + 60_000);
assert.deepEqual(registry.listActiveLeases(), [lease]);
});
// The registry hands a run's repeat allocation the lease it already holds. A provider refusing the
// repeat request (a profile field it does not read) must leave that lease and its session alone.
test("a refused repeat allocation keeps the run's live lease", async () => {
const registry = new LeaseRegistry();
const sessionStore = makeSessionStore('agent-device-refused-repeat-');
let calls = 0;
const allocate = async (req: DaemonRequest) =>
await handleLeaseCommands({
req,
sessionName: 'lease-ttl-test',
sessionStore,
leaseRegistry: registry,
leaseLifecycleProvider: {
allocate: async () => {
calls += 1;
if (calls === 1) return { providerSessionId: 'session-1' };
throw new AppError('INVALID_ARGS', '--provider-os-version is not supported by Cloud.');
},
},
});
const first = await allocate(allocateRequest());
const lease = (first?.ok ? first.data?.lease : undefined) as DeviceLease;
const repeat = allocateRequest();
repeat.flags = { providerOsVersion: '18.0' };
await assert.rejects(
allocate(repeat),
(error: unknown) => error instanceof AppError && error.code === 'INVALID_ARGS',
);
assert.equal(calls, 2);
assert.deepEqual(
registry.listActiveLeases().map((entry) => entry.leaseId),
[lease.leaseId],
);
assert.equal(
registry.resolveProviderSession({
provider: lease.leaseProvider,
providerSessionId: 'session-1',
tenantId: lease.tenantId,
})?.leaseId,
lease.leaseId,
);
});
// A requester that hangs up during its repeat allocation will never release the lease it reused, so
// the provider rejecting with the cancellation must release that lease and its session.
test('a repeat allocation canceled by its requester releases the reused lease', async () => {
const registry = new LeaseRegistry();
const sessionStore = makeSessionStore('agent-device-canceled-repeat-');
const requestId = 'canceled-repeat-allocation';
const releasedSessions: unknown[] = [];
let calls = 0;
const allocate = async (req: DaemonRequest) =>
await handleLeaseCommands({
req,
sessionName: 'lease-ttl-test',
sessionStore,
leaseRegistry: registry,
leaseLifecycleProvider: {
allocate: async (_lease, context) => {
calls += 1;
if (calls === 1) return { providerSessionId: 'session-1' };
markRequestCanceled(requestId);
context?.signal?.throwIfAborted();
throw new Error('the request signal was not aborted');
},
release: async (released) => {
releasedSessions.push(released.leaseId);
return { providerSessionId: 'session-1' };
},
},
});
const first = await allocate(allocateRequest());
const lease = (first?.ok ? first.data?.lease : undefined) as DeviceLease;
const repeat = allocateRequest();
repeat.meta = { ...repeat.meta, requestId };
const registration = registerRequestAbort(requestId);
try {
await assert.rejects(
allocate(repeat),
(error: unknown) => error instanceof AppError && error.details?.released === true,
);
} finally {
clearRequestCanceled(requestId, registration);
}
assert.equal(calls, 2);
assert.deepEqual(releasedSessions, [lease.leaseId]);
assert.deepEqual(registry.listActiveLeases(), []);
});
test('a tenant cannot allocate a macos-app lease', async () => {
const registry = new LeaseRegistry();
const request: DaemonRequest = {
token: 'token',
session: 'default',
command: 'lease_allocate',
positionals: [],
flags: {},
meta: {
tenantId: 'tenant-a',
runId: 'run-1',
leaseBackend: 'macos-app',
leaseProvider: 'proxy',
clientId: 'client-1',
deviceKey: 'com.apple.finder',
},
};
await assert.rejects(
handleLeaseCommands({
req: request,
sessionName: request.session,
sessionStore: makeSessionStore('agent-device-macos-app-allocate-'),
leaseRegistry: registry,
}),
(error: AppError) =>
error.code === 'UNAUTHORIZED' && error.details?.reason === 'MACOS_APP_LEASE_HOST_ALLOCATED',
);
assert.deepEqual(registry.listActiveLeases(), []);
});