diff --git a/docs/adr/0007-remote-device-leases.md b/docs/adr/0007-remote-device-leases.md index 91dd506412..b33b76280c 100644 --- a/docs/adr/0007-remote-device-leases.md +++ b/docs/adr/0007-remote-device-leases.md @@ -81,5 +81,5 @@ The detailed contracts are in the [daemon](../../packages/daemon/docs/remote-dev - Limrun has not moved its lease ownership onto the shared provider lease table ([#4102](https://github.com/callstack/agent-device/issues/4102)). - Provider allocation can still leave a rental outside registry recovery when a first allocation fails or a late allocation's release fails. Only the provider runtime that still holds the device can end that rental. - An older client or a direct RPC caller that sent no lease id on a leased session is refused. It must send the lease id that its allocation returned. -- `session_list` still shows session names to every holder of the proxy token ([#4908](https://github.com/callstack/agent-device/issues/4908)). The allocate run-binding refresh can still return an existing lease id to a caller that repeats the tenant, run id, and client id ([#4909](https://github.com/callstack/agent-device/issues/4909)). +- `session_list` still shows session names to every holder of the proxy token ([#4908](https://github.com/callstack/agent-device/issues/4908)). - A web open can be admitted under a non-`macos-app` lease for another backend; admission does not compare the request platform with the lease backend. diff --git a/packages/contracts/src/client-lease.ts b/packages/contracts/src/client-lease.ts index 662dbf546e..f5de8246f0 100644 --- a/packages/contracts/src/client-lease.ts +++ b/packages/contracts/src/client-lease.ts @@ -85,7 +85,7 @@ export type LeaseAllocateOptions = LeaseOptions & /** * The id for the new lease (32-128 random hex characters), refused when the daemon already issued it; * the client's configured `leaseId` is never sent here. Use the returned lease's `leaseId`: a daemon that predates this field mints its own, - * and a run that already holds a lease gets that lease back. + * and only a retry that sends the id of a live lease gets that lease back. */ leaseId?: string; leaseBackend?: LeaseBackend; @@ -95,8 +95,10 @@ export type LeaseAllocateOptions = LeaseOptions & clientId?: string; /** * Keeps the lease through session `close`; it then ends only through `leases.release`, expiry, or - * daemon shutdown. Asking for it on a lease the same client already holds for the run turns it on - * for that lease; the returned lease's `retainOnClose` says whether the daemon honored it. + * daemon shutdown. Enabling it on a lease that is already live needs that lease's current + * `leaseId` in this call, with the matching scope; an allocate that repeats the labels without + * the id is refused and retention stays off. The returned lease's `retainOnClose` says whether + * the daemon honored it. */ retainOnClose?: boolean; }; diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index 56e7450da9..2640480a11 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -9,7 +9,7 @@ Session `close` then leaves that lease and its provider device in place. Only `leases.release`, expiry, a provider-reported instance end, or daemon shutdown ends it. The default is unchanged, so the CLI's proxy sharing still frees devices on `close`. The allocated lease reports `retainOnClose: true` only if the daemon honored it. -Only the lease's own client can turn it on for a lease that the run already holds. +Only a refresh that sends the lease id turns it on for a lease that is already live. An unexpired `retainOnClose` lease keeps an idle daemon alive. Other leases, including human-control holds, do not. If the caller stops heartbeats for a retained lease, that lease expires after its `ttlMs`. @@ -77,6 +77,7 @@ If a request omits the lease id, the daemon refuses it with `UNAUTHORIZED`, reas The daemon never fills a missing lease id from the session. Tenant, run id, lease backend, client id, device key, and lease provider are labels. The daemon refuses a label that differs from the session lease. A missing label is not a refusal and grants nothing. +An allocate that repeats the labels of a live lease without that lease's id is refused as contention, with `DEVICE_IN_USE` and reason `DEVICE_LEASE_BUSY`. It returns no lease id. If the live lease has no device key, a label that contradicts it stays a scope mismatch, with `UNAUTHORIZED` and reason `LEASE_SCOPE_MISMATCH`. A repeat of a live lease with a device key is `DEVICE_LEASE_BUSY` whatever its client id says. Only an allocate that sends the id of its live lease gets that lease back. A caller-chosen lease id on allocate must have at least 32 hex digits (128 bits). A shorter id fails with reason `LEASE_ID_TOO_SHORT`. Commands that ignore the session lease, such as `devices`, `session_list`, and the lease RPCs, keep their own scope. diff --git a/packages/daemon/src/resources/__tests__/lease-registry.test.ts b/packages/daemon/src/resources/__tests__/lease-registry.test.ts index 0672a6d71a..0bda76eca3 100644 --- a/packages/daemon/src/resources/__tests__/lease-registry.test.ts +++ b/packages/daemon/src/resources/__tests__/lease-registry.test.ts @@ -38,6 +38,14 @@ function isLeaseIdInUse(error: unknown): boolean { ); } +function isDeviceLeaseBusy(error: unknown): boolean { + return ( + error instanceof AppError && + error.code === 'DEVICE_IN_USE' && + error.details?.reason === 'DEVICE_LEASE_BUSY' + ); +} + test('allocateLease keeps a caller-chosen lease id and refuses any id it already issued', () => { const registry = new LeaseRegistry(); const chosen = 'ABCDEF0123456789abcdef0123456789'; @@ -197,45 +205,49 @@ test('an expired provider lease keeps its id and provider session from a caller- ); }); -test('allocateLease is idempotent per tenant/run/backend and refreshes expiry', () => { +test('an allocation that repeats the run labels without the lease id is refused', () => { let now = 1_000; - const registry = new LeaseRegistry({ - now: () => now, - defaultLeaseTtlMs: 10_000, - }); + const registry = new LeaseRegistry({ now: () => now, defaultLeaseTtlMs: 10_000 }); const first = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); now = 2_000; - const second = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); - assert.equal(second.leaseId, first.leaseId); - assert.equal(second.heartbeatAt, 2_000); - assert.equal(second.expiresAt, 12_000); + + // The refusal names no lease id: a caller that does not hold one gets nothing back. + const error = captureThrown(() => + registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }), + ); + assert.ok(error instanceof AppError); + assert.equal(error.code, 'DEVICE_IN_USE'); + assert.equal(error.details?.reason, 'DEVICE_LEASE_BUSY'); + assert.equal(error.details?.leaseId, undefined); + assert.equal(registry.inspectActiveLease(first.leaseId)?.heartbeatAt, 1_000); + + // A label that contradicts the live device-less lease stays the scope mismatch it was. + const mismatch = captureThrown(() => + registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1', clientId: 'client-b' }), + ); + assert.ok(mismatch instanceof AppError); + assert.equal(mismatch.code, 'UNAUTHORIZED'); + assert.equal(mismatch.details?.reason, 'LEASE_SCOPE_MISMATCH'); }); -test('a later allocation asking for retainOnClose turns it on for the reused lease', () => { +test('only a refresh that sends the lease id turns retainOnClose on for the run lease', () => { const registry = new LeaseRegistry(); - const first = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); + const owner = { tenantId: 'tenant-a', runId: 'run-1', clientId: 'client-a' } as const; + const first = registry.allocateLease({ ...owner, leaseId: 'a'.repeat(32) }); const second = registry.allocateLease({ - tenantId: 'tenant-a', - runId: 'run-1', + ...owner, + leaseId: first.leaseId, retainOnClose: true, }); - const third = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); + const third = registry.allocateLease({ ...owner, leaseId: first.leaseId }); assert.equal(second.leaseId, first.leaseId); assert.equal(first.retainOnClose, undefined); assert.equal(second.retainOnClose, true); assert.equal(third.retainOnClose, true); -}); -test('a request without the owning clientId cannot turn retainOnClose on for a run lease', () => { - const registry = new LeaseRegistry(); - const owned = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1', clientId: 'a' }); - const reused = registry.allocateLease({ - tenantId: 'tenant-a', - runId: 'run-1', - retainOnClose: true, - }); - assert.equal(reused.leaseId, owned.leaseId); - assert.equal(reused.retainOnClose, undefined); + const heldBefore = registry.inspectActiveLease(first.leaseId); + assert.throws(() => registry.allocateLease({ ...owner, retainOnClose: true }), isDeviceLeaseBusy); + assert.deepEqual(registry.inspectActiveLease(first.leaseId), heldBefore); }); test('only an unexpired retainOnClose lease counts as retained', () => { @@ -313,30 +325,24 @@ test('capacity limits reject additional simulator leases', () => { ); }); -test('device-aware allocation is idempotent per tenant/run/backend/provider/device', () => { +test('an owner refresh of a device-aware lease renews it, and the same labels without the id are refused', () => { let now = 1_000; const registry = new LeaseRegistry({ now: () => now, defaultLeaseTtlMs: 10_000, }); - const first = registry.allocateLease({ + const owner = { tenantId: 'tenant-a', runId: 'run-1', - leaseBackend: 'ios-instance', + leaseBackend: 'ios-instance' as const, leaseProvider: 'proxy', deviceKey: 'device-1', clientId: 'client-a', - }); + }; + const first = registry.allocateLease({ ...owner, leaseId: 'a'.repeat(32) }); now = 3_000; - const second = registry.allocateLease({ - tenantId: 'tenant-a', - runId: 'run-1', - leaseBackend: 'ios-instance', - leaseProvider: 'proxy', - deviceKey: 'device-1', - clientId: 'client-a', - }); + const second = registry.allocateLease({ ...owner, leaseId: first.leaseId }); assert.equal(second.leaseId, first.leaseId); assert.equal(second.leaseProvider, 'proxy'); @@ -344,6 +350,8 @@ test('device-aware allocation is idempotent per tenant/run/backend/provider/devi assert.equal(second.clientId, 'client-a'); assert.equal(second.heartbeatAt, 3_000); assert.equal(second.expiresAt, 13_000); + + assert.throws(() => registry.allocateLease({ ...owner }), isDeviceLeaseBusy); }); test('same backend/provider/device rejects conflicting active lease', () => { diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index 78e69e109e..0f8962f933 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -102,8 +102,7 @@ export class LeaseRegistry { }); } this.assertHumanControlAdmission(normalized); - const existingLease = this.refreshExistingRunBinding(normalized, leaseTtlMs); - if (existingLease) return existingLease; + this.assertNoRunBindingLease(normalized); this.assertDeviceAvailable(normalized); this.enforceCapacity(normalized.backend); const lease = createDeviceLease(normalized, leaseTtlMs, this.now(), chosenLeaseId); @@ -201,29 +200,24 @@ export class LeaseRegistry { ); } - private refreshExistingRunBinding( - request: NormalizedAllocateLeaseRequest, - leaseTtlMs: number, - ): DeviceLease | undefined { + /** + * An allocation that repeats the labels of a live run binding without that binding's lease id + * claims a lease it cannot prove it owns, so it is refused like any other contention. The lease id + * is the credential, and labels a caller can guess are not one (#4909). For a device-less live + * lease, a label that disagrees stays the scope mismatch the daemon already refused. A repeat of a + * device-keyed binding is busy whatever its client id says. + */ + private assertNoRunBindingLease(request: NormalizedAllocateLeaseRequest): void { const bindingKey = leaseRunBindingKey(request); const existingId = this.runBindings.get(bindingKey); - if (!existingId) return undefined; + if (!existingId) return; const existingLease = this.leases.get(existingId); if (!existingLease) { this.runBindings.delete(bindingKey); - return undefined; - } - if (existingLease.clientId === request.clientId) { - return this.refreshLease( - request.retainOnClose ? { ...existingLease, retainOnClose: true } : existingLease, - leaseTtlMs, - ); - } - if (existingLease.deviceKey) { - throw deviceLeaseBusyError(existingLease); + return; } - assertLeaseScopeMatch(existingLease, request); - return this.refreshLease(existingLease, leaseTtlMs); + if (!existingLease.deviceKey) assertLeaseScopeMatch(existingLease, request); + throw deviceLeaseBusyError(existingLease); } /** diff --git a/packages/daemon/src/server/http/daemon-runtime-lease-run-binding.test.ts b/packages/daemon/src/server/http/daemon-runtime-lease-run-binding.test.ts new file mode 100644 index 0000000000..c6a3cc0e94 --- /dev/null +++ b/packages/daemon/src/server/http/daemon-runtime-lease-run-binding.test.ts @@ -0,0 +1,118 @@ +import fs from 'node:fs'; +import { afterEach, beforeEach, expect, test } from 'vitest'; +import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; +import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { daemonRuntimeDepsFixture } from '../../__tests__/support/daemon-runtime-deps-fixture.ts'; +import { startDaemonRuntime } from './daemon-runtime.ts'; + +// The lease id is the credential for a lease (#4909). Labels a caller can guess — the tenant, run, +// backend, provider, device key, and client id — are not one, so repeating them must not hand back +// the lease id of the caller that allocated the lease. + +const PROXY_SCOPE = { + tenantId: 'e2b', + runId: 'run-a', + leaseProvider: 'proxy', + clientId: 'client-a', + deviceKey: 'ios:mobile:SIM-001', + backend: 'ios-instance', +} as const; + +const PLAIN_SCOPE = { + tenantId: 'e2b', + runId: 'run-b', + backend: 'android-instance', +} as const; + +type RpcBody = { + result?: { ok?: boolean; data?: { lease?: Record; reused?: boolean } }; + error?: { data?: { code?: string; details?: Record } }; +}; + +let daemon: { close: () => Promise; httpPort: number; token: string }; + +beforeEach(async () => { + const stateDir = mkdtempForTestSync('agent-device-run-binding-'); + const runtime = await startDaemonRuntime({ + host: createTestHostEnvironment({ + env: { + ...process.env, + AGENT_DEVICE_STATE_DIR: stateDir, + AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0', + AGENT_DEVICE_DAEMON_SERVER_MODE: 'http', + }, + }), + stderr: { write: () => {} }, + stdout: { write: () => {} }, + composeDeps: daemonRuntimeDepsFixture({}), + }); + const { httpPort, token } = JSON.parse( + fs.readFileSync(resolveDaemonPaths(stateDir).infoPath, 'utf8'), + ) as { httpPort: number; token: string }; + daemon = { close: async () => void (await runtime.close()), httpPort, token }; +}); + +afterEach(async () => { + await daemon.close(); +}); + +async function rpc(method: string, params: Record): Promise { + const response = await fetch(`http://127.0.0.1:${daemon.httpPort}/rpc`, { + method: 'POST', + headers: { authorization: `Bearer ${daemon.token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ jsonrpc: '2.0', id: method, method, params }), + }); + return (await response.json()) as RpcBody; +} + +const allocate = (params: Record) => rpc('agent_device.lease.allocate', params); + +async function allocateLease(params: Record): Promise { + const allocated = await allocate(params); + const leaseId = allocated.result?.data?.lease?.leaseId; + expect(leaseId, JSON.stringify(allocated)).toBeTypeOf('string'); + return leaseId as string; +} + +test('an allocate that repeats every lease label but sends no lease id gets no lease id back', async () => { + const owner = { ...PROXY_SCOPE, session: 'agent-a' }; + const leaseId = await allocateLease(owner); + + const thief = await allocate({ ...owner, session: 'agent-b' }); + expect(thief.error?.data, JSON.stringify(thief)).toMatchObject({ + code: 'DEVICE_IN_USE', + details: { reason: 'DEVICE_LEASE_BUSY' }, + }); + expect(JSON.stringify(thief)).not.toContain(leaseId); + expect(thief.error?.data?.details?.leaseId).toBeUndefined(); +}); + +test('an allocate that repeats the labels of a device-less lease without its id is refused too', async () => { + const owner = { ...PLAIN_SCOPE, session: 'agent-a' }; + const leaseId = await allocateLease(owner); + + const thief = await allocate({ ...owner, session: 'agent-b' }); + expect(thief.error?.data, JSON.stringify(thief)).toMatchObject({ + code: 'DEVICE_IN_USE', + details: { reason: 'DEVICE_LEASE_BUSY' }, + }); + expect(JSON.stringify(thief)).not.toContain(leaseId); +}); + +test('the owner that sends the lease id allocates its live lease again and can release it', async () => { + const owner = { ...PROXY_SCOPE, session: 'agent-a' }; + const leaseId = await allocateLease(owner); + + const refreshed = await allocate({ ...owner, leaseId }); + expect(refreshed.result, JSON.stringify(refreshed)).toMatchObject({ + ok: true, + data: { reused: true, lease: { leaseId } }, + }); + + const released = await rpc('agent_device.lease.release', { ...owner, leaseId }); + expect(released.result?.data, JSON.stringify(released)).toMatchObject({ released: true }); + + const next = await allocate(owner); + expect(next.result?.ok, JSON.stringify(next)).toBe(true); + expect(next.result?.data?.lease?.leaseId).not.toBe(leaseId); +}); diff --git a/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts b/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts index 91f7ead218..149fb304c8 100644 --- a/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts +++ b/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts @@ -124,7 +124,7 @@ test('lease handler executes commands owned by the lease route', async () => { flags: { tenant: 'tenant-a', runId: 'run-a', - ...(command === INTERNAL_COMMANDS.leaseAllocate ? {} : { leaseId: allocated.leaseId }), + leaseId: allocated.leaseId, }, positionals: [], }, diff --git a/packages/daemon/src/sessions/handlers/__tests__/lease.test.ts b/packages/daemon/src/sessions/handlers/__tests__/lease.test.ts index 3ba3e45355..7f697bb583 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease.test.ts @@ -233,9 +233,9 @@ test('lease_allocate answers whether its request created the lease or got back a const created = await allocate(leaseId); assert.ok(created?.ok); assert.equal(created.data?.reused, false); - // A repeat for the same run binding gets that lease back, and the answer says this request did - // not create it — a client that might end the lease must end only the one its request created. - const repeated = await allocate(); + // A repeat that sends that lease id gets it back, and the answer says this request did not create + // it — a client that might end the lease must end only the one its request created. + const repeated = await allocate(leaseId); assert.ok(repeated?.ok); assert.equal((repeated.data?.lease as DeviceLease | undefined)?.leaseId, leaseId); assert.equal(repeated.data?.reused, true); @@ -503,8 +503,8 @@ test('a lease allocated without a provider keeps the TTL it was created with', a 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. +// A repeat allocation that sends its lease id gets that lease back. 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-'); @@ -528,6 +528,7 @@ test("a refused repeat allocation keeps the run's live lease", async () => { const first = await allocate(allocateRequest()); const lease = (first?.ok ? first.data?.lease : undefined) as DeviceLease; const repeat = allocateRequest(); + repeat.meta = { ...repeat.meta, leaseId: lease.leaseId }; repeat.flags = { providerOsVersion: '18.0' }; await assert.rejects( allocate(repeat), @@ -581,7 +582,7 @@ test('a repeat allocation canceled by its requester releases the reused lease', const first = await allocate(allocateRequest()); const lease = (first?.ok ? first.data?.lease : undefined) as DeviceLease; const repeat = allocateRequest(); - repeat.meta = { ...repeat.meta, requestId }; + repeat.meta = { ...repeat.meta, requestId, leaseId: lease.leaseId }; const registration = registerRequestAbort(requestId); try { await assert.rejects( diff --git a/src/__tests__/cli-leased-session.test.ts b/src/__tests__/cli-leased-session.test.ts index db40b43e9b..6aa622414d 100644 --- a/src/__tests__/cli-leased-session.test.ts +++ b/src/__tests__/cli-leased-session.test.ts @@ -138,29 +138,38 @@ function writeStoredConnection( }); } -// The daemon reuses a lease for a matching run binding (tenant, run, backend, provider, device), so -// two sessions whose allocations would bind the same run end up sharing one lease. -async function leaseIdsOnRealDaemon(allocations: CapturedDaemonRequest[]): Promise { +// The reader replays each captured allocation exactly as the CLI sent it, so it proves what the +// daemon answers that caller. An owner that sends the lease id of a live run binding gets that +// lease back; a caller that repeats the binding's labels without that id is refused as contention. +async function replayLeaseAllocationsOnRealDaemon( + allocations: CapturedDaemonRequest[], +): Promise> { const daemon = await startPublicDaemonRuntime({ serverMode: 'http' }); try { const client = createAgentDeviceClient({ daemonBaseUrl: daemon.baseUrl, daemonAuthToken: daemon.runtime.token, daemonTransport: 'http', - session: 'lease-reader', }); - const leaseIds = []; + const results: Array<{ leaseId?: string; error?: unknown }> = []; for (const allocate of allocations) { - const lease = await client.leases.allocate({ - tenant: String(scopeOf(allocate, 'tenantId')), - runId: String(scopeOf(allocate, 'runId')), - leaseBackend: 'android-instance', - leaseProvider: 'proxy', - clientId: String(scopeOf(allocate, 'clientId')), - }); - leaseIds.push(lease.leaseId); + const requestedLeaseId = scopeOf(allocate, 'leaseId'); + try { + const lease = await client.leases.allocate({ + tenant: String(scopeOf(allocate, 'tenantId')), + runId: String(scopeOf(allocate, 'runId')), + leaseBackend: 'android-instance', + leaseProvider: 'proxy', + clientId: String(scopeOf(allocate, 'clientId')), + session: String(allocate.session), + ...(requestedLeaseId === undefined ? {} : { leaseId: String(requestedLeaseId) }), + }); + results.push({ leaseId: lease.leaseId }); + } catch (error) { + results.push({ error }); + } } - return leaseIds; + return results; } finally { await daemon.close(); } @@ -192,6 +201,7 @@ test('the Node client is refused a provider lease until it names a session', asy assert.ok(leaseId); const namedPerCall = await createAgentDeviceClient(connection).leases.allocate({ ...lease, + leaseId, session: 'agent-a', }); assert.equal(namedPerCall.leaseId, leaseId); @@ -216,11 +226,15 @@ test("a second agent on the same proxy never reaches the first agent's connectio await connectProxy(shared, 'agent-b'); const openB = await runAgentCommand(shared, ['open', 'com.example', '--session', 'agent-b']); assert.equal(openB.code, null, openB.stdout); - const [leaseOfA, leaseOfB] = await leaseIdsOnRealDaemon([ + const [first, second] = await replayLeaseAllocationsOnRealDaemon([ allocationOf(openA), allocationOf(openB), ]); - assert.notEqual(leaseOfA, leaseOfB); + assert.ok(first && second); + assert.equal(first.error, undefined, String(first.error)); + assert.equal(second.error, undefined, String(second.error)); + assert.ok(first.leaseId && second.leaseId); + assert.notEqual(first.leaseId, second.leaseId); // The pointer now names B's connection; a command that names no session must never reach it. const batchSteps = '[{"command":"snapshot","input":{}}]'; @@ -479,7 +493,10 @@ function writeLeasedProfile(workspace: Workspace): string { return remoteConfig; } -test('sessions sharing one leased profile get leases of their own, and one session keeps its own', async () => { +// The same session in a fresh state dir has no saved lease id, so its CLI re-open allocates with a +// fresh id under the same labels. The daemon refuses that as contention (#4909): the labels are not +// the credential, the lease id is, and the fresh state has lost it. +test('sessions sharing one leased profile get leases of their own, and a fresh-state re-open is refused', async () => { const shared = workspace(); const remoteConfig = writeLeasedProfile(shared); const openA = await runAgentCommand(shared, [ @@ -514,13 +531,49 @@ test('sessions sharing one leased profile get leases of their own, and one sessi ]); assert.equal(openAAgain.code, null, openAAgain.stdout); - const [leaseA, leaseB, leaseAAgain] = await leaseIdsOnRealDaemon([ + const [first, second, again] = await replayLeaseAllocationsOnRealDaemon([ allocationOf(openA), allocationOf(openB), allocationOf(openAAgain), ]); - assert.notEqual(leaseA, leaseB); - assert.equal(leaseAAgain, leaseA); + assert.ok(first && second && again); + assert.equal(first.error, undefined, String(first.error)); + assert.equal(second.error, undefined, String(second.error)); + assert.ok(first.leaseId && second.leaseId); + assert.notEqual(first.leaseId, second.leaseId); + // The fresh-state re-open repeats agent-a's labels with a new id and no credential. + assert.equal(again.leaseId, undefined); + const refusal = again.error as { code?: string; details?: { leaseId?: string; reason?: string } }; + assert.equal(refusal.code, 'DEVICE_IN_USE'); + assert.equal(refusal.details?.reason, 'DEVICE_LEASE_BUSY'); + assert.equal(refusal.details?.leaseId, undefined); + + fs.rmSync(shared.root, { recursive: true, force: true }); +}); + +// The credential is the lease id: a re-open that replays the CLI's allocation, which names its id, +// gets that same lease back instead of contention. +test('a re-open that sends the lease id it saved gets its live lease back', async () => { + const shared = workspace(); + const remoteConfig = writeLeasedProfile(shared); + const openA = await runAgentCommand(shared, [ + 'open', + 'com.example', + '--session', + 'agent-a', + '--remote-config', + remoteConfig, + ]); + assert.equal(openA.code, null, openA.stdout); + const allocation = allocationOf(openA); + const savedLeaseId = scopeOf(allocation, 'leaseId'); + assert.equal(typeof savedLeaseId, 'string'); + + const [created, resumed] = await replayLeaseAllocationsOnRealDaemon([allocation, allocation]); + assert.ok(created && resumed); + assert.equal(created.error, undefined, String(created.error)); + assert.equal(resumed.error, undefined, String(resumed.error)); + assert.equal(resumed.leaseId, savedLeaseId); fs.rmSync(shared.root, { recursive: true, force: true }); }); diff --git a/src/__tests__/daemon-client-lease-device-spec.test.ts b/src/__tests__/daemon-client-lease-device-spec.test.ts index 13514bc13f..c41d6b76d2 100644 --- a/src/__tests__/daemon-client-lease-device-spec.test.ts +++ b/src/__tests__/daemon-client-lease-device-spec.test.ts @@ -70,9 +70,23 @@ test('a daemon refuses a lease allocate naming a device spec and records no leas // The answer that crosses the wire says this request created the lease, so a client that may // end a lease can tell its own from one the daemon had already issued. assert.equal(lease.created, true); + // The repeat that does not send that id is refused as contention and gets no lease id back. + await assert.rejects( + client.leases.allocate({ + tenant: 'proxy', + runId: 'run-spec', + leaseBackend: 'ios-instance', + platform: 'ios', + }), + (error: unknown) => + error instanceof AppError && + error.code === 'DEVICE_IN_USE' && + error.details?.reason === 'DEVICE_LEASE_BUSY', + ); const repeated = await client.leases.allocate({ tenant: 'proxy', runId: 'run-spec', + leaseId: LEASE_ID, leaseBackend: 'ios-instance', platform: 'ios', }); diff --git a/website/docs/docs/client-api.md b/website/docs/docs/client-api.md index 18744d20fe..50f733060c 100644 --- a/website/docs/docs/client-api.md +++ b/website/docs/docs/client-api.md @@ -349,7 +349,7 @@ Domain client methods: - `client.sessions.list()`, `stateDir()`, `close()`, `saveScript()`, `artifacts()`. `client.sessions.list()` without a configured `leaseId` omits leased sessions. - `client.apps.install()`, `reinstall()`, `uninstall()`, `installFromSource()`, `list()`, `open()`, `close()`, `push()`, `triggerEvent()` - `client.materializations.release()` -- `client.leases.allocate()`, `heartbeat()`, `release()`. A client on a lease from a lease provider must name its session, or the daemon refuses it with reason `REMOTE_SESSION_REQUIRED`. Every command on a leased session must send that lease's `leaseId`, or the daemon refuses it with `UNAUTHORIZED` and reason `LEASE_SESSION_MISMATCH`. Pass `retainOnClose: true` to `allocate()` when you release the lease yourself; session `close` then leaves it active until `release()`, expiry, or graceful 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. On iOS simulators, a healthy idle XCTest runner can stay available between those sessions. Releasing or expiring the lease stops its runner unless a session outside the lease has taken over the device. Pass `leaseId` (32 to 128 random hex characters; a shorter id fails with reason `LEASE_ID_TOO_SHORT`) to `allocate()` to name a new lease with an id the daemon has never issued, or to get back your live lease with that id when you retry with the same tenant, run, client, lease backend, and provider (and no device, or the leased one), then use the returned `leaseId`: a run that already holds a lease gets that one back, and an older daemon mints its own. `allocate()` also tells you which of those you got, on the returned lease's `created`: `true` when your request created that lease, `false` when it was already there, and omitted on `heartbeat()` or when an older daemon does not support ownership evidence. The CLI releases an allocate response it discards before recording (a spec refusal, identity refusal, or keyless replacement), unless `created` is `false`. After binding, rollback on a later preparation failure requires `created:true`. Against an older daemon that omits `created`, refused or replaced leases are released, but a bound, unrecorded lease remains until expiry if preparation fails. `allocate()` with a `leaseProvider` the daemon has no runtime for fails with `UNSUPPORTED_OPERATION`, reason `provider-not-registered`, and `details.registeredProviders`; no lease is recorded. Leases with no provider, `proxy`, or `cloud` need no runtime. +- `client.leases.allocate()`, `heartbeat()`, `release()`. A client on a lease from a lease provider must name its session, or the daemon refuses it with reason `REMOTE_SESSION_REQUIRED`. Every command on a leased session must send that lease's `leaseId`, or the daemon refuses it with `UNAUTHORIZED` and reason `LEASE_SESSION_MISMATCH`. Pass `retainOnClose: true` to `allocate()` when you release the lease yourself; session `close` then leaves it active until `release()`, expiry, or graceful 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. On iOS simulators, a healthy idle XCTest runner can stay available between those sessions. Releasing or expiring the lease stops its runner unless a session outside the lease has taken over the device. Pass `leaseId` (32 to 128 random hex characters; a shorter id fails with reason `LEASE_ID_TOO_SHORT`) to `allocate()` to name a new lease with an id the daemon has never issued, or to get back your live lease with that id when you retry with the same tenant, run, client, lease backend, and provider (and no device, or the leased one). An allocate that repeats those labels without the id of a live lease is refused with `DEVICE_IN_USE` and reason `DEVICE_LEASE_BUSY`, so always use the `leaseId` the reply carries; an older daemon ignores an id it is asked to name and answers that label-only repeat with the run's lease. `allocate()` also tells you which of those you got, on the returned lease's `created`: `true` when your request created that lease, `false` when it was already there, and omitted on `heartbeat()` or when an older daemon does not support ownership evidence. The CLI releases an allocate response it discards before recording (a spec refusal, identity refusal, or keyless replacement), unless `created` is `false`. After binding, rollback on a later preparation failure requires `created:true`. Against an older daemon that omits `created`, refused or replaced leases are released, but a bound, unrecorded lease remains until expiry if preparation fails. `allocate()` with a `leaseProvider` the daemon has no runtime for fails with `UNSUPPORTED_OPERATION`, reason `provider-not-registered`, and `details.registeredProviders`; no lease is recorded. Leases with no provider, `proxy`, or `cloud` need no runtime. - `client.metro.prepare()`, `reload()` - `client.capture.snapshot()`, `screenshot()`, `diff()` - `client.interactions.gesture()`, `click()`, `press()`, `longPress()`, `swipe()`, `pan()`, `drag()`, `fling()`, `swipeGesture()`, `focus()`, `type()`, `fill()`, `scroll()`, `pinch()`, `rotateGesture()`, `transformGesture()`, `tapGesture()`, `get()`, `is()`, `find()` diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index de21389881..f9531e1556 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -56,7 +56,7 @@ The daemon enforces the same rule for direct RPC callers. An `agent_device.comma Without `--udid` or `--serial`, `open` does not pick the device on the agent machine: it sends `--platform`, `--target`, and `--device` with the lease request, the daemon behind the proxy picks a matching device, and later commands use the device the lease names. The device therefore does not need to exist before `open`, which lets a service in front of the daemon create or choose it at that point. While that lease is active, an `open` that names a different device is refused instead of running on the leased one; close the session first, or run `connect --force` to start over. An existing lease that names no device, such as one supplied through `leaseId`, is refused with reason `LEASE_SCOPE_MISMATCH` and left active. -`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` (32 to 128 random hex characters; a shorter id fails with `INVALID_ARGS` and reason `LEASE_ID_TOO_SHORT`) the same way; repeating the id of a live lease returns that lease when the retry carries the same tenant, run, client, lease backend, and provider, and either names no device or the device the lease binds, so a retry after a lost reply does not allocate a second one. A retry without `ttlMs` keeps the lease's window. A retry that changes any of those fields is refused like any other reused id. The id identifies the lease: one run can hold several leases. Any other 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. +`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` (32 to 128 random hex characters; a shorter id fails with `INVALID_ARGS` and reason `LEASE_ID_TOO_SHORT`) the same way; repeating the id of a live lease returns that lease when the retry carries the same tenant, run, client, lease backend, and provider, and either names no device or the device the lease binds, so a retry after a lost reply does not allocate a second one. A retry without `ttlMs` keeps the lease's window. A retry that changes any of those fields is refused like any other reused id. The id identifies the lease: one run can hold several leases, and an allocate that repeats the tenant, run, backend, provider, device, and client of a live lease without sending that lease's id is refused with `DEVICE_IN_USE` and reason `DEVICE_LEASE_BUSY`. It returns no lease id. Keep the id the first reply gave you and send it on every retry; an older daemon answers a label-only repeat with that run's lease. Any id this daemon has already given another lease, active or ended, is refused with `INVALID_ARGS` and reason `LEASE_ID_IN_USE`, and without one the daemon makes the id. Several agents can share one proxy, and one machine, when each names its own session and 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.