Skip to content

Commit de4c6e3

Browse files
committed
fix(leasing): refuse a caller-chosen lease id the daemon already issued
Provider release retries and provider-session ownership stay keyed by a lease id after the lease ends, so a chosen id that reuses a released or expired lease could close another lease's provider session. The registry now records every id it issues and refuses any of them with LEASE_ID_IN_USE. createDeviceLease takes the id instead of having it overwritten afterwards.
1 parent 13a5e2b commit de4c6e3

6 files changed

Lines changed: 91 additions & 26 deletions

File tree

‎packages/contracts/src/client-lease.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ export type LeaseAllocateOptions = LeaseOptions & {
3030
tenant: string;
3131
runId: string;
3232
/**
33-
* The id for the new lease (16-128 hex characters); the client's configured `leaseId` is never
34-
* sent here. Use the returned lease's `leaseId`: a daemon that predates this field mints its own,
33+
* The id for the new lease (16-128 hex characters), refused when the daemon already issued it;
34+
* the client's configured `leaseId` is never sent here. Use the returned lease's `leaseId`: a daemon that predates this field mints its own,
3535
* and a run that already holds a lease gets that lease back.
3636
*/
3737
leaseId?: string;

‎packages/daemon/src/resources/__tests__/lease-registry.test.ts‎

Lines changed: 68 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,15 @@ test('allocateLease creates lease and enforces tenant/run validation', () => {
3030
);
3131
});
3232

33-
test('allocateLease keeps a caller-chosen lease id and refuses one an active lease holds', () => {
33+
function isLeaseIdInUse(error: unknown): boolean {
34+
return (
35+
error instanceof AppError &&
36+
error.code === 'INVALID_ARGS' &&
37+
error.details?.reason === 'LEASE_ID_IN_USE'
38+
);
39+
}
40+
41+
test('allocateLease keeps a caller-chosen lease id and refuses any id it already issued', () => {
3442
const registry = new LeaseRegistry();
3543
const chosen = 'ABCDEF0123456789abcdef0123456789';
3644
const lease = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1', leaseId: chosen });
@@ -39,22 +47,72 @@ test('allocateLease keeps a caller-chosen lease id and refuses one an active lea
3947

4048
assert.throws(
4149
() => registry.allocateLease({ tenantId: 'tenant-b', runId: 'run-2', leaseId: chosen }),
42-
(error: unknown) =>
43-
error instanceof AppError &&
44-
error.code === 'INVALID_ARGS' &&
45-
error.details?.reason === 'LEASE_ID_IN_USE',
50+
isLeaseIdInUse,
4651
);
4752
assert.throws(
4853
() => registry.allocateLease({ tenantId: 'tenant-b', runId: 'run-2', leaseId: 'not-hex' }),
4954
(error: unknown) => error instanceof AppError && error.code === 'INVALID_ARGS',
5055
);
5156

5257
assert.equal(registry.releaseLease({ leaseId: lease.leaseId }).released, true);
53-
const reused = registry.allocateLease({ tenantId: 'tenant-b', runId: 'run-2', leaseId: chosen });
54-
assert.equal(reused.leaseId, lease.leaseId);
55-
assert.notEqual(
56-
registry.allocateLease({ tenantId: 'tenant-c', runId: 'run-3' }).leaseId,
57-
lease.leaseId,
58+
assert.throws(
59+
() => registry.allocateLease({ tenantId: 'tenant-b', runId: 'run-2', leaseId: chosen }),
60+
isLeaseIdInUse,
61+
);
62+
63+
const minted = registry.allocateLease({ tenantId: 'tenant-c', runId: 'run-3' });
64+
const hostIssued = registry.putHostLease('0123456789abcdef0123456789abcdef', {
65+
tenantId: 'tenant-d',
66+
runId: 'run-4',
67+
});
68+
assert.equal(registry.releaseLease({ leaseId: minted.leaseId }).released, true);
69+
assert.equal(registry.releaseLease({ leaseId: hostIssued.leaseId }).released, true);
70+
for (const leaseId of [minted.leaseId, hostIssued.leaseId]) {
71+
assert.throws(
72+
() => registry.allocateLease({ tenantId: 'tenant-e', runId: 'run-5', leaseId }),
73+
isLeaseIdInUse,
74+
);
75+
}
76+
});
77+
78+
test('an expired provider lease keeps its id and provider session from a caller-chosen reuse', () => {
79+
let now = 1_000;
80+
const registry = new LeaseRegistry({ now: () => now, defaultLeaseTtlMs: 10_000 });
81+
const leaseId = 'abcdef0123456789abcdef0123456789';
82+
const expiring = registry.allocateLease({
83+
tenantId: 'tenant-a',
84+
runId: 'run-1',
85+
leaseId,
86+
leaseBackend: 'ios-instance',
87+
leaseProvider: 'limrun',
88+
deviceKey: 'device-1',
89+
});
90+
registry.recordProviderSession(expiring, 'provider-session-1');
91+
92+
now = 20_000;
93+
assert.deepEqual(
94+
registry.consumeExpiredLeases().map((lease) => lease.leaseId),
95+
[leaseId],
96+
);
97+
assert.throws(
98+
() =>
99+
registry.allocateLease({
100+
tenantId: 'tenant-a',
101+
runId: 'run-2',
102+
leaseId,
103+
leaseBackend: 'ios-instance',
104+
leaseProvider: 'limrun',
105+
deviceKey: 'device-1',
106+
}),
107+
isLeaseIdInUse,
108+
);
109+
assert.equal(
110+
registry.resolveProviderSession({
111+
provider: 'limrun',
112+
providerSessionId: 'provider-session-1',
113+
tenantId: 'tenant-a',
114+
})?.leaseId,
115+
leaseId,
58116
);
59117
});
60118

‎packages/daemon/src/resources/lease-registry-scope.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,9 +336,10 @@ export function createDeviceLease(
336336
request: NormalizedAllocateLeaseRequest,
337337
leaseTtlMs: number,
338338
now: number,
339+
leaseId = crypto.randomBytes(16).toString('hex'),
339340
): DeviceLease {
340341
return {
341-
leaseId: crypto.randomBytes(16).toString('hex'),
342+
leaseId,
342343
tenantId: request.tenantId,
343344
runId: request.runId,
344345
backend: request.backend,

‎packages/daemon/src/resources/lease-registry.ts‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ export class LeaseRegistry {
4949
private readonly mutations = new DeviceMutationDrain();
5050
private readonly inFlightWork = new LeaseInFlightWorkRegistry();
5151
private readonly leases = new Map<string, DeviceLease>();
52+
/**
53+
* Every id this daemon has given a lease. Provider release retries and provider-session ownership
54+
* stay keyed by a lease id after the lease ends, so a caller-chosen id must never name one again.
55+
*/
56+
private readonly issuedLeaseIds = new Set<string>();
5257
private readonly runBindings = new Map<string, string>();
5358
private readonly deviceBindings = new Map<string, string>();
5459
/** The inactivity window the host chose for each lease it allocated; a tenant cannot exceed it. */
@@ -82,19 +87,15 @@ export class LeaseRegistry {
8287
this.assertHumanControlAdmission(normalized);
8388
const existingLease = this.refreshExistingRunBinding(normalized, leaseTtlMs);
8489
if (existingLease) return existingLease;
85-
if (chosenLeaseId && this.leases.has(chosenLeaseId)) {
86-
throw new AppError('INVALID_ARGS', 'Lease id already names an active lease.', {
90+
if (chosenLeaseId && this.issuedLeaseIds.has(chosenLeaseId)) {
91+
throw new AppError('INVALID_ARGS', 'Lease id already names a lease this daemon issued.', {
8792
reason: 'LEASE_ID_IN_USE',
8893
});
8994
}
9095
this.assertDeviceAvailable(normalized);
9196
this.enforceCapacity(normalized.backend);
92-
const lease = {
93-
...createDeviceLease(normalized, leaseTtlMs, this.now()),
94-
...(chosenLeaseId ? { leaseId: chosenLeaseId } : {}),
95-
};
96-
this.leases.set(lease.leaseId, lease);
97-
this.bindLease(lease);
97+
const lease = createDeviceLease(normalized, leaseTtlMs, this.now(), chosenLeaseId);
98+
this.issueLease(lease);
9899
return { ...lease };
99100
}
100101

@@ -127,13 +128,18 @@ export class LeaseRegistry {
127128
});
128129
}
129130
this.enforceCapacity(normalized.backend);
130-
const lease = { ...createDeviceLease(normalized, leaseTtlMs, this.now()), leaseId: id };
131-
this.leases.set(lease.leaseId, lease);
131+
const lease = createDeviceLease(normalized, leaseTtlMs, this.now(), id);
132+
this.issueLease(lease);
132133
this.hostTtlMsByLeaseId.set(id, leaseTtlMs);
133-
this.bindLease(lease);
134134
return { ...lease };
135135
}
136136

137+
private issueLease(lease: DeviceLease): void {
138+
this.issuedLeaseIds.add(lease.leaseId);
139+
this.leases.set(lease.leaseId, lease);
140+
this.bindLease(lease);
141+
}
142+
137143
private refreshExistingRunBinding(
138144
request: NormalizedAllocateLeaseRequest,
139145
leaseTtlMs: number,

‎website/docs/docs/client-api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ Domain client methods:
247247
- `client.sessions.list()`, `stateDir()`, `close()`, `saveScript()`, `artifacts()`
248248
- `client.apps.install()`, `reinstall()`, `installFromSource()`, `list()`, `open()`, `close()`, `push()`, `triggerEvent()`
249249
- `client.materializations.release()`
250-
- `client.leases.allocate()`, `heartbeat()`, `release()`. Pass `retainOnClose: true` to `allocate()` when you release the lease yourself; session `close` then leaves it active until `release()`, expiry, or daemon shutdown. The returned lease has `retainOnClose: true` only when the daemon honored it. Keep heartbeating a retained lease between sessions: it expires after its `ttlMs` like any other lease. Pass `leaseId` (16 to 128 hex characters) to `allocate()` to name a new lease, then use the returned `leaseId`: a run that already holds a lease gets that one back, and an older daemon mints its own.
250+
- `client.leases.allocate()`, `heartbeat()`, `release()`. Pass `retainOnClose: true` to `allocate()` when you release the lease yourself; session `close` then leaves it active until `release()`, expiry, or daemon shutdown. The returned lease has `retainOnClose: true` only when the daemon honored it. Keep heartbeating a retained lease between sessions: it expires after its `ttlMs` like any other lease. Pass `leaseId` (16 to 128 hex characters) to `allocate()` to name a new lease with an id the daemon has never issued, then use the returned `leaseId`: a run that already holds a lease gets that one back, and an older daemon mints its own.
251251
- `client.metro.prepare()`, `reload()`
252252
- `client.capture.snapshot()`, `screenshot()`, `diff()`
253253
- `client.interactions.click()`, `press()`, `longPress()`, `swipe()`, `pan()`, `drag()`, `fling()`, `swipeGesture()`, `focus()`, `type()`, `fill()`, `scroll()`, `pinch()`, `rotateGesture()`, `transformGesture()`, `get()`, `is()`, `find()`

‎website/docs/docs/remote-proxy.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ agent-device disconnect
4747

4848
`connect proxy` stores the proxy profile and client identity. `open` leases the device for you, and the lease expires after five minutes without commands. A lease allocated directly over the RPC without `ttlMs` gets the daemon's one-minute inactivity default instead. Either window starts when allocation completes, not when it was requested. `close` releases the active session and its device lease, unless the lease was allocated with `retainOnClose`; only `leases.release`, expiry, or daemon shutdown ends that one. `disconnect` clears local connection state.
4949

50-
`open` names each new lease with an id it makes (32 lowercase hex characters) and sends it with the allocation, so a host in front of the daemon knows the lease id before the daemon allocates. A direct `agent_device.lease.allocate` RPC can pass `leaseId` (16 to 128 hex characters) the same way; an id an active lease already holds is refused with `INVALID_ARGS` and reason `LEASE_ID_IN_USE`, and without one the daemon makes the id. Use the id the reply carries: a run that already holds a lease gets that lease back, and an older daemon ignores the requested id.
50+
`open` names each new lease with an id it makes (32 lowercase hex characters) and sends it with the allocation, so a host in front of the daemon knows the lease id before the daemon allocates. A direct `agent_device.lease.allocate` RPC can pass `leaseId` (16 to 128 hex characters) the same way; an id this daemon has already given a lease, active or ended, is refused with `INVALID_ARGS` and reason `LEASE_ID_IN_USE`, and without one the daemon makes the id. Use the id the reply carries: a run that already holds a lease gets that lease back, and an older daemon ignores the requested id.
5151

5252
Several agents can share one proxy when each follows the same `connect proxy`, `open`, commands, `close`, and `disconnect` flow. A busy device error means another agent holds the device until it closes its session or its lease expires.
5353

0 commit comments

Comments
 (0)