Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/adr/0007-remote-device-leases.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
8 changes: 5 additions & 3 deletions packages/contracts/src/client-lease.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
};
Expand Down
3 changes: 2 additions & 1 deletion packages/daemon/docs/remote-device-lease-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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.

Expand Down
82 changes: 45 additions & 37 deletions packages/daemon/src/resources/__tests__/lease-registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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', () => {
Expand Down Expand Up @@ -313,37 +325,33 @@ 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');
assert.equal(second.deviceKey, 'device-1');
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', () => {
Expand Down
32 changes: 13 additions & 19 deletions packages/daemon/src/resources/lease-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string, unknown>; reused?: boolean } };
error?: { data?: { code?: string; details?: Record<string, unknown> } };
};

let daemon: { close: () => Promise<void>; 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<string, unknown>): Promise<RpcBody> {
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<string, unknown>) => rpc('agent_device.lease.allocate', params);

async function allocateLease(params: Record<string, unknown>): Promise<string> {
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);
});
Original file line number Diff line number Diff line change
Expand Up @@ -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: [],
},
Expand Down
Loading
Loading