diff --git a/docs/experiments/remote-web-public-network-confinement.md b/docs/experiments/remote-web-public-network-confinement.md index 9306f3fe33..d82cc1c22b 100644 --- a/docs/experiments/remote-web-public-network-confinement.md +++ b/docs/experiments/remote-web-public-network-confinement.md @@ -2,10 +2,10 @@ ## Status -Design proposal. [#5243](https://github.com/callstack/agent-device/pull/5243) introduces -`remote_web_public_network_unenforced` for remote tenant web commands. -The refusal is absent from the `main` revision that this proposal targets. -Land #5243 before landing the confinement implementation. Keep its refusal until the final phase. +Design proposal. [#5348](https://github.com/callstack/agent-device/pull/5348) adds +`REMOTE_WEB_PUBLIC_NETWORK_UNENFORCED` for remote tenant web commands on 0.22. +The proxy-based confinement design is not implemented. #5272 is superseded. +Keep the refusal until the final phase of the confinement implementation. ## Security invariant @@ -185,10 +185,10 @@ fail-closed when the evidence lane is absent or fails. ## Phased implementation -After #5243 lands, each phase can merge while `assertRemoteWebDeviceAdmitted` refuses remote web. +After #5348 lands, each phase can merge while `assertRemoteWebDeviceAdmitted` refuses remote web. Keep that refusal and the independent launch guard until the final phase. -1. Use the `publicNetworkOnly` provider context from #5265, carried by #5243. Preserve the trusted +1. Use the `publicNetworkOnly` provider context from #5265. Preserve the trusted marker through default web provider construction. Prove that nested batch and replay requests cannot clear the marker. 2. Add a private `@agent-device/platform-web` public-destination classifier. Cover every IPv4 and @@ -211,7 +211,7 @@ Keep that refusal and the independent launch guard until the final phase. 5. Add real Chromium integration evidence for every row in the coverage table. Observe attempted egress outside the proxy process. Include public positive controls, a local listener replacement attempt after proxy death, and fail-closed behavior on macOS, Linux, and Windows. -6. Replace the routing refusal in `assertRemoteWebDeviceAdmitted` with confinement lease admission. +6. Replace the refusal in `assertRemoteWebDeviceAdmitted` with confinement lease admission. At launch, keep `remote_web_browser_unconfined` unless the backend can prove it has the matching proxy. Keep `close` available when either check fails. Update help and security docs in the same change. diff --git a/packages/command-registry/src/daemon-command-descriptor.ts b/packages/command-registry/src/daemon-command-descriptor.ts index 5637ae6ee5..3764313796 100644 --- a/packages/command-registry/src/daemon-command-descriptor.ts +++ b/packages/command-registry/src/daemon-command-descriptor.ts @@ -48,6 +48,8 @@ export type DaemonCommandDescriptor = { * that session and stays refused. */ ignoresSessionLease?: boolean; + /** This request reads only session metadata or its own lease scope, never the session's device. */ + detachedFromSessionDevice?: (req: TRequest) => boolean; /** * packages/daemon/docs/remote-device-lease-contracts.md: this command may run under a `macos-app` lease, or on a daemon whose policy requires * one. A command without it is refused there, `leaseAdmissionExempt` or not, so a command diff --git a/packages/command-registry/src/registry.ts b/packages/command-registry/src/registry.ts index 21b14465b6..172237c832 100644 --- a/packages/command-registry/src/registry.ts +++ b/packages/command-registry/src/registry.ts @@ -232,6 +232,7 @@ export const RAW_COMMAND_DESCRIPTORS = [ daemon: { route: 'lease', refFrameEffect: 'preserve', + detachedFromSessionDevice: () => true, ...ADMISSION_AND_LOCK_EXEMPT, }, timeoutPolicy: DEFAULT_TIMEOUT_POLICY, @@ -349,6 +350,7 @@ export const RAW_COMMAND_DESCRIPTORS = [ sessionKind: 'inventory', lockPolicySelectorOverride: true, allowSessionlessDefaultDevice: allowAnyDeviceSessionless, + detachedFromSessionDevice: (req) => req.flags?.remote === true, ...REQUEST_EXECUTION_EXEMPT, }, timeoutPolicy: DEFAULT_TIMEOUT_POLICY, diff --git a/packages/daemon/src/core/daemon-command-registry.ts b/packages/daemon/src/core/daemon-command-registry.ts index 64e56b0e81..c4af3e7678 100644 --- a/packages/daemon/src/core/daemon-command-registry.ts +++ b/packages/daemon/src/core/daemon-command-registry.ts @@ -71,6 +71,11 @@ export function ignoresSessionLease(command: string): boolean { return getDaemonCommandDescriptor(command)?.ignoresSessionLease === true; } +export function isDetachedFromSessionDevice(req: DaemonRequest): boolean { + const entry = getDaemonCommandDescriptor(req.command); + return entry?.ignoresSessionLease === true || entry?.detachedFromSessionDevice?.(req) === true; +} + export function isAppLeaseAllowed(command: string): boolean { return getDaemonCommandDescriptor(command)?.appLease === 'allowed'; } diff --git a/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts b/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts index 4d79e2c4ad..bb978d3052 100644 --- a/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts @@ -8,6 +8,7 @@ import { type WebSessionIdentity, } from '@agent-device/kernel/device'; import { + ANDROID_DEVICE, WEB_DESKTOP_DEVICE, closeLoopbackServer, createTestHostEnvironment, @@ -25,6 +26,10 @@ import { lifecycleDeviceRuntimeGateway, } from '../../__tests__/support/test-device-runtime-gateway.ts'; import type { DaemonRequest } from '../../core/daemon-request.ts'; +import { + installInteractorResolution, + interactorResolution, +} from '../../core/interactor-resolution.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { daemonPlatformServicesFixture } from '../../__tests__/support/platform-services-fixture.ts'; import { resolveCommandDevice } from '../../resources/session-device-resolution.ts'; @@ -167,6 +172,155 @@ function openWebRequest(session: string): DaemonRequest { }; } +test('remote web open is refused before a browser runtime binds', async () => { + mockResolveTargetDevice.mockImplementation(webSessionResolution); + const store = makeSessionStore('agent-device-remote-web-denied-'); + let binds = 0; + const handler = createOpenHandler(store, new LeaseRegistry(), { + ...lifecycleDeviceRuntimeGateway, + bind: async (request) => { + binds += 1; + return await lifecycleDeviceRuntimeGateway.bind(request); + }, + }); + + const result = await handler({ + ...openWebRequest('remote-web'), + internal: { publicNetworkOnly: true }, + }); + expect(result).toMatchObject({ + ok: false, + error: { + code: 'UNSUPPORTED_OPERATION', + retriable: false, + details: { reason: 'REMOTE_WEB_PUBLIC_NETWORK_UNENFORCED' }, + }, + }); + expect(binds).toBe(0); + expect(store.toArray()).toEqual([]); +}); + +test('remote requests cannot use an existing web session', async () => { + mockResolveTargetDevice.mockImplementation(webSessionResolution); + const store = makeSessionStore('agent-device-remote-web-existing-'); + store.publish('existing-web', makeSession('existing-web', { device: WEB_DESKTOP_DEVICE })); + let binds = 0; + const handler = createOpenHandler(store, new LeaseRegistry(), { + ...lifecycleDeviceRuntimeGateway, + bind: async (request) => { + binds += 1; + return await lifecycleDeviceRuntimeGateway.bind(request); + }, + }); + + const result = await handler({ + token: 'test-token', + session: 'existing-web', + command: 'snapshot', + positionals: [], + flags: {}, + meta: { requestId: 'remote-existing-web', sessionExplicit: true }, + internal: { publicNetworkOnly: true }, + }); + expect(result).toMatchObject({ + ok: false, + error: { retriable: false, details: { reason: 'REMOTE_WEB_PUBLIC_NETWORK_UNENFORCED' } }, + }); + expect(binds).toBe(0); +}); + +test('remote replay on an existing web session is refused before any snapshot', async () => { + mockResolveTargetDevice.mockImplementation(webSessionResolution); + const store = makeSessionStore('agent-device-remote-web-replay-'); + store.publish('existing-web', makeSession('existing-web', { device: WEB_DESKTOP_DEVICE })); + const replayPath = path.join(mkdtempForTestSync('agent-device-remote-web-replay-'), 'flow.ad'); + fs.writeFileSync(replayPath, 'context platform=web\nclick "Save"\n'); + const snapshot = vi.fn(async () => ({ nodes: [] })); + const previous = interactorResolution(); + installInteractorResolution({ resolve: async () => ({ snapshot }) as never }); + try { + const result = await createOpenHandler(store)({ + ...freshWebRequest('replay', 'existing-web', replayPath), + internal: { publicNetworkOnly: true }, + }); + expect(result).toMatchObject({ + ok: false, + error: { retriable: false, details: { reason: 'REMOTE_WEB_PUBLIC_NETWORK_UNENFORCED' } }, + }); + expect(snapshot).not.toHaveBeenCalled(); + } finally { + installInteractorResolution(previous); + } +}); + +test('remote close can release an existing web session', async () => { + mockResolveTargetDevice.mockImplementation(webSessionResolution); + const store = makeSessionStore('agent-device-remote-web-close-'); + store.publish('existing-web', makeSession('existing-web', { device: WEB_DESKTOP_DEVICE })); + const handler = createOpenHandler(store); + + const result = await handler({ + token: 'test-token', + session: 'existing-web', + command: 'close', + positionals: [], + flags: {}, + meta: { requestId: 'remote-close-web', sessionExplicit: true }, + internal: { publicNetworkOnly: true }, + }); + expect(result).toMatchObject({ ok: true }); + expect(store.get('existing-web')).toBeUndefined(); +}); + +const androidSerial = { platform: 'android' as const, serial: ANDROID_DEVICE.id }; +test.each([ + { command: 'devices', flags: {}, refused: false }, + { command: 'session_list', flags: {}, refused: false }, + { command: 'lease_allocate', flags: {}, refused: false }, + { command: 'artifacts', flags: {}, refused: false }, + { command: 'doctor', flags: { remote: true }, leased: true, refused: false }, + { command: 'capabilities', flags: androidSerial, refused: false }, + { command: 'apps', flags: androidSerial, refused: false }, + { command: 'doctor', flags: {}, leased: true, refused: true }, + { command: 'capabilities', flags: {}, refused: true }, +])('remote $command $flags at a web session address: refused=$refused', async (row) => { + mockResolveTargetDevice.mockImplementation(async (flags, options) => + (flags as { serial?: string }).serial ? ANDROID_DEVICE : webSessionResolution(flags, options), + ); + const store = makeSessionStore('agent-device-remote-web-detached-'); + const leaseRegistry = new LeaseRegistry(); + const lease = row.leased ? leaseRegistry.allocateLease({ tenantId: 't', runId: 'r' }) : undefined; + store.publish( + 'existing-web', + makeSession('existing-web', { + device: WEB_DESKTOP_DEVICE, + sessionScope: { kind: 'named-local' }, + ...(lease && { lease }), + }), + ); + const result = await createOpenHandler( + store, + leaseRegistry, + )({ + token: 'test-token', + session: 'existing-web', + command: row.command, + positionals: [], + flags: row.flags, + meta: { requestId: `remote-${row.command}`, sessionExplicit: true, leaseId: lease?.leaseId }, + internal: { publicNetworkOnly: true }, + }); + const reason = result.ok ? undefined : result.error.details?.reason; + expect(reason === 'REMOTE_WEB_PUBLIC_NETWORK_UNENFORCED').toBe(row.refused); +}); + +test('local web open is unaffected by the remote web refusal', async () => { + mockResolveTargetDevice.mockImplementation(webSessionResolution); + const store = makeSessionStore('agent-device-local-web-open-'); + const result = await createOpenHandler(store)(openWebRequest('local-web')); + expect(result).toMatchObject({ ok: true }); +}); + test('implicit web sessions isolate workspaces and retain their device on follow-up requests', async () => { mockResolveTargetDevice.mockImplementation(webSessionResolution); const claimsDir = mkdtempForTestSync('agent-device-web-workspace-claims-'); diff --git a/packages/daemon/src/server/remote-host-input-policy.ts b/packages/daemon/src/server/remote-host-input-policy.ts index 623de0ff2b..b94eba1c8f 100644 --- a/packages/daemon/src/server/remote-host-input-policy.ts +++ b/packages/daemon/src/server/remote-host-input-policy.ts @@ -1,14 +1,25 @@ +import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { INTERNAL_COMMANDS } from '@agent-device/command-registry/catalog'; import { validateAndNormalizeBatchSteps } from '@agent-device/command-registry/batch'; import { DEFAULT_BATCH_MAX_STEPS } from '@agent-device/contracts/command'; import type { DaemonRequest } from '../core/daemon-request.ts'; +import type { SessionState } from '../core/session-state.ts'; +import { listSessionSelectorConflicts } from '../core/session-selector.ts'; +import { hasExplicitDeviceSelector } from '../core/device/device-selector-intent.ts'; +import { + isDetachedFromSessionDevice, + shouldPreferExplicitDeviceOverExistingSession, +} from '../core/daemon-command-registry.ts'; import { remoteScriptOpen } from '../core/session-script-publication-capability.ts'; const REMOTE_HOST_INPUT_REASONS = { // A remote request supplied a host path or other host input (`details.field`), which a remote // daemon refuses. denied: { reason: 'REMOTE_HOST_INPUT_DENIED' }, + // A remote request tried to use the managed browser on the daemon host, which cannot enforce a + // public-network-only policy. + webPublicNetworkUnenforced: { reason: 'REMOTE_WEB_PUBLIC_NETWORK_UNENFORCED' }, } as const satisfies ReasonTable<'remote daemon'>; const HOST_PATH_FIELDS = [ @@ -215,3 +226,33 @@ function remoteHostInputDenied(field: string, hint = REMOTE_HOST_INPUT_HINT): Ap hint, }); } + +function assertRemoteWebDeviceAdmitted(request: DaemonRequest, device: DeviceInfo): void { + if (!request.internal?.publicNetworkOnly) return; + if (device.platform !== 'web' || request.command === 'close') return; + throw new AppError( + 'UNSUPPORTED_OPERATION', + 'The managed web browser cannot enforce public-network-only access for remote requests.', + { reason: REMOTE_HOST_INPUT_REASONS.webPublicNetworkUnenforced.reason, retriable: false }, + ); +} + +export function assertRemoteWebSessionAdmitted(req: DaemonRequest, session?: SessionState): void { + if (!session || !req.internal?.publicNetworkOnly || isDetachedFromSessionDevice(req)) return; + const selectsOtherDevice = + shouldPreferExplicitDeviceOverExistingSession(req) && + hasExplicitDeviceSelector(req.flags) && + listSessionSelectorConflicts(session, req.flags).length > 0; + if (!selectsOtherDevice) assertRemoteWebDeviceAdmitted(req, session.device); +} + +export function withRemoteWebAdmission( + request: DaemonRequest, + admitPin: ((device: DeviceInfo) => void) | undefined, +): ((device: DeviceInfo) => void) | undefined { + if (!request.internal?.publicNetworkOnly) return admitPin; + return (device) => { + assertRemoteWebDeviceAdmitted(request, device); + admitPin?.(device); + }; +} diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index 5df273517d..1accd3fbcd 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -1,6 +1,6 @@ import { LEASE_REASONS } from '@agent-device/contracts/lease-scope'; import { thrownBeforeDispatch } from '../execution/request-dispatch-disclosure.ts'; -import { restrictRemoteHostInputs } from './remote-host-input-policy.ts'; +import * as remoteInput from './remote-host-input-policy.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { heldKeyedLockKeys } from '@agent-device/kernel/keyed-lock'; @@ -230,7 +230,7 @@ export async function createRequestExecutionScope(params: { }): Promise { const { sessionStore, leaseRegistry } = params; // Bound here, before this request takes a lock. - const unscopedReq = restrictRemoteHostInputs(params.req); + const unscopedReq = remoteInput.restrictRemoteHostInputs(params.req); const tenantScopedReq = scopeRequestSession(unscopedReq); // A nested batch or replay step arrives with the identity of the request that spawned it, and its // own name is already the store key. @@ -629,6 +629,7 @@ export async function createRequestExecutionScope(params: { let admissionCompleted = false; try { const existingRef = resolveRequestSessionRef(scopedReq, addressed, leaseRegistry); + remoteInput.assertRemoteWebSessionAdmitted(scopedReq, existingRef?.session); const existingDevice = existingRef?.session.device; if (isAndroidSessionObservation(scopedReq, existingDevice)) return await runObservation(existingDevice); @@ -810,7 +811,8 @@ function createRequestDeviceAccess(params: { scope: platformRequestScope, dispatchLedger: params.dispatchLedger, admitDeviceClaim: claimAdmission.admit, - admitDevice: + admitDevice: remoteInput.withRemoteWebAdmission( + params.req, params.admitDevicePin || daemonPolicy || claimPolicy === 'require-owner' ? (device) => { params.admitDevicePin?.(device); @@ -840,6 +842,7 @@ function createRequestDeviceAccess(params: { } } : undefined, + ), }), }; } diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 33c3d3f084..477193a444 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -1111,6 +1111,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `REMOTE_HOST_INPUT_DENIED` | A remote request supplied a host path or other host input (`details.field`), which a remote daemon refuses. | +| `REMOTE_WEB_PUBLIC_NETWORK_UNENFORCED` | A remote request tried to use the managed browser on the daemon host, which cannot enforce a public-network-only policy. | ### Remote transfer diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index bea0453832..7f40f1c2d4 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -158,7 +158,7 @@ derive delivery from step results. Remote requests ignore `meta.cwd`. They refuse host tooling paths and `--launch-console` with reason `REMOTE_HOST_INPUT_DENIED`. They also refuse daemon host paths as `install` and `reinstall` binaries, `push` payload files, and xctrace template files. `open` targets and launch -URLs cannot use the `file:` scheme. Serve local web content over HTTP(S) instead. Upload binaries with the +URLs cannot use the `file:` scheme. Remote web browser use is refused, so run web sessions locally. Upload binaries with the client, send `push` payloads as inline JSON, and name xctrace templates. Omit these inputs, or use a local daemon for host tooling. Test suite artifacts also use a daemon-chosen output root. @@ -409,6 +409,8 @@ daemons omit it. {"ok":true,"service":"agent-device-proxy","version":"0.21.39-dev","rpcProtocolVersion":3,"instanceId":"5f0c2d7e-8a41-4b7e-9c3a-2e6d1f4b8a90","hostArch":"arm64","upstream":{"ok":true,"service":"agent-device-daemon","version":"0.21.39-dev","rpcProtocolVersion":3,"instanceId":"b3e9a6c1-4d2f-4f8e-a0b7-7c5d9e1f2a34","hostArch":"arm64"}} ``` +A remote request cannot use the managed browser on the daemon host, because that browser could reach the host's private network. A remote command that would use it returns `UNSUPPORTED_OPERATION` with `details.reason: "REMOTE_WEB_PUBLIC_NETWORK_UNENFORCED"`. `close` stays allowed. Automating public sites through a remote managed browser is intentionally disabled. + ## Clean up Run `agent-device disconnect` when you finish the remote session. Stop the tunnel and the `agent-device proxy` process only when the host should stop accepting remote clients. Restarting the proxy generates a fresh token unless you supplied `--daemon-auth-token` explicitly.