From 341834bf902af962df0c67ddfed49300b6c291cd Mon Sep 17 00:00:00 2001 From: Jason Morse <35609178+JasonVMo@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:23:03 -0800 Subject: [PATCH 1/2] Isolate MCP connection authority and await descendant grant drains Separate permission scopes, attenuate each connection into a child principal, and preserve terminal-only cleanup proof across failed drains and lost responses. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .changeset/f12-connection-grants.md | 9 + packages/agentic/desktop-driver-mcp/AGENTS.md | 8 +- packages/agentic/desktop-driver-mcp/README.md | 5 +- .../references/connection.md | 47 +++-- .../references/current-status.md | 31 ++-- .../desktop-driver-mcp/src/controller.ts | 42 ++++- .../desktop-driver-mcp/src/server.test.ts | 164 ++++++++++++++++-- .../agentic/desktop-driver-mcp/src/server.ts | 5 + packages/agentic/desktop-driver/AGENTS.md | 5 + packages/agentic/desktop-driver/README.md | 6 + .../references/current-status.md | 39 +++-- .../desktop-driver/references/security.md | 43 ++++- .../desktop-driver/references/service.md | 12 +- .../src/authority/delegation.test.ts | 144 +++++++++++++++ .../src/authority/grants.test.ts | 47 ++++- .../desktop-driver/src/authority/grants.ts | 150 ++++++++++++++-- .../desktop-driver/src/authority/index.ts | 2 +- .../src/client/DesktopDriverClient.ts | 19 ++ .../src/server/createDesktopDriverServer.ts | 33 +++- .../src/server/delegation.test.ts | 161 +++++++++++++++++ .../src/testing/protocolHarness.ts | 3 +- 21 files changed, 879 insertions(+), 96 deletions(-) create mode 100644 .changeset/f12-connection-grants.md create mode 100644 packages/agentic/desktop-driver/src/authority/delegation.test.ts create mode 100644 packages/agentic/desktop-driver/src/server/delegation.test.ts diff --git a/.changeset/f12-connection-grants.md b/.changeset/f12-connection-grants.md new file mode 100644 index 0000000000..34f3b23083 --- /dev/null +++ b/.changeset/f12-connection-grants.md @@ -0,0 +1,9 @@ +--- +'@fluentui-react-native/desktop-driver': patch +'@fluentui-react-native/desktop-driver-mcp': patch +--- + +Separate driver, declared-workload, and recovery grant scopes. Add bounded, +attenuated connection principals and awaitable descendant revocation with +retryable terminal-only cleanup proof. Isolate MCP sessions per connection and +keep descriptor credentials out of diagnostics. diff --git a/packages/agentic/desktop-driver-mcp/AGENTS.md b/packages/agentic/desktop-driver-mcp/AGENTS.md index 6152388a43..4c69ec530e 100644 --- a/packages/agentic/desktop-driver-mcp/AGENTS.md +++ b/packages/agentic/desktop-driver-mcp/AGENTS.md @@ -27,12 +27,16 @@ only maps them onto MCP. cleanup responsibility after transport loss; reverify discovery and never replay a failed mutation. A verified replacement invalidates old references. Fence a lost acquisition response; disposal also cleans up late acquisitions. +- Delegate a distinct driver-only child after verified discovery. Retain it on + same-incarnation/descriptor-principal rediscovery; never share or resume another + connection's session. Disposal awaits child revocation, keeping terminal-only + cleanup proof for lost responses and failed drains; unauthorized is not cleanup. - Tie every artifact link to its session. Artifact ids restart in each session. - Progress ticks come from the adapter and never reach the service, so a waiting model does not keep an idle session alive. Cancellation aborts the HTTP call, which the service treats as the caller leaving. -- Messages the model reads are fixed or bounded. Connection failures name no - paths; the details go to stderr. +- Messages the model reads are fixed or bounded. Connection failures use fixed + diagnostics on stderr too; never echo discovery exceptions or descriptor contents. ## Validation diff --git a/packages/agentic/desktop-driver-mcp/README.md b/packages/agentic/desktop-driver-mcp/README.md index 07a0406810..6fdf584d5a 100644 --- a/packages/agentic/desktop-driver-mcp/README.md +++ b/packages/agentic/desktop-driver-mcp/README.md @@ -17,7 +17,10 @@ The adapter does not start anything. A trusted supervisor runs the Desktop Driver service with an authority, issues the agent a grant, and publishes a private connection descriptor. The adapter reads that descriptor, has the installed native helper verify the listening service's process identity, and -only then sends the grant. See +only then sends the grant to obtain its own driver-only child principal. Two +connections reading the same descriptor cannot share sessions. Disposal revokes +and drains the child, including ambiguous acquisitions; old services without +delegation fail closed. See [Connection and setup](references/connection.md). ## Use it diff --git a/packages/agentic/desktop-driver-mcp/references/connection.md b/packages/agentic/desktop-driver-mcp/references/connection.md index 97c90e0205..72da1b6963 100644 --- a/packages/agentic/desktop-driver-mcp/references/connection.md +++ b/packages/agentic/desktop-driver-mcp/references/connection.md @@ -23,6 +23,13 @@ four things before an agent connects: connection descriptor holding the service URL, the grant, and that identity. 4. Removes the descriptor after the service drains. +The descriptor grant defaults to `driver-control`. After verification, each MCP +controller uses `delegateConnection()` to obtain a distinct driver-only child +client. The child credential never enters tool results or diagnostics. Older or +unprotected services without the delegation route are explicitly unsupported by +this adapter, not a fallback to shared session authority. The generic driver's +unprotected mode is unchanged. + The descriptor format, storage, and verifier contracts belong to `@fluentui-react-native/desktop-driver` (its service reference, "Private connection descriptors"). @@ -86,7 +93,8 @@ desktop-driver-mcp [--descriptor ] [--root ] | `--root ` | The private storage root, when the supervisor published somewhere other than the platform default. It must be absolute and canonical. | The adapter speaks MCP over stdio until the client closes stdin, then stops -admissions and attempts to delete its session, including late acquisition. +admissions and attempts to revoke and drain its child, including late or +ambiguous acquisitions. Cleanup waits at most ten seconds; an unresolved attempt continues while the process lives and reports to stderr. Service drain/expiry is still needed when the adapter cannot confirm deletion. `--help` and `--version` write to stderr so stdout @@ -104,29 +112,42 @@ service then confirms its incarnation. The adapter connects on the first tool call, not at startup, so it can start before the service. When the service cannot be reached, a tool returns the -fixed reason `service-unavailable`; the cause, which may name local paths, goes -to stderr. Transport failure invalidates the cached connection, **not** known +fixed reason `service-unavailable`; stderr reports a fixed diagnostic without +echoing discovery errors, which may contain paths or credentials. +Transport failure invalidates the cached connection, **not** known session cleanup responsibility. The next call re-verifies discovery. The same -verified service incarnation and non-secret grant principal can rebind the -known session. A replacement service or an authoritative invalid/revoked +verified service incarnation and descriptor principal reuse the controller's +existing private child client, never another connection's child. This retains +known-session cleanup responsibility rather than resuming across connections. +A replacement service or an authoritative invalid/revoked session invalidates old references; open a new session and observe again. Nothing automatically replays the failed operation. Operations, acquisition, close, and complete resource reads are serialized per -MCP connection. Disposal stops admission immediately and cleans up a session -whose acquisition completes late. A failed DELETE retains responsibility until -confirmed deletion or authoritative invalidation. A lost create response has +MCP connection. Disposal stops admission immediately and drains the child, +including sessions whose acquisition completes late. A failed session DELETE +retains responsibility until confirmed deletion or authoritative invalidation. +A lost create response has no safely known session id: `session-uncertain` fences further acquisition and -mutation. Revoke the old grant (and drain it) or replace the service through the -trusted supervisor; do not guess an id or acquire again under the same authority. +mutation. Close the MCP connection to revoke and drain its child, or have the +supervisor revoke and drain the parent. Do not guess an id or acquire again +under the same child. A new principal on the same live service does not prove that the old session -ended. The adapter first attempts cleanup with the old authority, or verifies -its revocation. Current descriptors share one supervisor-issued agent grant, -not isolated per-MCP-connection grants. Grant labels are not principals. +ended. The adapter first awaits terminal cleanup with the old child before +delegating from a replacement descriptor principal. Grant labels are not +principals. A revoked child credential is retained solely to retry its own +`DELETE /furn/grants/current` cleanup after a lost response or failed drain; +unauthorized is never treated as successful cleanup. Repeated disposal can +retry an incomplete cleanup while the process remains alive. There is no resume across different MCP connections and no crash-safe native recovery promise; see [current status](current-status.md). +The authority limits delegation to eight edges and 4096 grants per service +incarnation, including revoked roots/children. Exhaustion is explicit and +requires an operator-controlled drain and service replacement. Cleanup proof +is never silently evicted or reused. + ## Embedding `createDesktopDriverMcpServer({ connect, version })` returns an SDK `McpServer` diff --git a/packages/agentic/desktop-driver-mcp/references/current-status.md b/packages/agentic/desktop-driver-mcp/references/current-status.md index 0e72ce554d..f32e7ce147 100644 --- a/packages/agentic/desktop-driver-mcp/references/current-status.md +++ b/packages/agentic/desktop-driver-mcp/references/current-status.md @@ -19,21 +19,22 @@ and the generalized management facet is ## Capability matrix -| Capability | State | Boundary/remaining work | -| ------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Six tools over shared driver schemas | Done | Session, observe, act, check, capture, story. No separate execution path. | -| Private descriptor and native identity verification | Done | Verifies before sending a grant. No model URL/token/config/executable input. | -| Single-flight connection/session lifetime | Done | Serial acquisition, close, operations and resource reads; late acquisition after dispose is cleaned up. | -| Same-port protected restart/revocation | Done in deterministic contracts | Invalid authority is forgotten; next call re-verifies discovery. No mutation replay. Live endpoint reruns remain required. | -| Same-authority transport retry | Done, bounded semantics | Retain known session cleanup responsibility and rebind only after verification of the same incarnation/principal. This is not cross-MCP-connection resume. | -| Lost create response | Fenced; recovery in progress | `session-uncertain`; no repeated acquisition. Operator must revoke the old grant or replace the service. No session-enumeration shortcut. | -| Failed delete/disconnect | Done with limits | Keep known-session responsibility; bounded dispose wait leaves late cleanup attached. Unreachable-service cleanup cannot be guaranteed; service drain/expiry remains necessary. | -| Launch-mode discovery | Done | Status lists effective launch/attach modes; no predictable attach-first failure against launch-only targets. | -| Progress, cancellation, paged image resources | Done | Progress does not renew idle sessions; artifacts are session-bound and hash-checked. | -| Storybook control | Experimental | Driver selection/marker path exists; channel ingress/reconnect and full exclusive context authority remain incomplete. | -| Per-connection attenuated grants and resumable sessions | Work in progress | Current supervisor publishes one shared agent grant. Labels are not client isolation. | -| Workload/test orchestration tools | Work in progress | Belong to a future harness control/client surface; adapter never becomes the resource owner. | -| General MCP-client qualification | Work in progress | SDK stdio evidence exists; client-specific resource/image/cancellation behavior needs independent runs. | +| Capability | State | Boundary/remaining work | +| --------------------------------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Six tools over shared driver schemas | Done | Session, observe, act, check, capture, story. No separate execution path. | +| Private descriptor and native identity verification | Done | Verifies before sending a grant. No model URL/token/config/executable input. | +| Single-flight connection/session lifetime | Done | Serial acquisition, close, operations and resource reads; late acquisition after dispose is cleaned up. | +| Same-port protected restart/revocation | Done in deterministic contracts | Invalid authority is forgotten; next call re-verifies discovery. No mutation replay. Live endpoint reruns remain required. | +| Same-authority transport retry | Done, bounded semantics | Retain known session cleanup responsibility and rebind only after verification of the same incarnation/principal. This is not cross-MCP-connection resume. | +| Lost create response | Fenced; child drain implemented | `session-uncertain`; no repeated acquisition. Connection disposal revokes and drains the child, including unknown session ids. Live descriptor-path reruns not run for this change. | +| Failed delete/disconnect | Done with limits | Keep known-session responsibility; bounded dispose wait leaves late cleanup attached. Unreachable-service cleanup cannot be guaranteed; service drain/expiry remains necessary. | +| Launch-mode discovery | Done | Status lists effective launch/attach modes; no predictable attach-first failure against launch-only targets. | +| Progress, cancellation, paged image resources | Done | Progress does not renew idle sessions; artifacts are session-bound and hash-checked. | +| Storybook control | Experimental | Driver selection/marker path exists; channel ingress/reconnect and full exclusive context authority remain incomplete. | +| Per-connection attenuated grants | Done in deterministic contracts | Each controller delegates a distinct driver-only child after verification; target/scope subsets and terminal-only cleanup retry. Native descriptor-path qualification not run for this change. | +| Cross-connection session resume | Intentionally unsupported | No lease/grace or ownership-transfer protocol. Same-controller rediscovery retains its existing child; no automatic replay or cross-connection resume. | +| Workload/test orchestration tools | Work in progress | Belong to a future harness control/client surface; adapter never becomes the resource owner. | +| General MCP-client qualification | Work in progress | SDK stdio evidence exists; client-specific resource/image/cancellation behavior needs independent runs. | See [connection](connection.md) and [tools](tools.md) for exact behavior. Native and Storybook limitations are tracked in diff --git a/packages/agentic/desktop-driver-mcp/src/controller.ts b/packages/agentic/desktop-driver-mcp/src/controller.ts index c93ac46042..969d462bd8 100644 --- a/packages/agentic/desktop-driver-mcp/src/controller.ts +++ b/packages/agentic/desktop-driver-mcp/src/controller.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto'; import { DesktopSessionClient } from '@fluentui-react-native/desktop-driver/client'; -import type { OperationCallOptions } from '@fluentui-react-native/desktop-driver/client'; +import type { DesktopDriverClient, OperationCallOptions } from '@fluentui-react-native/desktop-driver/client'; import type { ArtifactResult, OperationResponse } from '@fluentui-react-native/desktop-driver/operations'; import type { ConnectDesktopDriver, DesktopDriverConnection } from './connection.js'; @@ -48,6 +48,7 @@ const maxArtifactBytes = 16 * 1024 * 1024; export class DesktopController { readonly #connect: ConnectDesktopDriver; #connection?: DesktopDriverConnection; + #binding?: { root: DesktopDriverConnection; child: DesktopDriverConnection }; #open?: OpenSession; #uncertain?: DesktopDriverConnection; #pending: Promise = Promise.resolve(); @@ -198,8 +199,12 @@ export class DesktopController { this.#disconnected.abort(); return (this.#disposing ??= (async () => { const cleanup = this.#pending.then(async () => { - await this.closeSession(); - this.assertCertain(); + if (this.#binding) { + await this.#binding.child.client.revokeConnection(); + this.#open = undefined; + this.#uncertain = undefined; + this.#binding = undefined; + } }); this.#pending = cleanup.catch(() => { console.error('desktop-driver-mcp: session cleanup is incomplete; the service must drain or expire the session.'); @@ -218,6 +223,7 @@ export class DesktopController { ]); } finally { if (timer) clearTimeout(timer); + if (this.#binding) this.#disposing = undefined; } })()); } @@ -227,11 +233,35 @@ export class DesktopController { let connection: DesktopDriverConnection; try { connection = await this.#connect(); - } catch (error) { - // The cause can name machine-local paths; the operator reads it on stderr, the model reads a fixed message. - console.error(`desktop-driver-mcp: connecting failed: ${error instanceof Error ? error.message : String(error)}`); + } catch { + // Discovery failures can contain descriptor credentials; neither protocol output nor diagnostics may echo them. + console.error('desktop-driver-mcp: connecting failed; verify private discovery and the service identity.'); throw new AdapterError('service-unavailable', 'The Desktop Driver service is not available. Ask the operator to start it.'); } + const binding = this.#binding; + if (binding && binding.root.incarnation === connection.incarnation && binding.root.principal === connection.principal) { + connection = binding.child; + } else { + if (binding && binding.root.incarnation === connection.incarnation) { + await this.guard(() => binding.child.client.revokeConnection()); + this.#open = undefined; + this.#uncertain = undefined; + } + const root = connection; + let child: DesktopDriverClient; + try { + child = await this.guard(() => root.client.delegateConnection()); + } catch (error) { + if (isWebDriverError(error) && ['unknown command', 'unsupported operation'].includes(error.code)) { + throw new AdapterError('connection-authority-unsupported', 'The service does not support isolated connection authority.'); + } + throw error; + } + const principal = child.principalId; + if (!principal) throw new AdapterError('service-unavailable', 'The service does not support isolated connection authority.'); + connection = { client: child, incarnation: root.incarnation, principal }; + this.#binding = { child: connection, root }; + } const previous = this.#open?.connection ?? this.#uncertain; if (previous && previous.incarnation !== connection.incarnation) { this.#open = undefined; diff --git a/packages/agentic/desktop-driver-mcp/src/server.test.ts b/packages/agentic/desktop-driver-mcp/src/server.test.ts index abdbff0986..10c4e5b3fd 100644 --- a/packages/agentic/desktop-driver-mcp/src/server.test.ts +++ b/packages/agentic/desktop-driver-mcp/src/server.test.ts @@ -3,7 +3,10 @@ import { createHash, randomBytes } from 'node:crypto'; import { createDesktopDriverClient } from '@fluentui-react-native/desktop-driver/client'; import { DesktopAuthority } from '@fluentui-react-native/desktop-driver/authority'; import type { DesktopStoryManifest } from '@fluentui-react-native/desktop-driver/storybook'; -import { createDesktopDriverStoryHarness, createDesktopDriverTestHarness } from '@fluentui-react-native/desktop-driver/testing'; +import { + createDesktopDriverStoryHarness as createStoryHarness, + createDesktopDriverTestHarness as createTestHarness, +} from '@fluentui-react-native/desktop-driver/testing'; import type { DesktopDriverTestHarness } from '@fluentui-react-native/desktop-driver/testing'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; @@ -17,6 +20,30 @@ type Fixture = { client: Client; harness: DesktopDriverTestHarness }; const features = { accessibilityActions: true, boundedObservation: true }; const onePixelPng = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='; +const connections = new WeakMap(); + +async function createDesktopDriverTestHarness( + options: Parameters[0] = {}, + story?: Parameters[1], + serverOptions: Parameters[2] = {}, +): Promise { + const authority = serverOptions.authority ?? new DesktopAuthority(); + const grant = authority.issue({ label: 'test', targets: '*' }); + const harness = await createTestHarness(options, story, { ...serverOptions, authority }); + connections.set(harness, { authority, token: grant.token }); + return harness; +} + +async function createDesktopDriverStoryHarness( + manifest: DesktopStoryManifest, + options: Parameters[1], +): Promise { + const authority = new DesktopAuthority(); + const grant = authority.issue({ label: 'test', targets: '*' }); + const harness = await createStoryHarness(manifest, options, { authority }); + connections.set(harness, { authority, token: grant.token }); + return harness; +} async function connectClient(connect: ConnectDesktopDriver, progressIntervalMs?: number): Promise { const server = createDesktopDriverMcpServer({ connect, version: '0.0.0-test', ...(progressIntervalMs ? { progressIntervalMs } : {}) }); @@ -24,6 +51,11 @@ async function connectClient(connect: ConnectDesktopDriver, progressIntervalMs?: await server.connect(serverTransport); const client = new Client({ name: 'test', version: '1.0.0' }); await client.connect(clientTransport); + const close = client.close.bind(client); + client.close = async () => { + await close(); + await server.close(); + }; return client; } @@ -44,10 +76,12 @@ async function withFixture( } function testConnection(harness: DesktopDriverTestHarness, fetcher?: typeof fetch): DesktopDriverConnection { + const connection = connections.get(harness); + if (!connection) throw new Error('Missing fixture authority.'); return { - client: createDesktopDriverClient({ url: harness.server.url, ...(fetcher ? { fetch: fetcher } : {}) }), - incarnation: harness.server.url, - principal: 'test', + client: createDesktopDriverClient({ grant: connection.token, url: harness.server.url, ...(fetcher ? { fetch: fetcher } : {}) }), + incarnation: connection.authority.incarnation, + principal: connection.token.split('.')[1], }; } @@ -78,6 +112,107 @@ async function open(client: Client, harness: DesktopDriverTestHarness): Promise< } describe('desktop-driver-mcp', () => { + test('isolates controllers sharing a descriptor principal instead of sharing sessions', async () => { + const harness = await createDesktopDriverTestHarness({ features }); + const first = new DesktopController(async () => testConnection(harness)); + const second = new DesktopController(async () => testConnection(harness)); + try { + const session = await first.open({ launch: true, target: harness.target.id }); + const owner = harness.server.sessions.get(session.id).owner?.grantId; + expect(owner).not.toBe(testConnection(harness).principal); + expect((await second.status()).session).toBeUndefined(); + await expect(second.run('observe', {})).rejects.toMatchObject({ reason: 'no-session' }); + await expect(second.open({ launch: true, target: harness.target.id })).rejects.toMatchObject({ code: 'session not created' }); + await first.dispose(); + const next = await second.open({ launch: true, target: harness.target.id }); + expect(harness.server.sessions.get(next.id).owner?.grantId).not.toBe(owner); + } finally { + await first.dispose(); + await second.dispose(); + await harness.close(); + } + }); + + test('refuses old or unprotected services rather than falling back to shared authority', async () => { + const harness = await createTestHarness({ features }); + const controller = new DesktopController(async () => ({ + client: createDesktopDriverClient({ url: harness.server.url }), + incarnation: 'legacy', + principal: 'legacy', + })); + try { + await expect(controller.status()).rejects.toMatchObject({ reason: 'connection-authority-unsupported' }); + } finally { + await controller.dispose(); + await harness.close(); + } + }); + + test.each(['lost-response', 'drain-failure', 'unauthorized'] as const)( + 'retains terminal cleanup responsibility after %s', + async (failure) => { + const errors = jest.spyOn(console, 'error').mockImplementation(() => undefined); + const harness = await createDesktopDriverTestHarness({ features }); + let revocations = 0; + const connection = testConnection(harness, async (input, init) => { + const response = await fetch(input, init); + if (String(input).endsWith('/furn/grants/current')) { + revocations += 1; + if (revocations === 1 && failure === 'lost-response') { + await response.body?.cancel(); + throw new Error('injected revoke response loss'); + } + if (revocations === 1 && failure === 'unauthorized') { + await response.body?.cancel(); + return new Response(JSON.stringify({ value: { error: 'unauthorized', message: 'injected auth failure' } }), { + status: 401, + headers: { 'content-type': 'application/json' }, + }); + } + } + return response; + }); + const controller = new DesktopController(async () => connection); + try { + const session = await controller.open({ launch: true, target: harness.target.id }); + if (failure === 'drain-failure') { + jest.spyOn(harness.server.sessions, 'deleteOwnedBy').mockRejectedValueOnce(new Error('injected drain failure')); + } + await controller.dispose(); + expect(controller.session).toBe(session.id); + expect(errors).toHaveBeenCalledWith( + 'desktop-driver-mcp: session cleanup is incomplete; the service must drain or expire the session.', + ); + await controller.dispose(); + expect(controller.session).toBeUndefined(); + expect(revocations).toBe(2); + expect(() => harness.server.sessions.get(session.id)).toThrow(); + } finally { + await controller.dispose(); + await harness.close(); + errors.mockRestore(); + } + }, + ); + + test('never echoes discovery failure contents to diagnostics or model output', async () => { + const errors = jest.spyOn(console, 'error').mockImplementation(() => undefined); + const sensitive = 'fdg1.private-principal.private-credential'; + const client = await connectClient(async () => { + throw new Error(sensitive); + }); + try { + const result = await call(client, 'desktop_session'); + expect(result.isError).toBe(true); + expect(JSON.stringify(result)).not.toContain(sensitive); + expect(errors).toHaveBeenCalledWith('desktop-driver-mcp: connecting failed; verify private discovery and the service identity.'); + expect(JSON.stringify(errors.mock.calls)).not.toContain(sensitive); + } finally { + await client.close(); + errors.mockRestore(); + } + }); + test('offers six tools with bounded schemas, and lists the service targets', async () => { await withFixture({}, async ({ client, harness }) => { const { tools } = await client.listTools(); @@ -352,7 +487,8 @@ describe('desktop-driver-mcp', () => { unavailable = true; const refused = await call(client, 'desktop_session'); expect(JSON.stringify(json(refused))).not.toContain('/private/path'); - expect(errors).toHaveBeenCalledWith(expect.stringContaining('/private/path')); + expect(errors).toHaveBeenCalledWith('desktop-driver-mcp: connecting failed; verify private discovery and the service identity.'); + expect(JSON.stringify(errors.mock.calls)).not.toContain('/private/path'); unavailable = false; harness = await createDesktopDriverTestHarness({ features }); @@ -367,7 +503,7 @@ describe('desktop-driver-mcp', () => { test('ends the open session when the MCP client goes away', async () => { const harness = await createDesktopDriverTestHarness({ features }); - const driver = createDesktopDriverClient({ url: harness.server.url }); + const driver = testConnection(harness).client; const client = await connectClient(async () => ({ ...testConnection(harness), client: driver })); try { const session = await open(client, harness); @@ -375,10 +511,11 @@ describe('desktop-driver-mcp', () => { const started = Date.now(); let gone = false; while (!gone && Date.now() - started < 3000) { - gone = await driver.request('GET', `/session/${session}/window`).then( - () => false, - (error: { code?: string }) => error.code === 'invalid session id', - ); + try { + harness.server.sessions.get(session); + } catch { + gone = true; + } } expect(gone).toBe(true); } finally { @@ -505,8 +642,10 @@ describe('desktop-driver-mcp', () => { test('retains the session after a lost mutation response without replaying the mutation', async () => { const harness = await createDesktopDriverTestHarness({ features }); let mutations = 0; + let delegations = 0; const connection = testConnection(harness, async (input, init) => { const response = await fetch(input, init); + if (String(input).endsWith('/furn/grants/connection')) delegations += 1; if (String(input).endsWith('/furn/ops/sequence')) { mutations += 1; await response.body?.cancel(); @@ -529,6 +668,7 @@ describe('desktop-driver-mcp', () => { response: { result: { status: 'passed' } }, }); expect(mutations).toBe(1); + expect(delegations).toBe(1); } finally { await controller.dispose(); await harness.close(); @@ -587,9 +727,7 @@ describe('desktop-driver-mcp', () => { } finally { await controller.dispose(); await harness.close(); - expect(errors).toHaveBeenCalledWith( - 'desktop-driver-mcp: session cleanup is incomplete; the service must drain or expire the session.', - ); + expect(errors).not.toHaveBeenCalled(); errors.mockRestore(); } }); diff --git a/packages/agentic/desktop-driver-mcp/src/server.ts b/packages/agentic/desktop-driver-mcp/src/server.ts index c0394dd40d..f45d4a9969 100644 --- a/packages/agentic/desktop-driver-mcp/src/server.ts +++ b/packages/agentic/desktop-driver-mcp/src/server.ts @@ -257,6 +257,11 @@ export function createDesktopDriverMcpServer(options: DesktopDriverMcpServerOpti server.server.onclose = () => { void controller.dispose(); }; + const close = server.close.bind(server); + server.close = async () => { + await close(); + await controller.dispose(); + }; return server; } diff --git a/packages/agentic/desktop-driver/AGENTS.md b/packages/agentic/desktop-driver/AGENTS.md index d829e9855f..5f6d8d940d 100644 --- a/packages/agentic/desktop-driver/AGENTS.md +++ b/packages/agentic/desktop-driver/AGENTS.md @@ -22,6 +22,11 @@ editing. - Bind only to loopback, reject browser-origin requests, and fail closed when a helper, signature, target identity, permission, or capability cannot be verified. +- Keep driver-control, declared-workload, and operator-recovery authority + separate. Child grants may only attenuate targets/scopes. Revoke descendant + authority synchronously and await acquisition/session drains; revoked-child + proof authorizes only retrying that child's terminal cleanup, never driver + access. Never evict cleanup proof to reuse the finite lifetime grant budget. - Permit one active session per target. Serialize each session's commands and all physical input, including across independent helper processes. - Every host operation must honor its `AbortSignal`, stop side effects, settle diff --git a/packages/agentic/desktop-driver/README.md b/packages/agentic/desktop-driver/README.md index 35fddb1804..3e65b032ed 100644 --- a/packages/agentic/desktop-driver/README.md +++ b/packages/agentic/desktop-driver/README.md @@ -159,3 +159,9 @@ The [reference index](references/README.md) describes each package-owned guide. The service implements native application semantics rather than pretending to be a browser. Unsupported browser features return `unsupported operation` instead of fabricated success. + +Protected clients use `driver-control` grants. MCP connections attenuate the +private descriptor grant into distinct child principals, with target/scope +subset checks and awaitable, retryable descendant revocation. Workload and +operator-recovery scopes do not expose management HTTP routes; see the +[security model](references/security.md). diff --git a/packages/agentic/desktop-driver/references/current-status.md b/packages/agentic/desktop-driver/references/current-status.md index 871dcc3912..d3b68e71ae 100644 --- a/packages/agentic/desktop-driver/references/current-status.md +++ b/packages/agentic/desktop-driver/references/current-status.md @@ -19,25 +19,26 @@ and its sub-issues, which record dependencies and parallel waves. ## Capabilities -| Capability | State | Boundary or remaining work | -| ---------------------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| W3C service and typed/WDIO clients | Done | Registered targets only; native browser-inapplicable commands explicitly unsupported. | -| Application-neutral driver | Done | No Storybook, React, or React Native dependency. Optional story provider is injected. | -| Native sessions and command/input queues | Done | One reservation per registered target in one service. Cross-service exact-application claims remain work in progress. | -| Verified private discovery and grants | Done | Native identity verified before credential transmission; all protected driver routes authenticate. Does not protect the separate Storybook channel. | -| Mutation effects, settlement, quarantine | Done | Native mutations settle before advancing. Uncertain story changes now quarantine instead of assuming a later render is safe. | -| Durable settlement storage and trusted recovery API | Done in library; integration in progress | Requires explicit `recovery` options. Shipped generic/Storybook supervisors do not yet wire them; restart can erase uncertainty. Do not use restart as recovery evidence. | -| Bounded observation, references, paging, deltas | Done | Provider capability/budget checks, explicit completeness and truncation. Reference generation is session-local; reopen after application replacement. | -| Find, action, check, sequence | Done | Up to eight sequence steps; request-id outcomes prevent replay within their retained session history. No replay across service replacement. | -| Capture and artifact pages | Done | Session-bound bounded artifacts and hashes; pixels are opt-in. Screenshots are evidence, not visual comparison. | -| Named accessibility actions | Done in agent operations | WDIO can list actions but has no corresponding named-action invocation command. | -| Story catalog/select/reset | Done, experimental integration | Catalog-only IDs, correlated readiness and marker verification. Delayed/unknown failures fence mutations. | -| Story args on protected driver | Intentionally unsupported | `story-args-unsupported`; legacy unprotected args remain separate. | -| Exclusive Storybook control | Work in progress | Channel selection/prepare ingress can bypass driver authority; out-of-band args/context invalidation is incomplete. | -| Supervisor crash containment and automatic reclaim | Work in progress outside driver | Exact ownership ledger, surviving-resource reconciliation, and lifelines belong to desktop-test. | -| Application-exit/reconnect continuity | Work in progress | No transparent app/session or runtime bridge restoration. Events are advisory, not proof of recovery. | -| Recording/replay export, event-tail API, visual comparison | Work in progress/deferred | No agent-session-to-WDIO export; window-events still returns its full bounded ring. | -| Intel macOS and distributed/remote control | Unsupported | Current macOS helper is arm64; service is loopback-only. | +| Capability | State | Boundary or remaining work | +| ---------------------------------------------------------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| W3C service and typed/WDIO clients | Done | Registered targets only; native browser-inapplicable commands explicitly unsupported. | +| Application-neutral driver | Done | No Storybook, React, or React Native dependency. Optional story provider is injected. | +| Native sessions and command/input queues | Done | One reservation per registered target in one service. Cross-service exact-application claims remain work in progress. | +| Verified private discovery and grants | Done | Native identity verified before credential transmission; all protected driver routes authenticate. Does not protect the separate Storybook channel. | +| Attenuated connection principals and permission scopes | Done in deterministic contracts | Driver/workload/recovery scopes are distinct; fixed driver-only HTTP delegation, target/scope subsets, synchronous subtree fencing and awaitable/retryable drain. Native descriptor-path requalification not run for this change. | +| Mutation effects, settlement, quarantine | Done | Native mutations settle before advancing. Uncertain story changes now quarantine instead of assuming a later render is safe. | +| Durable settlement storage and trusted recovery API | Done in library; integration in progress | Requires explicit `recovery` options. Shipped generic/Storybook supervisors do not yet wire them; restart can erase uncertainty. Do not use restart as recovery evidence. | +| Bounded observation, references, paging, deltas | Done | Provider capability/budget checks, explicit completeness and truncation. Reference generation is session-local; reopen after application replacement. | +| Find, action, check, sequence | Done | Up to eight sequence steps; request-id outcomes prevent replay within their retained session history. No replay across service replacement. | +| Capture and artifact pages | Done | Session-bound bounded artifacts and hashes; pixels are opt-in. Screenshots are evidence, not visual comparison. | +| Named accessibility actions | Done in agent operations | WDIO can list actions but has no corresponding named-action invocation command. | +| Story catalog/select/reset | Done, experimental integration | Catalog-only IDs, correlated readiness and marker verification. Delayed/unknown failures fence mutations. | +| Story args on protected driver | Intentionally unsupported | `story-args-unsupported`; legacy unprotected args remain separate. | +| Exclusive Storybook control | Work in progress | Channel selection/prepare ingress can bypass driver authority; out-of-band args/context invalidation is incomplete. | +| Supervisor crash containment and automatic reclaim | Work in progress outside driver | Exact ownership ledger, surviving-resource reconciliation, and lifelines belong to desktop-test. | +| Application-exit/reconnect continuity | Work in progress | No transparent app/session or runtime bridge restoration. Events are advisory, not proof of recovery. | +| Recording/replay export, event-tail API, visual comparison | Work in progress/deferred | No agent-session-to-WDIO export; window-events still returns its full bounded ring. | +| Intel macOS and distributed/remote control | Unsupported | Current macOS helper is arm64; service is loopback-only. | The approved direction is a stronger `desktop-test` workload host, with native authority here and MCP as a client. No coordinator package or daemon is being diff --git a/packages/agentic/desktop-driver/references/security.md b/packages/agentic/desktop-driver/references/security.md index 3e300f6ae5..5e901b9387 100644 --- a/packages/agentic/desktop-driver/references/security.md +++ b/packages/agentic/desktop-driver/references/security.md @@ -52,6 +52,22 @@ in its command queue authenticates again immediately before dispatch. the grant behaves as one that is not registered, in `/status` and in capability matching. The service refuses to start when a grant names a target it does not register. +- A grant also names explicit permission scopes: `driver-control`, + `declared-workload`, and `operator-recovery`. Omitted scopes mean only + `driver-control`. Every protected driver route requires that scope; the other + scopes alone confer no driver access. Workload and recovery HTTP routes are + not implemented. Trusted in-process recovery remains an operator API. +- `authority.delegate(parent.id, request)` creates a distinct child principal, + rejecting target or scope expansion (including wildcard expansion). An + omitted child scope inherits its parent's scopes. The fixed HTTP + `POST /furn/grants/connection` accepts no fields and delegates only + `driver-control`, with the parent's target set and label. The typed client's + `delegateConnection()` keeps the returned credential private. Neither a parent + nor a sibling can address the child's sessions. +- Delegation is bounded to eight edges and 4096 total grants per service + incarnation, including roots and revoked grants. Exhaustion fails explicitly; + cleanup proof is never evicted or recycled to admit new connections. Operators + must drain and replace the service to reset this finite lifetime budget. - A session belongs to the grant that created it. Every other grant gets the answer for an id that does not exist, and that check runs before the command queues, so a grant can neither probe for another grant's session nor wait in, @@ -68,11 +84,21 @@ in its command queue authenticates again immediately before dispatch. dispatch, and teardown waits behind the settled command. A draining session accepts only `DELETE`. A session that fails to close stays tracked, and shutdown retries it. -- `authority.revoke()` schedules that drain; its synchronous return is not an - awaited cleanup barrier. Ordinary HTTP `DELETE` is queued behind current - work before drain begins. Neither revocation notification nor a ten-minute - idle setting proves that native work has settled; handoff must await deletion - or a future explicit drain barrier. +- `authority.revoke()` synchronously invalidates the entire descendant tree; + its boolean return is not a cleanup barrier. Await + `authority.revokeAndDrain(id)` to join all descendant drains, including + already-revoked descendants and in-flight acquisitions. Listener failures are + retained and reported; a subsequent barrier retries a failed drain. +- `DELETE /furn/grants/current` is child self-cleanup only, never root or + sibling revocation. It awaits the same drain. The authority retains a digest + tombstone for a revoked child: its old credential authenticates **only this + exact terminal route** so a lost response or failed drain can be retried. + It cannot authorize status, session work, delegation, or another principal's + cleanup. Unauthorized is not cleanup evidence. Tombstones retain no plaintext + secret and live until the service incarnation ends. +- Ordinary session HTTP `DELETE` is queued behind current work before drain + begins. Neither revocation notification nor a ten-minute idle setting proves + settlement; handoff must await session deletion or the explicit grant drain. - A grant's session that receives no request for `idleSessionTimeoutMs` (ten minutes by default; 0 disables) closes as `DELETE` would: input is released, a launched application is closed, and an attached application is @@ -87,9 +113,10 @@ in its command queue authenticates again immediately before dispatch. The boundary is other operating-system accounts and accidental cross-client access. It does not isolate mutually hostile processes of the same account and -does not protect against administrators. The service does not publish tokens -over HTTP. The embedding supervisor delivers each over a private channel or in -an owner-validated connection descriptor, keeping it out of capabilities, +does not protect against administrators. The service publishes child tokens only +in the authenticated connection-delegation response, never status or +driver-operation output. The embedding supervisor delivers root grants over a +private channel or in an owner-validated connection descriptor, keeping them out of capabilities, command lines, logs, and test output. Private descriptors contain plaintext credentials; process-wide heap dumps can also contain credentials. diff --git a/packages/agentic/desktop-driver/references/service.md b/packages/agentic/desktop-driver/references/service.md index 281744d35f..d02fc03764 100644 --- a/packages/agentic/desktop-driver/references/service.md +++ b/packages/agentic/desktop-driver/references/service.md @@ -323,7 +323,17 @@ const client = createDesktopDriverClient({ grant: agent.token, url: service.url session that does not exist. - `/status` lists only the grant's targets and reports `service.incarnation`, which changes whenever the service restarts. -- `authority.revoke(grant.id)` closes the sessions that grant owns. +- `authority.revoke(grant.id)` invalidates the grant and its descendants + immediately. Await `authority.revokeAndDrain(grant.id)` to confirm their + sessions and in-flight acquisitions have settled and closed; failed drains + remain observable and retryable. +- Scopes default to `driver-control`; `declared-workload` and + `operator-recovery` do not imply driver access or add HTTP management routes. + `authority.delegate(parent.id, request)` rejects target/scope expansion. + `client.delegateConnection()` returns a separate driver-only client; + `child.revokeConnection()` awaits self-cleanup and remains retryable with + terminal-only proof after revocation. See [security](security.md) for the + eight-edge depth and 4096-grant service-lifetime limits. - A grant's session closes after `idleSessionTimeoutMs` without a request for it, ten minutes by default. Every request for the session renews it, and a running request is never interrupted by expiry. Pass `0` to disable expiry. diff --git a/packages/agentic/desktop-driver/src/authority/delegation.test.ts b/packages/agentic/desktop-driver/src/authority/delegation.test.ts new file mode 100644 index 0000000000..e1e2a76453 --- /dev/null +++ b/packages/agentic/desktop-driver/src/authority/delegation.test.ts @@ -0,0 +1,144 @@ +import { DesktopAuthority } from './grants.js'; + +describe('attenuated grants', () => { + test('isolates siblings even when their labels and target scopes match', () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: ['a', 'b'] }); + const first = authority.delegate(parent.id, { label: 'agent', targets: ['a'] }); + const second = authority.delegate(parent.id, { label: 'agent', targets: ['a'] }); + + expect(first.id).not.toBe(second.id); + expect(first.token).not.toBe(second.token); + expect(authority.authenticate(`Bearer ${first.token}`)?.id).toBe(first.id); + expect(authority.authenticate(`Bearer ${second.token}`)?.id).toBe(second.id); + }); + + test('refuses target and permission expansion', () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: ['a'], scopes: ['driver-control'] }); + + expect(() => authority.delegate(parent.id, { label: 'child', targets: '*' })).toThrow(); + expect(() => authority.delegate(parent.id, { label: 'child', targets: ['b'] })).toThrow(); + for (const scope of ['declared-workload', 'operator-recovery'] as const) { + expect(() => authority.delegate(parent.id, { label: 'child', targets: ['a'], scopes: [scope] })).toThrow(); + } + }); + + test('invalidates the entire subtree before awaiting every drain listener', async () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: '*' }); + const child = authority.delegate(parent.id, { label: 'child', targets: ['a'] }); + const descendant = authority.delegate(child.id, { label: 'nested', targets: ['a'] }); + const sibling = authority.issue({ label: 'agent', targets: '*' }); + let finish!: () => void; + const pending = new Promise((resolve) => { + finish = resolve; + }); + const drained: string[] = []; + authority.onRevoke(async ({ id }) => { + await pending; + drained.push(id); + }); + + const drain = authority.revokeAndDrain(parent.id); + for (const grant of [parent, child, descendant]) { + expect(authority.authenticate(`Bearer ${grant.token}`)).toBeUndefined(); + } + expect(authority.authenticate(`Bearer ${sibling.token}`)?.id).toBe(sibling.id); + expect(drained).toEqual([]); + finish(); + await drain; + expect(new Set(drained)).toEqual(new Set([parent.id, child.id, descendant.id])); + }); + + test('reports drain failure without resurrecting any credentials', async () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: '*' }); + const child = authority.delegate(parent.id, { label: 'child', targets: ['a'] }); + authority.onRevoke(async () => { + throw new Error('injected drain failure'); + }); + + await expect(authority.revokeAndDrain(parent.id)).rejects.toThrow(); + expect(authority.authenticate(`Bearer ${child.token}`)).toBeUndefined(); + await expect(authority.revokeAndDrain(parent.id)).rejects.toThrow(); + }); + + test('joins concurrent parent and child retries without repeating successful listeners', async () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: '*' }); + const child = authority.delegate(parent.id, { label: 'child', targets: '*' }); + const calls: string[] = []; + let failed = false; + authority.onRevoke(({ id }) => { + calls.push(id); + if (id === child.id && !failed) { + failed = true; + throw new Error('injected child drain failure'); + } + }); + await expect(authority.revokeAndDrain(parent.id)).rejects.toThrow('drain failed'); + await Promise.all([authority.revokeAndDrain(parent.id), authority.revokeAndDrain(child.id)]); + expect(calls.filter((id) => id === parent.id)).toHaveLength(1); + expect(calls.filter((id) => id === child.id)).toHaveLength(2); + await expect(authority.revokeAndDrain('missing')).rejects.toThrow('Unknown grant'); + }); + + test('reports an unobserved legacy drain failure before allowing a successful retry', async () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: '*' }); + const listener = jest.fn().mockRejectedValueOnce(new Error('injected failure')).mockResolvedValue(undefined); + authority.onRevoke(listener); + authority.revoke(parent.id); + await new Promise((resolve) => setImmediate(resolve)); + await expect(authority.revokeAndDrain(parent.id)).rejects.toThrow('drain failed'); + expect(listener).toHaveBeenCalledTimes(1); + await expect(authority.revokeAndDrain(parent.id)).resolves.toBeUndefined(); + expect(listener).toHaveBeenCalledTimes(2); + }); + + test('joins an already revoked descendant drain when its parent is revoked', async () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: '*' }); + const child = authority.delegate(parent.id, { label: 'child', targets: ['a'] }); + let finish!: () => void; + const pending = new Promise((resolve) => { + finish = resolve; + }); + authority.onRevoke(({ id }) => (id === child.id ? pending : undefined)); + authority.revoke(child.id); + let completed = false; + const drain = authority.revokeAndDrain(parent.id).then(() => { + completed = true; + }); + await Promise.resolve(); + expect(completed).toBe(false); + finish(); + await drain; + }); + + test('accepts equal and narrower scopes, freezes them, and defaults roots to driver only', () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'operator', targets: '*', scopes: ['driver-control', 'operator-recovery'] }); + const child = authority.delegate(parent.id, { label: 'child', targets: ['a'], scopes: ['driver-control'] }); + expect(child.scopes).toEqual(['driver-control']); + expect(Object.isFrozen(child.scopes)).toBe(true); + expect(authority.delegate(child.id, { label: 'equal', targets: ['a'] }).scopes).toEqual(child.scopes); + expect(authority.issue({ label: 'default', targets: '*' }).scopes).toEqual(['driver-control']); + }); + + test('bounds depth and service-lifetime issuance without evicting cleanup proof', async () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: '*' }); + let current = parent; + for (let depth = 0; depth < 8; depth += 1) { + current = authority.delegate(current.id, { label: 'child', targets: '*' }); + } + expect(() => authority.delegate(current.id, { label: 'too-deep', targets: '*' })).toThrow(); + await authority.revokeAndDrain(current.id); + for (let index = 9; index < 4096; index += 1) authority.issue({ label: 'bounded', targets: '*' }); + expect(() => authority.issue({ label: 'exhausted', targets: '*' })).toThrow('limit'); + expect(authority.authenticateRevocation(`Bearer ${current.token}`)?.id).toBe(current.id); + expect(authority.authenticate(`Bearer ${current.token}`)).toBeUndefined(); + }); +}); diff --git a/packages/agentic/desktop-driver/src/authority/grants.test.ts b/packages/agentic/desktop-driver/src/authority/grants.test.ts index 77abbf1ef6..a36042a87c 100644 --- a/packages/agentic/desktop-driver/src/authority/grants.test.ts +++ b/packages/agentic/desktop-driver/src/authority/grants.test.ts @@ -1,11 +1,56 @@ import { DesktopAuthority, grantAllowsTarget } from './grants.js'; describe('DesktopAuthority', () => { + test('awaits asynchronous cleanup after synchronous invalidation', async () => { + const authority = new DesktopAuthority(); + const grant = authority.issue({ label: 'agent', targets: '*' }); + let finish!: () => void; + const pending = new Promise((resolve) => { + finish = resolve; + }); + const listener = jest.fn(() => pending); + authority.onRevoke(listener); + expect(authority.revoke(grant.id)).toBe(true); + expect(authority.authenticate(`Bearer ${grant.token}`)).toBeUndefined(); + let drained = false; + const barrier = authority.revokeAndDrain(grant.id).then(() => { + drained = true; + }); + await Promise.resolve(); + expect(drained).toBe(false); + finish(); + await barrier; + expect(listener).toHaveBeenCalledTimes(1); + expect(drained).toBe(true); + }); + + test('keeps drain failures observable after legacy revocation and awaits every listener', async () => { + const authority = new DesktopAuthority(); + const grant = authority.issue({ label: 'agent', targets: '*' }); + const failure = new Error('injected cleanup failure'); + let completed = false; + authority.onRevoke(() => { + throw failure; + }); + authority.onRevoke(async () => { + completed = true; + }); + authority.revoke(grant.id); + await expect(authority.revokeAndDrain(grant.id)).rejects.toMatchObject({ errors: [failure] }); + expect(completed).toBe(true); + await expect(authority.revokeAndDrain(grant.id)).rejects.toMatchObject({ errors: [failure] }); + }); + test('issues grants whose tokens authenticate to the same grant', () => { const authority = new DesktopAuthority(); const issued = authority.issue({ label: 'agent', targets: ['a', 'b'] }); - expect(authority.authenticate(`Bearer ${issued.token}`)).toEqual({ id: issued.id, label: 'agent', targets: ['a', 'b'] }); + expect(authority.authenticate(`Bearer ${issued.token}`)).toEqual({ + id: issued.id, + label: 'agent', + scopes: ['driver-control'], + targets: ['a', 'b'], + }); expect(authority.authenticate(`bearer ${issued.token}`)?.id).toBe(issued.id); }); diff --git a/packages/agentic/desktop-driver/src/authority/grants.ts b/packages/agentic/desktop-driver/src/authority/grants.ts index 871f53c865..e32c2320a4 100644 --- a/packages/agentic/desktop-driver/src/authority/grants.ts +++ b/packages/agentic/desktop-driver/src/authority/grants.ts @@ -8,6 +8,7 @@ const maxTargetIdLength = 200; /** The registered target ids a grant may open and drive, or `*` for every target the service registers. */ export type GrantTargets = '*' | readonly string[]; +export type GrantScope = 'driver-control' | 'declared-workload' | 'operator-recovery'; export type GrantRequest = { /** @@ -16,6 +17,7 @@ export type GrantRequest = { */ label: string; targets: GrantTargets; + scopes?: readonly GrantScope[]; }; /** What the service knows about an authenticated caller. It never contains the secret. */ @@ -23,12 +25,17 @@ export type DesktopGrant = { readonly id: string; readonly label: string; readonly targets: GrantTargets; + readonly scopes: readonly GrantScope[]; + readonly parentId?: string; }; /** A new grant with its bearer token. The token is returned once and cannot be recovered from the authority. */ export type IssuedDesktopGrant = DesktopGrant & { readonly token: string }; -type StoredGrant = { digest: Buffer; grant: DesktopGrant }; +type StoredGrant = { digest: Buffer; grant: DesktopGrant; depth: number }; +type Drain = { pending: Promise; failed: boolean; failureReported: boolean }; +const maxGrants = 4096; +const maxDepth = 8; /** * The credential authority of one service incarnation. A service that has an authority requires a grant for every @@ -43,25 +50,60 @@ export class DesktopAuthority { /** Identifies this service start. A reconnecting client must find the same value or the service restarted. */ readonly incarnation = `inc_${randomBytes(12).toString('hex')}`; private readonly grants = new Map(); - private readonly revocationListeners = new Set<(grant: DesktopGrant) => void>(); + private readonly revocationListeners = new Set<(grant: DesktopGrant) => unknown>(); + private readonly drains = new Map(); + private readonly revoked = new Map(); + private issuedCount = 0; // Verifying a token for an unknown grant compares against this so the two failures take the same work. private readonly unknownDigest = digestOf(randomBytes(32).toString('base64url')); issue(request: GrantRequest): IssuedDesktopGrant { + return this.create(request, undefined); + } + + /** Trusted callers may attenuate targets and permissions, never expand them. */ + delegate(parentId: string, request: GrantRequest): IssuedDesktopGrant { + const parent = this.grants.get(parentId); + if (!parent || parent.depth >= maxDepth) throw new TypeError('Grant delegation is unavailable.'); + const targets = normalizeTargets(request.targets); + const scopes = normalizeScopes(request.scopes ?? parent.grant.scopes); + if ( + (targets === '*' ? parent.grant.targets !== '*' : targets.some((id) => !grantAllowsTarget(parent.grant, id))) || + scopes.some((scope) => !parent.grant.scopes.includes(scope)) + ) { + throw new TypeError('A child grant cannot exceed its parent authority.'); + } + return this.create({ ...request, scopes, targets }, parent); + } + + private create(request: GrantRequest, parent: StoredGrant | undefined): IssuedDesktopGrant { + if (this.issuedCount >= maxGrants) throw new RangeError('The service grant limit has been reached.'); const label = request.label; if (typeof label !== 'string' || !labelPattern.test(label)) { throw new TypeError('A grant label must be 1-32 characters of letters, digits, ".", "_", ":" or "-".'); } const targets = normalizeTargets(request.targets); + const scopes = normalizeScopes(request.scopes); const id = randomBytes(16).toString('hex'); const secret = randomBytes(32).toString('base64url'); - const grant: DesktopGrant = Object.freeze({ id, label, targets }); - this.grants.set(id, { digest: digestOf(secret), grant }); + const grant: DesktopGrant = Object.freeze({ id, label, targets, scopes, ...(parent ? { parentId: parent.grant.id } : {}) }); + this.grants.set(id, { digest: digestOf(secret), grant, depth: parent ? parent.depth + 1 : 0 }); + this.issuedCount += 1; return Object.freeze({ ...grant, token: `${tokenScheme}.${id}.${secret}` }); } /** Returns the grant behind an `Authorization: Bearer` value, or undefined for anything else. Never throws. */ authenticate(authorization: string | undefined): DesktopGrant | undefined { + return this.authenticateFrom(authorization, this.grants); + } + + /** Terminal proof is accepted only by the child's own cleanup route, never ordinary authentication. */ + authenticateRevocation(authorization: string | undefined): DesktopGrant | undefined { + const grant = this.authenticateFrom(authorization, this.revoked); + return grant?.parentId ? grant : undefined; + } + + private authenticateFrom(authorization: string | undefined, records: ReadonlyMap): DesktopGrant | undefined { if (typeof authorization !== 'string' || authorization.length > maxAuthorizationLength) { return undefined; } @@ -72,25 +114,102 @@ export class DesktopAuthority { if (parts.length !== 3 || parts[0] !== tokenScheme) { return undefined; } - const stored = this.grants.get(parts[1]); + const stored = records.get(parts[1]); const matches = timingSafeEqual(digestOf(parts[2]), stored?.digest ?? this.unknownDigest); return stored && matches ? stored.grant : undefined; } - /** Invalidates a grant. Sessions it owns are reported to listeners so the service can drain them. */ + /** Invalidates a grant immediately. Use revokeAndDrain to await session cleanup and observe failures. */ revoke(grantId: string): boolean { const stored = this.grants.get(grantId); if (!stored) { return false; } - this.grants.delete(grantId); - for (const listener of this.revocationListeners) { - listener(stored.grant); + const subtree = this.subtree(stored); + for (const item of subtree) { + this.grants.delete(item.grant.id); + this.revoked.set(item.grant.id, item); + } + for (const item of subtree) { + if (!this.drains.has(item.grant.id)) this.startDrain(item); } return true; } - onRevoke(listener: (grant: DesktopGrant) => void): () => void { + private subtree(root: StoredGrant): StoredGrant[] { + const records = [...this.grants.values(), ...this.revoked.values()]; + return records.filter((candidate) => { + let current: StoredGrant | undefined = candidate; + while (current) { + if (current === root) return true; + const parentId = current.grant.parentId ?? ''; + current = this.grants.get(parentId) ?? this.revoked.get(parentId); + } + return false; + }); + } + + private startDrain({ grant }: StoredGrant): Drain { + let resolve!: () => void; + let reject!: (reason: unknown) => void; + const drain: Drain = { + pending: new Promise((complete, fail) => { + resolve = complete; + reject = fail; + }), + failed: false, + failureReported: false, + }; + this.drains.set(grant.id, drain); + // Install the barrier before calling listeners, which may themselves revoke another branch. + void drain.pending.catch(() => undefined); + const pending = [...this.revocationListeners].map((listener) => { + try { + return Promise.resolve(listener(grant)); + } catch (error) { + return Promise.reject(error); + } + }); + void Promise.allSettled(pending).then((results) => { + const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected'); + if (failures.length) { + drain.failed = true; + reject( + new AggregateError( + failures.map(({ reason }) => reason), + 'Desktop Driver grant drain failed.', + ), + ); + } else { + resolve(); + } + }); + return drain; + } + + /** Joins the original drain even when synchronous revocation already invalidated the grant. */ + async revokeAndDrain(grantId: string): Promise { + this.revoke(grantId); + const root = this.revoked.get(grantId); + if (!root) throw new TypeError('Unknown grant revocation.'); + const drains = this.subtree(root).map((stored) => { + const drain = this.drains.get(stored.grant.id); + return !drain || (drain.failed && drain.failureReported) ? this.startDrain(stored) : drain; + }); + const results = await Promise.allSettled(drains.map((drain) => drain.pending)); + for (const [index, result] of results.entries()) { + if (result.status === 'rejected') drains[index].failureReported = true; + } + const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected'); + if (failures.length) { + throw new AggregateError( + failures.flatMap(({ reason }) => (reason instanceof AggregateError ? reason.errors : [reason])), + 'Desktop Driver grant drain failed.', + ); + } + } + + onRevoke(listener: (grant: DesktopGrant) => unknown): () => void { this.revocationListeners.add(listener); return () => this.revocationListeners.delete(listener); } @@ -114,6 +233,17 @@ export function grantAllowsTarget(grant: DesktopGrant, targetId: string): boolea return grant.targets === '*' || grant.targets.includes(targetId); } +function normalizeScopes(scopes: readonly GrantScope[] = ['driver-control']): readonly GrantScope[] { + if ( + !Array.isArray(scopes) || + scopes.length === 0 || + scopes.some((scope) => !['driver-control', 'declared-workload', 'operator-recovery'].includes(scope)) + ) { + throw new TypeError('A grant requires recognized permission scopes.'); + } + return Object.freeze([...new Set(scopes)]); +} + function normalizeTargets(targets: GrantTargets): GrantTargets { if (targets === '*') { return '*'; diff --git a/packages/agentic/desktop-driver/src/authority/index.ts b/packages/agentic/desktop-driver/src/authority/index.ts index 5813615697..2ea5e9a239 100644 --- a/packages/agentic/desktop-driver/src/authority/index.ts +++ b/packages/agentic/desktop-driver/src/authority/index.ts @@ -1,5 +1,5 @@ export { DesktopAuthority, grantAllowsTarget } from './grants.js'; -export type { DesktopGrant, GrantRequest, GrantTargets, IssuedDesktopGrant } from './grants.js'; +export type { DesktopGrant, GrantRequest, GrantScope, GrantTargets, IssuedDesktopGrant } from './grants.js'; export { publishConnectionDescriptor, readConnectionDescriptor } from './connectionDescriptor.js'; export type { DesktopConnectionDescriptor, DesktopServiceIdentity, VerifyDesktopService } from './connectionDescriptor.js'; export { createMacOSPrivateStorage } from './macosPrivateStorage.js'; diff --git a/packages/agentic/desktop-driver/src/client/DesktopDriverClient.ts b/packages/agentic/desktop-driver/src/client/DesktopDriverClient.ts index eaa6bc95ba..17f8b1e67a 100644 --- a/packages/agentic/desktop-driver/src/client/DesktopDriverClient.ts +++ b/packages/agentic/desktop-driver/src/client/DesktopDriverClient.ts @@ -74,6 +74,25 @@ export class DesktopDriverClient { return this.request('GET', '/status'); } + /** Non-secret identity for connection bookkeeping; never authorizes a request. */ + get principalId(): string | undefined { + return this.#grant?.split('.')[1]; + } + + /** Obtains a connection-local driver-only principal. Credentials remain private to the returned client. */ + async delegateConnection(): Promise { + const value = await this.request<{ token: string }>('POST', '/furn/grants/connection'); + if (typeof value?.token !== 'string' || !/^fdg1\.[0-9a-f]{32}\.[A-Za-z0-9_-]{43}$/.test(value.token)) { + throw new Error('The service does not support connection authority.'); + } + return new DesktopDriverClient({ fetch: this.fetch, grant: value.token, url: this.url }); + } + + /** Retryable terminal cleanup: revoked credentials authorize only their own child drain. */ + revokeConnection(): Promise { + return this.request('DELETE', '/furn/grants/current'); + } + async newSession(capabilities: NewSessionCapabilities): Promise { const value = await this.request<{ capabilities: Record; sessionId: string }>('POST', '/session', { capabilities, diff --git a/packages/agentic/desktop-driver/src/server/createDesktopDriverServer.ts b/packages/agentic/desktop-driver/src/server/createDesktopDriverServer.ts index 7b325f2f43..1fea7d25d6 100644 --- a/packages/agentic/desktop-driver/src/server/createDesktopDriverServer.ts +++ b/packages/agentic/desktop-driver/src/server/createDesktopDriverServer.ts @@ -129,9 +129,7 @@ export async function createDesktopDriverServer(options: DesktopDriverServerOpti const port = await listen(httpServer, host, options.port ?? 0); // A revoked grant leaves its sessions unreachable, so they are closed rather than holding their targets. A session that // fails to close stays tracked, and service shutdown retries it and reports the failure. - const stopDrainingRevokedGrants = options.authority?.onRevoke((grant) => { - void sessions.deleteOwnedBy(grant.id).catch(() => undefined); - }); + const stopDrainingRevokedGrants = options.authority?.onRevoke((grant) => sessions.deleteOwnedBy(grant.id)); return { host, @@ -262,8 +260,11 @@ function authenticateRequest(request: IncomingMessage, authority: DesktopAuthori if (!authority) { return undefined; } - const grant = authority.authenticate(request.headers.authorization); - if (!grant) { + const cleanup = request.method === 'DELETE' && request.url === '/furn/grants/current'; + const grant = + authority.authenticate(request.headers.authorization) ?? + (cleanup ? authority.authenticateRevocation(request.headers.authorization) : undefined); + if (!grant || !grant.scopes.includes('driver-control')) { // A missing, malformed, revoked, and wrong-secret grant are indistinguishable, and the stack trace stays server-side. const error = new WebDriverError('unauthorized', 'A valid Desktop Driver grant is required.'); error.stack = ''; @@ -286,6 +287,28 @@ function visibleTargets(context: Pick, targets: TargetReg async function route(context: RouteContext, sessions: SessionManager, targets: TargetRegistry): Promise { const { body, method, segments } = context; + if (segments.length === 3 && segments[0] === 'furn' && segments[1] === 'grants' && context.authority && context.grant) { + if (method === 'POST' && segments[2] === 'connection') { + if (Object.keys(requireObject(body, 'Connection delegation')).length !== 0) + throw invalidArgument('Connection delegation accepts no input.'); + const child = context.authority.delegate(context.grant.id, { + label: context.grant.label, + scopes: ['driver-control'], + targets: context.grant.targets, + }); + return { token: child.token }; + } + if (method === 'DELETE' && segments[2] === 'current') { + if (!context.grant.parentId) { + const error = new WebDriverError('unauthorized', 'Only a connection child can revoke itself.'); + error.stack = ''; + throw error; + } + await context.authority.revokeAndDrain(context.grant.id); + return null; + } + } + if (method === 'GET' && segments.length === 1 && segments[0] === 'status') { const targetInfo = await Promise.all( visibleTargets(context, targets).map(async (target) => { diff --git a/packages/agentic/desktop-driver/src/server/delegation.test.ts b/packages/agentic/desktop-driver/src/server/delegation.test.ts new file mode 100644 index 0000000000..4a1127b58e --- /dev/null +++ b/packages/agentic/desktop-driver/src/server/delegation.test.ts @@ -0,0 +1,161 @@ +import { DesktopAuthority } from '../authority/grants.js'; +import { createDesktopDriverClient } from '../client/DesktopDriverClient.js'; +import { createDesktopDriverTestHarness } from '../testing/protocolHarness.js'; + +describe('connection grant routes', () => { + test('isolates two connections reading the same parent grant and drains descendants', async () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ + label: 'agent', + scopes: ['driver-control', 'declared-workload', 'operator-recovery'], + targets: '*', + }); + const harness = await createDesktopDriverTestHarness({}, undefined, { authority }); + const client = createDesktopDriverClient({ grant: parent.token, url: harness.server.url }); + try { + const first = await client.delegateConnection(); + const second = await client.delegateConnection(); + expect(first.principalId).toMatch(/^[a-f0-9]{32}$/); + expect(() => + authority.delegate(first.principalId ?? '', { + label: 'escalation', + scopes: ['operator-recovery'], + targets: '*', + }), + ).toThrow('exceed'); + const session = await first.newSession({ alwaysMatch: { 'furn:target': harness.target.id } }); + await expect(second.request('GET', `/session/${session.id}/window`)).rejects.toMatchObject({ code: 'invalid session id' }); + await expect(client.request('GET', `/session/${session.id}/window`)).rejects.toMatchObject({ code: 'invalid session id' }); + const status = await second.status(); + const output = JSON.stringify(status); + expect(output).not.toContain(parent.token); + expect(output).not.toContain(session.id); + await authority.revokeAndDrain(parent.id); + expect(() => harness.server.sessions.get(session.id)).toThrow(); + await expect(first.status()).rejects.toMatchObject({ code: 'unauthorized' }); + await expect(second.status()).rejects.toMatchObject({ code: 'unauthorized' }); + await expect(first.request('DELETE', `/furn/grants/${second.principalId}`)).rejects.toMatchObject({ code: 'unauthorized' }); + await expect(first.request('POST', '/session', {})).rejects.toMatchObject({ code: 'unauthorized' }); + await expect(first.revokeConnection()).resolves.toBeNull(); + } finally { + await harness.close(); + } + }); + + test('child self-revocation is an awaited session drain and cannot revoke its parent', async () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: '*' }); + const harness = await createDesktopDriverTestHarness({}, undefined, { authority }); + const client = createDesktopDriverClient({ grant: parent.token, url: harness.server.url }); + try { + await expect(client.revokeConnection()).rejects.toMatchObject({ code: 'unauthorized' }); + const child = await client.delegateConnection(); + const session = await child.newSession({ alwaysMatch: { 'furn:target': harness.target.id } }); + await child.revokeConnection(); + expect(() => harness.server.sessions.get(session.id)).toThrow(); + await expect(child.status()).rejects.toMatchObject({ code: 'unauthorized' }); + await expect(client.status()).resolves.toMatchObject({ ready: true }); + } finally { + await harness.close(); + } + }); + + test.each(['declared-workload', 'operator-recovery'] as const)('does not treat %s as driver authority', async (scope) => { + const authority = new DesktopAuthority(); + const grant = authority.issue({ label: 'operator', targets: '*', scopes: [scope] }); + const harness = await createDesktopDriverTestHarness({}, undefined, { authority }); + const client = createDesktopDriverClient({ grant: grant.token, url: harness.server.url }); + try { + await expect(client.status()).rejects.toMatchObject({ code: 'unauthorized' }); + await expect(client.newSession({ alwaysMatch: { 'furn:target': harness.target.id } })).rejects.toMatchObject({ + code: 'unauthorized', + }); + await expect(client.delegateConnection()).rejects.toMatchObject({ code: 'unauthorized' }); + } finally { + await harness.close(); + } + }); + + test('retries failed drain and lost revoke responses with terminal-only proof', async () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: '*' }); + const harness = await createDesktopDriverTestHarness({}, undefined, { authority }); + let loseResponse = false; + const client = createDesktopDriverClient({ + grant: parent.token, + url: harness.server.url, + fetch: async (input, init) => { + const response = await fetch(input, init); + if (loseResponse && String(input).endsWith('/furn/grants/current')) { + loseResponse = false; + await response.body?.cancel(); + throw new Error('injected revoke response loss'); + } + return response; + }, + }); + try { + const child = await client.delegateConnection(); + const session = await child.newSession({ alwaysMatch: { 'furn:target': harness.target.id } }); + jest.spyOn(harness.server.sessions, 'deleteOwnedBy').mockRejectedValueOnce(new Error('injected drain failure')); + await expect(child.revokeConnection()).rejects.toMatchObject({ code: 'unknown error' }); + await expect(child.status()).rejects.toMatchObject({ code: 'unauthorized' }); + await expect(child.delegateConnection()).rejects.toMatchObject({ code: 'unauthorized' }); + loseResponse = true; + await expect(child.revokeConnection()).rejects.toThrow('response loss'); + expect(() => harness.server.sessions.get(session.id)).toThrow(); + await expect(child.revokeConnection()).resolves.toBeNull(); + await expect(child.status()).rejects.toMatchObject({ code: 'unauthorized' }); + } finally { + await harness.close(); + } + }); + + test('rejects arbitrary delegation fields rather than expanding child scope', async () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: '*' }); + const harness = await createDesktopDriverTestHarness({}, undefined, { authority }); + const client = createDesktopDriverClient({ grant: parent.token, url: harness.server.url }); + try { + for (const body of [{ targets: '*' }, { scopes: ['operator-recovery'] }, { parentId: parent.id }]) { + await expect(client.request('POST', '/furn/grants/connection', body)).rejects.toMatchObject({ code: 'invalid argument' }); + } + } finally { + await harness.close(); + } + }); + + test('awaits child acquisition settlement when the parent is revoked during launch', async () => { + const authority = new DesktopAuthority(); + const parent = authority.issue({ label: 'agent', targets: '*' }); + const harness = await createDesktopDriverTestHarness({ launchDelayMs: 100 }, undefined, { authority }); + const client = createDesktopDriverClient({ grant: parent.token, url: harness.server.url }); + try { + const child = await client.delegateConnection(); + const launch = harness.host.launch.bind(harness.host); + let entered!: () => void; + const started = new Promise((resolve) => { + entered = resolve; + }); + jest.spyOn(harness.host, 'launch').mockImplementation((...args) => { + entered(); + return launch(...args); + }); + const opening = expect( + child.newSession({ + alwaysMatch: { 'furn:target': harness.target.id, 'furn:launchMode': 'launch' }, + }), + ).rejects.toMatchObject({ code: 'session not created' }); + await started; + await authority.revokeAndDrain(parent.id); + await opening; + const other = authority.issue({ label: 'other', targets: '*' }); + const session = await createDesktopDriverClient({ grant: other.token, url: harness.server.url }).newSession({ + alwaysMatch: { 'furn:target': harness.target.id }, + }); + await session.delete(); + } finally { + await harness.close(); + } + }); +}); diff --git a/packages/agentic/desktop-driver/src/testing/protocolHarness.ts b/packages/agentic/desktop-driver/src/testing/protocolHarness.ts index de56a970a0..d36696d311 100644 --- a/packages/agentic/desktop-driver/src/testing/protocolHarness.ts +++ b/packages/agentic/desktop-driver/src/testing/protocolHarness.ts @@ -43,6 +43,7 @@ export async function createDesktopDriverTestHarness( export async function createDesktopDriverStoryHarness( manifest: DesktopStoryManifest, options: FakeDesktopHostOptions = {}, + serverOptions: Omit = {}, ): Promise { const host = new FakeDesktopHost({ ...options, storyRootTestId: 'story-root' }); const storyOrchestrator = new FakeStoryOrchestrator(manifest, host); @@ -56,7 +57,7 @@ export async function createDesktopDriverStoryHarness( storyOrchestrator, storyRootTestId: 'story-root', }; - const server = await createDesktopDriverServer({ targets: [target] }); + const server = await createDesktopDriverServer({ ...serverOptions, targets: [target] }); return { host, server, From e4d2efc20f855d511c78e8c070a530f15d9ce7eb Mon Sep 17 00:00:00 2001 From: Jason Morse <35609178+JasonVMo@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:05:53 -0800 Subject: [PATCH 2/2] Scope injected authority-test deadlines to failing clicks Restore normal cleanup budgets in finally and exercise application cleanup beyond the injected click deadline. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../src/server/authority.test.ts | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/packages/agentic/desktop-driver/src/server/authority.test.ts b/packages/agentic/desktop-driver/src/server/authority.test.ts index 25eb764e85..56d880f208 100644 --- a/packages/agentic/desktop-driver/src/server/authority.test.ts +++ b/packages/agentic/desktop-driver/src/server/authority.test.ts @@ -359,8 +359,14 @@ describe('Desktop Driver protected service', () => { async ({ agent, capabilities, harness, other }) => { const session = await createDesktopDriverClient({ grant: agent.token, url: harness.server.url }).newSession(capabilities); const element = await session.findElement('accessibility id', 'button-primary'); - harness.server.sessions.get(session.id).desktopTimeouts.nativeCommand = 10; - await expect(element.click()).rejects.toMatchObject({ code: 'timeout' }); + const timeouts = harness.server.sessions.get(session.id).desktopTimeouts; + const nativeCommand = timeouts.nativeCommand; + try { + timeouts.nativeCommand = 10; + await expect(element.click()).rejects.toMatchObject({ code: 'timeout' }); + } finally { + timeouts.nativeCommand = nativeCommand; + } const status = await call(harness, 'GET', '/status', { authorization: bearer(other) }); const refused = await call(harness, 'POST', '/session', { authorization: bearer(other), body: { capabilities } }); @@ -372,7 +378,8 @@ describe('Desktop Driver protected service', () => { expect(text).not.toContain('sessionId'); } }, - { faults: { click: { mode: 'lost-response' } } }, + // Cleanup deliberately exceeds the click deadline; it must retain the normal command budget. + { closeDelayMs: 25, faults: { click: { mode: 'lost-response' } } }, ); }); @@ -608,7 +615,7 @@ describe('Desktop Driver protected service', () => { describe('Desktop Driver service without an authority', () => { test('keeps the documented loopback behavior, including the quarantine session id', async () => { - const harness = await createDesktopDriverTestHarness({ faults: { click: { mode: 'lost-response' } } }); + const harness = await createDesktopDriverTestHarness({ closeDelayMs: 25, faults: { click: { mode: 'lost-response' } } }); try { const client = createDesktopDriverClient({ url: harness.server.url }); const session = await client.newSession({ @@ -620,8 +627,14 @@ describe('Desktop Driver service without an authority', () => { }, }); const element = await session.findElement('accessibility id', 'button-primary'); - harness.server.sessions.get(session.id).desktopTimeouts.nativeCommand = 10; - await expect(element.click()).rejects.toMatchObject({ code: 'timeout' }); + const timeouts = harness.server.sessions.get(session.id).desktopTimeouts; + const nativeCommand = timeouts.nativeCommand; + try { + timeouts.nativeCommand = 10; + await expect(element.click()).rejects.toMatchObject({ code: 'timeout' }); + } finally { + timeouts.nativeCommand = nativeCommand; + } const status = (await client.status()) as { targets: { quarantine?: { sessionId?: string } }[] };