Skip to content

Commit 8fa91ac

Browse files
authored
fix(daemon): close no longer throws tenant-isolation error on a never-allocated lease (#2029)
* fix(daemon): close no longer throws tenant-isolation error on a never-allocated lease `close` on a tenant-isolated connection (e.g. BrowserStack) whose lease was never allocated (`connect` succeeded but `open` never reached `lease_allocate`) threw a generic "tenant isolation requires lease id." error from the lease-admission gate before `close`'s own handler ever got a chance to run — masking the much clearer SESSION_NOT_FOUND / lease-less teardown path it already supports. Scoped narrowly to plain `close` (no app-target positional) so `close <app>`, which resolves its device straight from flags when there's no session, still goes through full lease/tenant admission. Fixes #2016 * fix(daemon): require session===undefined for the close lease bypass, not just a missing lease field Review on #2029 (P1): the bypass fired on any lease-less session, including a *stored* SessionState. Tenant-scoped session names are keyed by tenant, not by run, so a lease-less stored session could belong to a different run in the same tenant — a caller without a matching lease could tear it down. Narrow the bypass to session === undefined (no daemon session record at all), which is the actual deferred-connect case from #2016: `open` never ran, so the daemon never created a session to protect. Adds router-level regression tests through the real session-scoping/locked-admission/close-handler pipeline (request-execution-scope.test.ts): deferred connect with no session closes as SESSION_NOT_FOUND without ever calling the lease provider, while an app-target close and an existing lease-less stored session both still require a real lease. * test: bump workflow help-card byte budget after merging main Merging main (#2020) grew the workflow help card's "Bootstrap" line past the existing 9000-byte budget by a few bytes — unrelated to this PR's fix, just picked up by merging latest main. Bumping the budget rather than trimming #2020's recently-rewritten help copy. * fix(daemon): move close's admission bypass into the command-descriptor registry Review on #2029, P1: request-admission.ts was reclassifying req.command and req.positionals inline instead of consuming a registry predicate (ADR-0003). Added a request-sensitive DaemonCommandDescriptor trait, sessionlessPlainCloseAdmissionExempt, declared on close's descriptor via a named predicate (isPlainCloseRequest); request-admission.ts now asks the registry (isSessionlessPlainCloseAdmissionExempt) instead of matching req.command === 'close' and req.positionals.length itself. P2: reverted the workflow help-card byte-budget bump from #2030bd (9000 -> 9100) back to 9000, and instead trimmed the "Bootstrap" help line by the minimum amount ("or one provider" -> "or provider", "providers never fall back" -> "no provider fallback") to fit the existing budget with a small margin (8994 bytes). That budget regression came from #2020 on main, unrelated to this PR's close/lease-admission fix.
1 parent c77bc40 commit 8fa91ac

7 files changed

Lines changed: 291 additions & 4 deletions

File tree

‎src/cli-schema/cli-help-topics.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ test('usageForCommand resolves workflow help topic', async () => {
138138
assert.match(help, /Shapes and platform quirks: help gestures/);
139139
assert.match(
140140
help,
141-
/open --foreground -> snapshot\. Selection: explicit --device\/--udid\/--serial, then session, booted\/bootable local, or one provider; --platform\/--target only filter\./,
141+
/open --foreground -> snapshot\. Selection: explicit --device\/--udid\/--serial, then session, booted\/bootable local, or provider; --platform\/--target only filter\./,
142142
);
143143
assert.match(help, /Never open artifact paths or invent package ids/);
144144
assert.match(

‎src/cli-schema/cli-help.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ Command shape:
134134
Gestures: scroll/swipe for lists/flicks; gesture pan|fling|pinch|rotate|transform|drag for multi-touch. Shapes and platform quirks: help gestures.
135135
136136
Bootstrap:
137-
open --foreground -> snapshot. Selection: explicit --device/--udid/--serial, then session, booted/bootable local, or one provider; --platform/--target only filter. Ambiguous/empty fails with bounded retry selectors; providers never fall back.
137+
open --foreground -> snapshot. Selection: explicit --device/--udid/--serial, then session, booted/bootable local, or provider; --platform/--target only filter. Ambiguous/empty fails with bounded retry selectors; no provider fallback.
138138
Install arguments are app/package id then artifact path: agent-device install com.example.app ./dist/app.apk --platform android, then open <id> --relaunch for fresh state. Use reinstall only when explicitly requested.
139139
Unknown app id: devices, then apps, then open <discovered-app-id>. Never open artifact paths or invent package ids; ask if lookup misses the target.
140140
Apple CI: prepare ios-runner after boot/install, before replay/test (help prepare). Remote/cloud: connect -> open -> commands -> close -> disconnect (help remote). Reusable scripts, secret-safe fills, replay repair: help scripting.

‎src/core/command-descriptor/registry.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,14 @@ const isShardedTestRequest = (req: DispatchedCommand): boolean =>
168168
req.command === 'test' &&
169169
(typeof req.flags?.shardAll === 'number' || typeof req.flags?.shardSplit === 'number');
170170

171+
// #2016: a plain `close` (no app-target positional) has nothing to close via
172+
// flags, so it's the only close shape eligible for the sessionless
173+
// no-lease-anywhere admission bypass in request-admission.ts. `close <app>`
174+
// resolves its device straight from flags when there's no session and must
175+
// stay behind full lease/tenant admission.
176+
const isPlainCloseRequest = (req: DispatchedCommand): boolean =>
177+
(req.positionals?.length ?? 0) === 0;
178+
171179
// ADR 0014 request-sensitive ref-frame resolvers. The action is the leading
172180
// positional (see keyboard/alert daemon writers in src/commands/system/index.ts
173181
// and src/commands/capture/alert.ts). Only the read-only status probes preserve
@@ -927,6 +935,7 @@ export const RAW_COMMAND_DESCRIPTORS = [
927935
refFrameEffect: 'may-invalidate',
928936
allowInvalidRecording: true,
929937
saveScriptFlagOwner: true,
938+
sessionlessPlainCloseAdmissionExempt: isPlainCloseRequest,
930939
},
931940
timeoutPolicy: DEFAULT_TIMEOUT_POLICY,
932941
batchable: true,
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import { makeIosSession } from '../../__tests__/test-utils/session-factories.ts';
4+
import { LeaseRegistry } from '../lease-registry.ts';
5+
import { assertRequestLeaseAdmission } from '../request-admission.ts';
6+
import type { DaemonRequest } from '../types.ts';
7+
8+
function makeRequest(overrides: Partial<DaemonRequest> = {}): DaemonRequest {
9+
return {
10+
token: 'token',
11+
session: 'default',
12+
command: 'close',
13+
positionals: [],
14+
flags: {},
15+
...overrides,
16+
};
17+
}
18+
19+
// #2016: a tenant-isolated connection (e.g. BrowserStack) whose lease was
20+
// never allocated (`open` was never called) must not surface the generic
21+
// tenant/run/lease admission error when `close` tries to clean it up.
22+
test('close on a tenant-isolated session with no lease ever allocated admits without throwing', () => {
23+
const registry = new LeaseRegistry();
24+
25+
const result = assertRequestLeaseAdmission(
26+
makeRequest({
27+
command: 'close',
28+
meta: { tenantId: 'tenant-a', runId: 'run-1', sessionIsolation: 'tenant' },
29+
}),
30+
registry,
31+
undefined,
32+
);
33+
34+
assert.equal(result, undefined);
35+
});
36+
37+
test('close on a lease-less but stored tenant-isolated session still requires a lease id', () => {
38+
// #2016 follow-up: a *stored* session under tenant isolation is keyed by
39+
// tenant, not by run, so a lease-less stored session could belong to
40+
// another run in the same tenant. The bypass must not treat "this session
41+
// record has no lease field" as proof there's nothing to protect — only
42+
// "no session record exists at all" (the actual deferred-connect case)
43+
// qualifies.
44+
const registry = new LeaseRegistry();
45+
const session = makeIosSession('default');
46+
47+
assert.throws(
48+
() =>
49+
assertRequestLeaseAdmission(
50+
makeRequest({
51+
command: 'close',
52+
meta: { tenantId: 'tenant-a', runId: 'run-1', sessionIsolation: 'tenant' },
53+
}),
54+
registry,
55+
session,
56+
),
57+
/tenant isolation requires lease id/,
58+
);
59+
});
60+
61+
test('close with an app target still requires a lease id even with no lease anywhere', () => {
62+
// #2016 follow-up: `close <app>` with no session resolves its device
63+
// straight from flags (`closeWithoutSession`), so it must not bypass
64+
// tenant/lease admission the way a plain `close` (nothing to close) does —
65+
// otherwise any caller could close an arbitrary flag-selected device on a
66+
// tenant-isolated fleet without ever presenting a lease.
67+
const registry = new LeaseRegistry();
68+
69+
assert.throws(
70+
() =>
71+
assertRequestLeaseAdmission(
72+
makeRequest({
73+
command: 'close',
74+
positionals: ['com.example.app'],
75+
meta: { tenantId: 'tenant-a', runId: 'run-1', sessionIsolation: 'tenant' },
76+
}),
77+
registry,
78+
undefined,
79+
),
80+
/tenant isolation requires lease id/,
81+
);
82+
});
83+
84+
test('close with an explicit lease id but no session lease still requires an active lease', () => {
85+
const registry = new LeaseRegistry();
86+
87+
assert.throws(
88+
() =>
89+
assertRequestLeaseAdmission(
90+
makeRequest({
91+
command: 'close',
92+
meta: {
93+
tenantId: 'tenant-a',
94+
runId: 'run-1',
95+
leaseId: 'a'.repeat(32),
96+
sessionIsolation: 'tenant',
97+
},
98+
}),
99+
registry,
100+
undefined,
101+
),
102+
/Lease is not active/,
103+
);
104+
});
105+
106+
test('non-close commands on a tenant-isolated session still require a lease id', () => {
107+
const registry = new LeaseRegistry();
108+
109+
assert.throws(
110+
() =>
111+
assertRequestLeaseAdmission(
112+
makeRequest({
113+
command: 'snapshot',
114+
meta: { tenantId: 'tenant-a', runId: 'run-1', sessionIsolation: 'tenant' },
115+
}),
116+
registry,
117+
undefined,
118+
),
119+
/tenant isolation requires lease id/,
120+
);
121+
});
122+
123+
test('close still admits and heartbeats a real active lease', () => {
124+
let now = 1_000;
125+
const registry = new LeaseRegistry({ now: () => now });
126+
const lease = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' });
127+
const session = makeIosSession('default', {
128+
lease: {
129+
leaseId: lease.leaseId,
130+
tenantId: lease.tenantId,
131+
runId: lease.runId,
132+
leaseBackend: lease.backend,
133+
expiresAt: lease.expiresAt,
134+
},
135+
});
136+
now = 2_000;
137+
138+
const result = assertRequestLeaseAdmission(
139+
makeRequest({
140+
command: 'close',
141+
meta: { tenantId: 'tenant-a', runId: 'run-1', sessionIsolation: 'tenant' },
142+
}),
143+
registry,
144+
session,
145+
);
146+
147+
assert.equal(result?.leaseId, lease.leaseId);
148+
assert.equal(result?.heartbeatAt, 2_000);
149+
});

‎src/daemon/__tests__/request-execution-scope.test.ts‎

Lines changed: 91 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { afterAll, test, expect } from 'vitest';
1+
import { afterAll, test, expect, vi } from 'vitest';
22
import fs from 'node:fs';
33
import path from 'node:path';
44
import {
@@ -23,6 +23,7 @@ import { resolveSessionRequestLogPath } from '../session-store.ts';
2323
import type { DaemonRequest } from '../types.ts';
2424
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
2525
import { makeTestScreenRecordingResource } from '../../__tests__/test-utils/screen-recording-live-handle.ts';
26+
import { handleCloseCommand } from '../handlers/session-close.ts';
2627

2728
const TEST_ROOT = mkdtempForTestSync('agent-device-request-execution-scope-');
2829
const LOG_PATH = path.join(TEST_ROOT, 'diagnostics.log');
@@ -754,6 +755,95 @@ test('runLocked rejects a request canceled while waiting for its execution lock'
754755
}
755756
});
756757

758+
// #2016 router-level regression: a deferred remote connection (`connect`
759+
// succeeded, `open` never ran, so the daemon never allocated a lease or
760+
// created a session) reaches `close`'s own SESSION_NOT_FOUND outcome
761+
// through the real tenant-scoping + locked-admission pipeline, rather than
762+
// throwing the generic tenant-isolation error before `handleCloseCommand`
763+
// ever runs. No provider is touched — there is nothing to release.
764+
test('router: deferred tenant connect with no daemon session closes as SESSION_NOT_FOUND without touching the provider', async () => {
765+
const sessionStore = makeSessionStore('agent-device-request-scope-');
766+
const leaseRegistry = new LeaseRegistry();
767+
const release = vi.fn(async () => ({}));
768+
769+
const scope = await createRequestExecutionScope({
770+
req: makeRequest({
771+
session: 'default',
772+
command: 'close',
773+
meta: { tenantId: 'tenant-a', runId: 'run-1', sessionIsolation: 'tenant' },
774+
}),
775+
sessionStore,
776+
leaseRegistry,
777+
});
778+
expect(scope.sessionName).toBe('tenant-a:default');
779+
780+
const response = await scope.runLocked(async () =>
781+
handleCloseCommand({
782+
req: scope.req,
783+
sessionName: scope.sessionName,
784+
logPath: scope.requestLogPath,
785+
sessionStore,
786+
leaseRegistry,
787+
leaseLifecycleProvider: { release },
788+
}),
789+
);
790+
791+
expect(response.ok).toBe(false);
792+
if (!response.ok) {
793+
expect(response.error.code).toBe('SESSION_NOT_FOUND');
794+
}
795+
expect(release).not.toHaveBeenCalled();
796+
});
797+
798+
// The same deferred connection, but with an app-target `close <app>`. This
799+
// must not reach `handleCloseCommand` at all — an app-target close with no
800+
// session resolves its device straight from flags, so it stays behind full
801+
// lease/tenant admission (the router rejects it before dispatch).
802+
test('router: deferred tenant connect still refuses an app-target close before dispatch', async () => {
803+
const sessionStore = makeSessionStore('agent-device-request-scope-');
804+
const leaseRegistry = new LeaseRegistry();
805+
806+
const scope = await createRequestExecutionScope({
807+
req: makeRequest({
808+
session: 'default',
809+
command: 'close',
810+
positionals: ['com.example.app'],
811+
meta: { tenantId: 'tenant-a', runId: 'run-1', sessionIsolation: 'tenant' },
812+
}),
813+
sessionStore,
814+
leaseRegistry,
815+
});
816+
817+
await expect(scope.runLocked(async () => 'unreachable')).rejects.toThrow(
818+
/tenant isolation requires lease id/,
819+
);
820+
});
821+
822+
// A stored session that already exists under this tenant-scoped name but
823+
// happens to carry no lease must still be refused: it could belong to a
824+
// different run in the same tenant (sessions are tenant-scoped, not
825+
// run-scoped), so a missing lease field alone is not proof of ownership.
826+
test('router: an existing lease-less session under tenant isolation still refuses close', async () => {
827+
const sessionStore = makeSessionStore('agent-device-request-scope-');
828+
sessionStore.set('tenant-a:default', makeIosSession('tenant-a:default'));
829+
const leaseRegistry = new LeaseRegistry();
830+
831+
const scope = await createRequestExecutionScope({
832+
req: makeRequest({
833+
session: 'default',
834+
command: 'close',
835+
meta: { tenantId: 'tenant-a', runId: 'run-1', sessionIsolation: 'tenant' },
836+
}),
837+
sessionStore,
838+
leaseRegistry,
839+
});
840+
expect(scope.sessionName).toBe('tenant-a:default');
841+
842+
await expect(scope.runLocked(async () => 'unreachable')).rejects.toThrow(
843+
/tenant isolation requires lease id/,
844+
);
845+
});
846+
757847
function makeRequest(overrides: Partial<DaemonRequest> = {}): DaemonRequest {
758848
return {
759849
token: 'test-token',

‎src/daemon/daemon-command-registry.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,17 @@ export type DaemonCommandDescriptor = {
4444
preferExplicitDeviceOverExistingSession?: boolean;
4545
allowSessionlessDefaultDevice?: (req: DaemonRequest) => boolean;
4646
skipSessionlessProviderDevice?: (req: DaemonRequest) => boolean;
47+
/**
48+
* #2016: this request shape is eligible for the sessionless,
49+
* no-lease-anywhere lease-admission bypass — a session that was never
50+
* created (deferred `connect`, `open` never ran) has no lease to admit or
51+
* release. Only `close` declares it, and only for the plain-close shape
52+
* (no app-target positional): `close <app>` resolves its device straight
53+
* from flags when there's no session, so it must stay behind full
54+
* lease/tenant admission. Declared here so `request-admission.ts` asks the
55+
* registry instead of reclassifying `req.command`/`req.positionals` itself.
56+
*/
57+
sessionlessPlainCloseAdmissionExempt?: (req: DaemonRequest) => boolean;
4758
};
4859

4960
export type DaemonProviderDeviceResolutionIntent =
@@ -121,6 +132,12 @@ export function usesSessionlessDefaultProviderDevice(req: DaemonRequest): boolea
121132
return typeof allow === 'function' ? allow(req) : false;
122133
}
123134

135+
/** #2016: whether this request qualifies for the sessionless plain-close lease-admission bypass. */
136+
export function isSessionlessPlainCloseAdmissionExempt(req: DaemonRequest): boolean {
137+
const exempt = getDaemonCommandDescriptor(req.command)?.sessionlessPlainCloseAdmissionExempt;
138+
return typeof exempt === 'function' ? exempt(req) : false;
139+
}
140+
124141
/**
125142
* ADR 0014: the ref-frame effect a request resolves to, honoring the
126143
* request-sensitive resolver form. Returns `undefined` for commands with no

‎src/daemon/request-admission.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import { AppError } from '@agent-device/kernel/errors';
22
import { normalizeTenantId, resolveSessionIsolationMode } from './config.ts';
33
import { isTenantOwnedSessionName, tenantScopedSessionName } from './session-tenant-scope.ts';
4-
import { isLeaseAdmissionExempt } from './daemon-command-registry.ts';
4+
import {
5+
isLeaseAdmissionExempt,
6+
isSessionlessPlainCloseAdmissionExempt,
7+
} from './daemon-command-registry.ts';
58
import {
69
DEFAULT_PROXY_LEASE_TTL_MS,
710
findMissingProxyLeaseFields,
@@ -69,6 +72,25 @@ export function assertRequestLeaseAdmission(
6972
const requestLeaseScope = resolveLeaseScope(req);
7073
assertProxyOpenLeaseMetadata(req, requestLeaseScope);
7174
const sessionLease = session?.lease;
75+
// #2016: a tenant-isolated connection that never reached `open` has no
76+
// daemon session and no lease to admit or release. Falling through would
77+
// make the generic tenant/run/lease check below throw "tenant isolation
78+
// requires lease id.", which reads as an access-control failure instead of
79+
// "nothing to close". Let the close handler's own session lookup return
80+
// its SESSION_NOT_FOUND response instead. Requires `session === undefined`,
81+
// not just a lease-less session: a *stored* session under tenant isolation
82+
// is keyed by tenant, not by run, so a lease-less stored session could
83+
// belong to another run in the same tenant — admission must still verify a
84+
// matching lease before that run's session can be torn down. Which request
85+
// shape qualifies (plain `close`, not an app-target `close <app>`) is the
86+
// registry's call, not this module's — see `sessionlessPlainCloseAdmissionExempt`.
87+
if (
88+
session === undefined &&
89+
!requestLeaseScope.leaseId &&
90+
isSessionlessPlainCloseAdmissionExempt(req)
91+
) {
92+
return undefined;
93+
}
7294
if (!sessionLease && req.meta?.sessionIsolation !== 'tenant') {
7395
if (!requestLeaseScope.leaseId) return undefined;
7496
if (!requestLeaseScope.tenantId && !requestLeaseScope.runId) return undefined;

0 commit comments

Comments
 (0)