diff --git a/packages/apple-runner/src/__tests__/runner-transport.test.ts b/packages/apple-runner/src/__tests__/runner-transport.test.ts index b4231879b1..5145ec4560 100644 --- a/packages/apple-runner/src/__tests__/runner-transport.test.ts +++ b/packages/apple-runner/src/__tests__/runner-transport.test.ts @@ -39,7 +39,11 @@ vi.mock('../runner-usbmux.ts', async (importOriginal) => { }); import { clearDeviceTunnelIpCache } from '../runner-command-route.ts'; -import { fetchWithTimeout, sendRunnerCommandOnce } from '../runner-transport.ts'; +import { + fetchWithTimeout, + postRunnerCommandOverRoute, + sendRunnerCommandOnce, +} from '../runner-transport.ts'; import { mkdtempForTestSync } from './tmp-dir.ts'; // The real `resolveIosPhysicalDeviceControl` resolves the CoreDevice tunnel IP @@ -211,6 +215,84 @@ test('sendRunnerCommandOnce reaches the macOS host runner on loopback, never ove assert.equal(mockRunCmd.mock.calls.length, 0); }); +test('a forwarded runner route never sends its tokens over plain http off loopback', async () => { + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + const endpoint = { + ...RUNNER_ENDPOINT_FIXTURE, + http: { url: 'http://instance.invalid/command', headers: { Authorization: 'Bearer limrun' } }, + }; + + await assert.rejects( + () => sendRunnerCommandOnce(iosSimulator, endpoint, { command: 'uptime' }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.reason, 'insecure_credential_transport'); + assert.equal(error.details?.dispatched, 'no'); + return true; + }, + ); + assert.equal(fetchMock.mock.calls.length, 0); +}); + +test('the runner sends to a CoreDevice tunnel address with fetch, as a bracketed fd00:: host', async () => { + mockUsbmuxPostCommand.mockRejectedValue(usbmuxDeviceUnattachedError()); + stubSuccessfulFetch(); + mockRunCmd.mockImplementation(makeTunnelIpLookup('fda3:3a9e:368d::1')); + + await sendRunnerCommandOnce(iosDevice, RUNNER_ENDPOINT_FIXTURE, { command: 'uptime' }); + + const [url, init] = vi.mocked(fetch).mock.calls[0]!; + assert.equal(url, 'http://[fda3:3a9e:368d::1]:8100/command'); + assert.equal(init?.redirect, 'error'); +}); + +// The same address is allowed on the tunnel route above, so the exclusion +// follows how the route was resolved, not what the address looks like. +test('a route CoreDevice did not report is refused even at a tunnel-shaped address', async () => { + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + const route = { + kind: 'network', + url: 'http://[fd00::123]:8100/command', + cachedTunnelIp: false, + } as const; + + await assert.rejects( + () => + postRunnerCommandOverRoute(iosDevice, route, { + endpoint: RUNNER_ENDPOINT_FIXTURE, + command: { command: 'uptime' }, + timeoutMs: 5_000, + }), + (error: unknown) => { + assert.equal((error as AppError).details?.reason, 'insecure_credential_transport'); + assert.equal((error as AppError).details?.dispatched, 'no'); + return true; + }, + ); + assert.equal(fetchMock.mock.calls.length, 0); +}); + +test.each(['fe80::1', '2001:db8::1', 'fc00::1', '10.0.0.7', 'iphone.coredevice.local'])( + 'a reported tunnel address of %s is no tunnel route, so it never receives the runner token', + async (reported) => { + mockUsbmuxPostCommand.mockRejectedValue(usbmuxDeviceUnattachedError()); + stubSuccessfulFetch(); + mockRunCmd.mockImplementation(makeTunnelIpLookup(reported)); + + await assert.rejects( + () => sendRunnerCommandOnce(iosDevice, RUNNER_ENDPOINT_FIXTURE, { command: 'uptime' }), + (error: unknown) => { + assert.equal((error as AppError).details?.reason, 'insecure_credential_transport'); + assert.equal((error as AppError).details?.dispatched, 'no'); + return true; + }, + ); + assert.equal(vi.mocked(fetch).mock.calls.length, 0); + }, +); + test('sendRunnerCommandOnce writes nothing for a device with no route, and says so', async () => { mockUsbmuxPostCommand.mockRejectedValue(usbmuxDeviceUnattachedError()); const fetchMock = vi.fn(); diff --git a/packages/apple-runner/src/runner-command-route.ts b/packages/apple-runner/src/runner-command-route.ts index 8a0eb19ba5..60ef4ea781 100644 --- a/packages/apple-runner/src/runner-command-route.ts +++ b/packages/apple-runner/src/runner-command-route.ts @@ -19,6 +19,12 @@ export type RunnerCommandRoute = kind: 'network'; url: string | null; cachedTunnelIp: boolean; + /** + * Set only on the route built from the tunnel address CoreDevice reports for this device. + * Its tunnel encrypts the traffic, so it may carry the runner token over plain http to a + * tunnel address that is not loopback. + */ + coreDeviceTunnel?: true; } | { kind: 'usbmux'; @@ -115,6 +121,7 @@ function buildTunnelRoute( kind: 'network', url: tunnelIp ? `http://[${tunnelIp}]:${port}/command` : null, cachedTunnelIp, + coreDeviceTunnel: true, }; } diff --git a/packages/apple-runner/src/runner-transport.ts b/packages/apple-runner/src/runner-transport.ts index 4fa663a2b7..996c5e892f 100644 --- a/packages/apple-runner/src/runner-transport.ts +++ b/packages/apple-runner/src/runner-transport.ts @@ -105,6 +105,18 @@ export async function postRunnerCommandOverRoute( 'no', ); } + // The request carries the runner token, and a forwarded one the provider's own headers. A + // simulator or macOS runner listens on 127.0.0.1, so only another route loads the rule. + if (URL.parse(route.url)?.hostname !== '127.0.0.1') { + const { assertSecureCredentialTransport } = + await import('@agent-device/contracts/credential-transport'); + assertSecureCredentialTransport( + route.url, + endpoint.http ? 'Runner forwarding URL' : 'Runner device address', + { coreDeviceTunnel: route.coreDeviceTunnel }, + ); + throwIfCanceledBeforeSend(signal); + } const response = await fetchWithTimeout( route.url, { diff --git a/packages/contracts/package.json b/packages/contracts/package.json index bcdc022689..b73faaa3d8 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -168,6 +168,10 @@ "types": "./src/daemon-command-surface.ts", "default": "./src/daemon-command-surface.ts" }, + "./credential-transport": { + "types": "./src/credential-transport.ts", + "default": "./src/credential-transport.ts" + }, "./daemon-http": { "types": "./src/daemon-http.ts", "default": "./src/daemon-http.ts" @@ -308,6 +312,10 @@ "types": "./src/logs-runtime-plan.ts", "default": "./src/logs-runtime-plan.ts" }, + "./loopback-host": { + "types": "./src/loopback-host.ts", + "default": "./src/loopback-host.ts" + }, "./managed-web-backend": { "types": "./src/managed-web-backend.ts", "default": "./src/managed-web-backend.ts" diff --git a/packages/contracts/src/credential-transport.test.ts b/packages/contracts/src/credential-transport.test.ts new file mode 100644 index 0000000000..ceedf5c772 --- /dev/null +++ b/packages/contracts/src/credential-transport.test.ts @@ -0,0 +1,97 @@ +import { expect, test } from 'vitest'; +import { AppError } from '@agent-device/kernel/errors'; +import { + assertSecureCredentialSocket, + assertSecureCredentialTransport, +} from './credential-transport.ts'; +import { isLoopbackHostname } from './loopback-host.ts'; + +test('loopback hostnames are recognized in each spelling a base URL carries', () => { + expect(isLoopbackHostname('LocalHost ')).toBe(true); + expect(isLoopbackHostname('127.0.0.1')).toBe(true); + expect(isLoopbackHostname('[::1]')).toBe(true); + expect(isLoopbackHostname('::ffff:127.0.0.1')).toBe(true); + expect(isLoopbackHostname('0.0.0.0')).toBe(false); + expect(isLoopbackHostname('127.1.2.3')).toBe(true); + expect(isLoopbackHostname('localhost.example.test')).toBe(false); + expect(isLoopbackHostname('')).toBe(false); +}); + +test.each([ + 'https://fleet.example.test/agent-device', + 'https://10.0.0.7:4310', + 'http://127.0.0.1:4310/agent-device', + 'http://[::1]:4310', + 'http://localhost:4310', +])('a credential may travel to %s', (url) => { + expect(assertSecureCredentialTransport(url, 'Remote daemon base URL').href).toBe( + new URL(url).href, + ); +}); + +test.each([ + 'http://fleet.example.test/agent-device', + 'http://10.0.0.7:4310', + 'http://0.0.0.0:4310', + 'http://localhost.:4310', + 'ws://127.0.0.1:4310', + 'http:', +])('a credential never travels to %s', (url) => { + let refusal: unknown; + try { + assertSecureCredentialTransport(url, 'Remote daemon base URL'); + } catch (error) { + refusal = error; + } + expect(refusal).toBeInstanceOf(AppError); + expect((refusal as AppError).code).toBe('INVALID_ARGS'); + expect((refusal as AppError).details?.reason).toBe('insecure_credential_transport'); +}); + +test.each([ + 'wss://bridge.example.test/bridge?ticket=t', + 'ws://127.0.0.1:4310/bridge?ticket=t', + 'WS://[::1]:4310/bridge', + 'ws://localhost:4310/bridge', +])('a credential socket may open to %s', (url) => { + expect(assertSecureCredentialSocket(url, 'Bridge socket URL').href).toBe(new URL(url).href); +}); + +test.each([ + 'ws://bridge.example.test/bridge?ticket=t', + 'ws://10.0.0.7:4310/bridge', + 'http://localhost/bridge', + 'http://127.0.0.1:4310/bridge', + 'https://bridge.example.test/bridge', + 'ftp://127.0.0.1/bridge', + 'ws:', +])('a credential socket never opens to %s', (url) => { + expect(() => assertSecureCredentialSocket(url, 'Bridge socket URL')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'insecure_credential_transport' }), + }), + ); +}); + +test.each(['http://[fd00::1]:8100/command', 'http://[fdda:2b::42]:8100'])( + 'the CoreDevice tunnel exception admits %s, and only when asked for', + (url) => { + expect(() => assertSecureCredentialTransport(url, 'Runner URL')).toThrow(); + expect( + assertSecureCredentialTransport(url, 'Runner URL', { coreDeviceTunnel: true }).href, + ).toBe(new URL(url).href); + }, +); + +test.each([ + 'http://[fe80::1]:8100', + 'http://[fc00::1]:8100', + 'http://[2001:db8::1]:8100', + 'http://10.0.0.7:8100', + 'http://iphone.coredevice.local:8100', + 'ws://[fd00::1]:8100', +])('the CoreDevice tunnel exception never admits %s', (url) => { + expect(() => + assertSecureCredentialTransport(url, 'Runner URL', { coreDeviceTunnel: true }), + ).toThrow(); +}); diff --git a/packages/contracts/src/credential-transport.ts b/packages/contracts/src/credential-transport.ts new file mode 100644 index 0000000000..1e634d9b3f --- /dev/null +++ b/packages/contracts/src/credential-transport.ts @@ -0,0 +1,90 @@ +import net from 'node:net'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { isLoopbackHostname } from './loopback-host.ts'; + +// The one rule for every request that carries a credential (a daemon or proxy token, a host bridge +// or provider bearer, a cloud auth secret): it travels over https, or over plain http only to this +// machine. + +/** Why a client refuses to send a credential before any request leaves. */ +const CREDENTIAL_TRANSPORT_REASONS = { + // A credential would travel over plain http or ws to a host that is not loopback, to a socket URL + // that is not ws or wss, or to a URL that does not parse. The refusal names the setting, never + // the destination. + insecureTransport: { reason: 'insecure_credential_transport' }, +} as const satisfies ReasonTable<'remote connection'>; + +/** The one plain-http destination off loopback a credential may name, and only when asked for. */ +export type CredentialTransportExceptions = { + /** The request goes to a device's CoreDevice tunnel address, which that tunnel encrypts. */ + coreDeviceTunnel?: boolean; +}; + +/** Whether a credential sent to `url` stays off the network in cleartext: https, or http on loopback. */ +export function isSecureCredentialDestination(url: URL): boolean { + if (url.protocol === 'https:') return true; + return url.protocol === 'http:' && isLoopbackHostname(url.hostname); +} + +/** Plain http to a unique local IPv6 address in `fd00::/8`, where CoreDevice puts its tunnel. */ +function isCoreDeviceTunnelDestination(url: URL): boolean { + const address = url.hostname.replace(/^\[(.*)\]$/, '$1'); + const range = new net.BlockList(); + range.addSubnet('fd00::', 8, 'ipv6'); + return url.protocol === 'http:' && net.isIPv6(address) && range.check(address, 'ipv6'); +} + +/** + * Refuses a credential-bearing destination unless it is https or plain http to loopback. A URL + * that does not parse is refused too. `subject` names the setting in the message; the destination + * itself is never named, so a refusal is safe on paths that must not disclose their endpoint. + */ +export function assertSecureCredentialTransport( + url: string | URL, + subject: string, + exceptions: CredentialTransportExceptions = {}, +): URL { + const destination = typeof url === 'string' ? URL.parse(url) : url; + if (destination) { + if (isSecureCredentialDestination(destination)) return destination; + if (exceptions.coreDeviceTunnel && isCoreDeviceTunnelDestination(destination)) { + return destination; + } + } + throw credentialTransportRefusal( + destination + ? `${subject} must use https to send credentials; plain http is allowed only on loopback.` + : `${subject} is not a valid URL, so no credential is sent to it.`, + ); +} + +/** + * The same rule for a WebSocket that carries a credential: `wss` to any host, or `ws` to loopback. + * Any other scheme is refused, including the http and https a `WebSocket` would accept. + */ +export function assertSecureCredentialSocket(url: string, subject: string): URL { + const destination = URL.parse(url); + if (destination?.protocol === 'wss:') return destination; + if (destination?.protocol === 'ws:' && isLoopbackHostname(destination.hostname)) { + return destination; + } + throw credentialTransportRefusal( + `${subject} must use wss to send credentials; ws is allowed only on loopback.`, + ); +} + +/** The typed refusal. It is only ever thrown before the credential leaves. */ +function credentialTransportRefusal(message: string): AppError { + return new AppError('INVALID_ARGS', message, { + reason: CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason, + dispatched: 'no', + hint: 'Use an https or wss URL, or reach the host through a loopback tunnel or port forward, for example ssh -L 4310:127.0.0.1:4310 and then http://127.0.0.1:4310.', + }); +} + +export function isCredentialTransportRefusal(error: unknown): error is AppError { + return ( + error instanceof AppError && + error.details?.reason === CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason + ); +} diff --git a/packages/contracts/src/loopback-host.ts b/packages/contracts/src/loopback-host.ts new file mode 100644 index 0000000000..51fedd1fa9 --- /dev/null +++ b/packages/contracts/src/loopback-host.ts @@ -0,0 +1,18 @@ +import net from 'node:net'; + +const LOOPBACK_BLOCK_LIST = new net.BlockList(); +LOOPBACK_BLOCK_LIST.addSubnet('127.0.0.0', 8, 'ipv4'); +LOOPBACK_BLOCK_LIST.addAddress('::1', 'ipv6'); +LOOPBACK_BLOCK_LIST.addSubnet('::ffff:127.0.0.0', 104, 'ipv6'); + +/** Whether an address names this machine: `localhost` or a loopback literal. */ +export function isLoopbackHostname(hostname: string): boolean { + const normalized = hostname + .trim() + .toLowerCase() + .replace(/^\[(.*)\]$/, '$1'); + if (normalized === 'localhost') return true; + if (net.isIPv4(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv4'); + if (net.isIPv6(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv6'); + return false; +} diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts index ff5455d08d..a600106f4f 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts @@ -1,9 +1,9 @@ // A checked call whose connection never opens is this client's own proof that nothing left. On fake // time: the first POST never connects, so the connect timer fires, the `/health` loop runs, and the -// command is sent once more. `http.request` is replaced, so no real socket is involved. +// command is sent once more. `https.request` is replaced, so no real socket is involved. import assert from 'node:assert/strict'; -import http from 'node:http'; +import https from 'node:https'; import { EventEmitter } from 'node:events'; import { afterEach, test, vi } from 'vitest'; import { isRequestCanceledError } from '@agent-device/kernel/errors'; @@ -26,7 +26,7 @@ function fakeResponse(): EventEmitter { */ function firstCheckedConnectHangs(healthStatus = 200, healthProtocol = 3): Call[] { const calls: Call[] = []; - vi.spyOn(http, 'request').mockImplementation((( + vi.spyOn(https, 'request').mockImplementation((( options: { method?: string; path?: string }, callback: (res: EventEmitter) => void, ) => { @@ -72,14 +72,14 @@ function firstCheckedConnectHangs(healthStatus = 200, healthProtocol = 3): Call[ }, }); return req; - }) as unknown as typeof http.request); + }) as unknown as typeof https.request); return calls; } /** Every checked POST is refused before it connects, while `/health` answers 503. */ function checkedConnectRefused(): Call[] { const calls: Call[] = []; - vi.spyOn(http, 'request').mockImplementation((( + vi.spyOn(https, 'request').mockImplementation((( options: { method?: string; path?: string }, callback: (res: EventEmitter) => void, ) => { @@ -111,7 +111,7 @@ function checkedConnectRefused(): Call[] { }, }); return req; - }) as unknown as typeof http.request); + }) as unknown as typeof https.request); return calls; } @@ -133,7 +133,7 @@ function driveFakeTime(): () => Promise { }; } -const BASE_URL = 'http://remote-mac.example.test:7777/agent-device'; +const BASE_URL = 'https://remote-mac.example.test:7777/agent-device'; let tokenSeq = 0; /** A token of its own per test: the process health cache is keyed by it. */ diff --git a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts new file mode 100644 index 0000000000..a32933d77b --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts @@ -0,0 +1,80 @@ +// A remote daemon token never travels over plain http off loopback: the refusal comes from the +// settings the client reads, before any socket opens. + +import assert from 'node:assert/strict'; +import http from 'node:http'; +import https from 'node:https'; +import net from 'node:net'; +import { afterEach, test, vi } from 'vitest'; +import { createTestHostEnvironment } from '@agent-device/test-kit'; +import { AppError } from '@agent-device/kernel/errors'; +import { assertRemoteServesCheckedRpc, createDaemonTransport } from '../index.ts'; + +const REQUEST = { session: 'default', command: 'devices', positionals: [], flags: {} }; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +const INSECURE_BASE_URL = 'http://remote-mac.example.test:7777/agent-device'; + +function spyOnEverySend() { + return [ + vi.spyOn(http, 'request'), + vi.spyOn(https, 'request'), + vi.spyOn(net, 'connect'), + vi.spyOn(net, 'createConnection'), + vi.spyOn(globalThis, 'fetch'), + ]; +} + +async function refusalOf(task: () => Promise): Promise { + const refusal = await task().then( + () => assert.fail('expected the plain http base URL to be refused'), + (error: unknown) => error, + ); + assert.ok(refusal instanceof AppError, String(refusal)); + return refusal; +} + +// The health-first route, and the checked route a connected profile opts into, both send the token +// to the same base URL; neither the probe nor the checked POST nor a recovery probe may start. +test.each([ + ['health-first', {}], + ['checked', { daemonRpc: 'checked' }], +] as const)( + 'a token for a plain http daemon off loopback is refused on the %s route before any request leaves', + async (_route, flags) => { + const opened = spyOnEverySend(); + const send = createDaemonTransport( + createTestHostEnvironment({ + env: { + AGENT_DEVICE_DAEMON_BASE_URL: INSECURE_BASE_URL, + AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'remote-secret', + }, + }), + ); + + const refusal = await refusalOf(() => send({ ...REQUEST, flags })); + + assert.equal(refusal.code, 'INVALID_ARGS'); + assert.equal(refusal.details?.reason, 'insecure_credential_transport'); + assert.doesNotMatch(JSON.stringify([refusal.message, refusal.details]), /remote-mac/); + for (const spy of opened) assert.equal(spy.mock.calls.length, 0); + }, +); + +test('the connect checked-capability probe refuses a plain http daemon off loopback unsent', async () => { + const opened = spyOnEverySend(); + + const refusal = await refusalOf(() => + assertRemoteServesCheckedRpc( + { daemonBaseUrl: INSECURE_BASE_URL, daemonAuthToken: 'remote-secret' }, + createTestHostEnvironment(), + ), + ); + + assert.equal(refusal.details?.reason, 'insecure_credential_transport'); + assert.doesNotMatch(JSON.stringify([refusal.message, refusal.details]), /remote-mac/); + for (const spy of opened) assert.equal(spy.mock.calls.length, 0); +}); diff --git a/packages/daemon-client/src/__tests__/daemon-client-remote-health-recovery-budget.test.ts b/packages/daemon-client/src/__tests__/daemon-client-remote-health-recovery-budget.test.ts index c7b0a32862..24f9fc7397 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-remote-health-recovery-budget.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-remote-health-recovery-budget.test.ts @@ -1,19 +1,19 @@ // The remote `/health` gate re-probes a daemon that answers 5xx for the command's own budget. This -// drives a whole default budget on fake time: `http.request` answers on the next tick, so no real +// drives a whole default budget on fake time: `https.request` answers on the next tick, so no real // timer or socket is involved. import assert from 'node:assert/strict'; -import http from 'node:http'; +import https from 'node:https'; import { EventEmitter } from 'node:events'; import { afterEach, test, vi } from 'vitest'; import { AppError, isRequestCanceledError } from '@agent-device/kernel/errors'; import { sendToDaemon } from '../index.ts'; -/** Replaces `http.request` with one that answers every request 503, recording each probe's time. */ +/** Replaces `https.request` with one that answers every request 503, recording each probe's time. */ function answerEveryRequest503(): { probeTimes: number[]; rpcs: () => number } { const probeTimes: number[] = []; let rpcs = 0; - vi.spyOn(http, 'request').mockImplementation((( + vi.spyOn(https, 'request').mockImplementation((( options: { method?: string }, callback: (res: EventEmitter) => void, ) => { @@ -35,7 +35,7 @@ function answerEveryRequest503(): { probeTimes: number[]; rpcs: () => number } { }, }); return req; - }) as unknown as typeof http.request); + }) as unknown as typeof https.request); return { probeTimes, rpcs: () => rpcs }; } @@ -66,7 +66,7 @@ function remoteSessionList() { session: 'default', command: 'session', positionals: ['list'], - flags: { daemonBaseUrl: 'http://remote-mac.example.test:7777/agent-device' }, + flags: { daemonBaseUrl: 'https://remote-mac.example.test:7777/agent-device' }, meta: { requestId: 'req-remote-budget' }, }; } diff --git a/packages/daemon-client/src/__tests__/index.test.ts b/packages/daemon-client/src/__tests__/index.test.ts index 0549473e2a..8ab733f967 100644 --- a/packages/daemon-client/src/__tests__/index.test.ts +++ b/packages/daemon-client/src/__tests__/index.test.ts @@ -2,6 +2,7 @@ import type { RequestProgressEvent } from '@agent-device/contracts/progress'; import { test } from 'vitest'; import assert from 'node:assert/strict'; import http from 'node:http'; +import https from 'node:https'; import net from 'node:net'; import { EventEmitter } from 'node:events'; import fs from 'node:fs'; @@ -35,7 +36,7 @@ type MockHttpResponse = EventEmitter & { async function withRemoteDaemonEnv(callback: () => Promise): Promise { const previousBaseUrl = process.env.AGENT_DEVICE_DAEMON_BASE_URL; const previousAuthToken = process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN; - process.env.AGENT_DEVICE_DAEMON_BASE_URL = 'http://remote-mac.example.test:7777/agent-device'; + process.env.AGENT_DEVICE_DAEMON_BASE_URL = 'https://remote-mac.example.test:7777/agent-device'; process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN = 'remote-secret'; try { @@ -56,8 +57,8 @@ function emitJsonRpcResult(res: MockHttpResponse, id: string, result: unknown): function mockEventHttpRequest( handler: (context: { options: Record; body: string; res: MockHttpResponse }) => void, ): () => void { - const originalHttpRequest = http.request; - (http as unknown as { request: typeof http.request }).request = (( + const originalHttpRequest = https.request; + (https as unknown as { request: typeof https.request }).request = (( options: any, callback: (res: any) => void, ) => { @@ -84,10 +85,10 @@ function mockEventHttpRequest( }); }; return req as any; - }) as typeof http.request; + }) as typeof https.request; return () => { - (http as unknown as { request: typeof http.request }).request = originalHttpRequest; + (https as unknown as { request: typeof https.request }).request = originalHttpRequest; }; } @@ -340,8 +341,8 @@ test('sendToDaemon forwards replay test progress before the HTTP NDJSON response const stderrCapture = beginStderrCapture(); const seenPaths: string[] = []; const progressEvents: RequestProgressEvent[] = []; - const originalHttpRequest = http.request; - (http as unknown as { request: typeof http.request }).request = (( + const originalHttpRequest = https.request; + (https as unknown as { request: typeof https.request }).request = (( options: any, callback: (res: any) => void, ) => { @@ -408,7 +409,7 @@ test('sendToDaemon forwards replay test progress before the HTTP NDJSON response }); }; return req as any; - }) as typeof http.request; + }) as typeof https.request; try { await withRemoteDaemonEnv(async () => { @@ -434,7 +435,7 @@ test('sendToDaemon forwards replay test progress before the HTTP NDJSON response assert.equal(progressEvent.title, 'Payments flow'); } } finally { - (http as unknown as { request: typeof http.request }).request = originalHttpRequest; + (https as unknown as { request: typeof https.request }).request = originalHttpRequest; stderrCapture.restore(); } }); @@ -511,8 +512,8 @@ test('sendToDaemon uses explicit remote daemon base URL and auth token', async ( let rpcRequest: Record | null = null; const seenPaths: string[] = []; let healthcheckTimeout: number | undefined; - const originalHttpRequest = http.request; - (http as unknown as { request: typeof http.request }).request = (( + const originalHttpRequest = https.request; + (https as unknown as { request: typeof https.request }).request = (( options: any, callback: (res: any) => void, ) => { @@ -573,11 +574,11 @@ test('sendToDaemon uses explicit remote daemon base URL and auth token', async ( }); }; return req as any; - }) as typeof http.request; + }) as typeof https.request; const previousBaseUrl = process.env.AGENT_DEVICE_DAEMON_BASE_URL; const previousAuthToken = process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN; - process.env.AGENT_DEVICE_DAEMON_BASE_URL = 'http://remote-mac.example.test:7777/agent-device'; + process.env.AGENT_DEVICE_DAEMON_BASE_URL = 'https://remote-mac.example.test:7777/agent-device'; process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN = 'ambient-token'; try { @@ -603,7 +604,7 @@ test('sendToDaemon uses explicit remote daemon base URL and auth token', async ( assert.equal((rpcRequest as any)?.params?.token, 'remote-secret'); assert.equal((rpcRequest as any)?.params?.flags?.daemonAuthToken, undefined); } finally { - (http as unknown as { request: typeof http.request }).request = originalHttpRequest; + (https as unknown as { request: typeof https.request }).request = originalHttpRequest; if (previousBaseUrl === undefined) delete process.env.AGENT_DEVICE_DAEMON_BASE_URL; else process.env.AGENT_DEVICE_DAEMON_BASE_URL = previousBaseUrl; if (previousAuthToken === undefined) delete process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN; @@ -706,8 +707,8 @@ test.each([ test('sendToDaemon sends lease helpers as top-level JSON-RPC methods over HTTP', async () => { const rpcRequests: Record[] = []; - const originalHttpRequest = http.request; - (http as unknown as { request: typeof http.request }).request = (( + const originalHttpRequest = https.request; + (https as unknown as { request: typeof https.request }).request = (( options: any, callback: (res: any) => void, ) => { @@ -766,11 +767,11 @@ test('sendToDaemon sends lease helpers as top-level JSON-RPC methods over HTTP', }); }; return req as any; - }) as typeof http.request; + }) as typeof https.request; const previousBaseUrl = process.env.AGENT_DEVICE_DAEMON_BASE_URL; const previousAuthToken = process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN; - process.env.AGENT_DEVICE_DAEMON_BASE_URL = 'http://remote-mac.example.test:7777/agent-device'; + process.env.AGENT_DEVICE_DAEMON_BASE_URL = 'https://remote-mac.example.test:7777/agent-device'; process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN = 'remote-secret'; try { @@ -841,7 +842,7 @@ test('sendToDaemon sends lease helpers as top-level JSON-RPC methods over HTTP', leaseId: 'lease-new', }); } finally { - (http as unknown as { request: typeof http.request }).request = originalHttpRequest; + (https as unknown as { request: typeof https.request }).request = originalHttpRequest; if (previousBaseUrl === undefined) delete process.env.AGENT_DEVICE_DAEMON_BASE_URL; else process.env.AGENT_DEVICE_DAEMON_BASE_URL = previousBaseUrl; if (previousAuthToken === undefined) delete process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN; diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index f816e9734c..8e2dddc0a6 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -14,8 +14,9 @@ import { stopAndRetireDaemon, type OwnedReplayStateDir, } from '@agent-device/daemon-contracts/daemon-registration-owner'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; +import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; import { - isLoopbackHostname, resolveDaemonPaths, resolveDaemonServerMode, resolveDaemonTransportPreference, @@ -610,8 +611,13 @@ function validateRemoteDaemonTrust( ): void { if (!remoteBaseUrl) return; const hostname = new URL(remoteBaseUrl).hostname; + if (remoteAuthToken?.trim()) { + // Every remote request (health, rpc, probes, transfers, diagnostics) sends the token to this + // base URL, so the refusal comes before the first request. + assertSecureCredentialTransport(remoteBaseUrl, 'Remote daemon base URL'); + return; + } if (isLoopbackHostname(hostname)) return; - if (typeof remoteAuthToken === 'string' && remoteAuthToken.trim().length > 0) return; throw new AppError( 'INVALID_ARGS', 'Remote daemon base URL for non-loopback hosts requires daemon authentication', diff --git a/packages/daemon-contracts/src/daemon-resolution-loopback.test.ts b/packages/daemon-contracts/src/daemon-resolution-loopback.test.ts index 287033ae19..f5ddef72d6 100644 --- a/packages/daemon-contracts/src/daemon-resolution-loopback.test.ts +++ b/packages/daemon-contracts/src/daemon-resolution-loopback.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'vitest'; -import { daemonBaseUrlIsLocal, isLoopbackHostname } from './daemon-resolution.ts'; +import { daemonBaseUrlIsLocal } from './daemon-resolution.ts'; test('a daemon base URL on loopback addresses this machine', () => { expect(daemonBaseUrlIsLocal(undefined)).toBe(true); @@ -15,14 +15,3 @@ test('a daemon base URL off loopback addresses another machine', () => { // An unusable base URL is refused when the transport resolves it; here it is treated as remote. expect(daemonBaseUrlIsLocal('not a url')).toBe(false); }); - -test('loopback hostnames are recognized in each spelling a base URL carries', () => { - expect(isLoopbackHostname('LocalHost ')).toBe(true); - expect(isLoopbackHostname('127.0.0.1')).toBe(true); - expect(isLoopbackHostname('[::1]')).toBe(true); - expect(isLoopbackHostname('::ffff:127.0.0.1')).toBe(true); - expect(isLoopbackHostname('0.0.0.0')).toBe(false); - expect(isLoopbackHostname('127.1.2.3')).toBe(true); - expect(isLoopbackHostname('localhost.example.test')).toBe(false); - expect(isLoopbackHostname('')).toBe(false); -}); diff --git a/packages/daemon-contracts/src/daemon-resolution.ts b/packages/daemon-contracts/src/daemon-resolution.ts index c343aaf6ba..8663fb413b 100644 --- a/packages/daemon-contracts/src/daemon-resolution.ts +++ b/packages/daemon-contracts/src/daemon-resolution.ts @@ -1,6 +1,5 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; -import net from 'node:net'; import path from 'node:path'; import { admitPrivateRoot, @@ -13,6 +12,7 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { type EnvMap } from '@agent-device/kernel/source-value'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; +import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; import type { OwnerIdentity } from '@agent-device/host-kit/process'; import type { DaemonServerMode, DaemonTransportPreference } from '@agent-device/kernel/contracts'; export type { DaemonServerMode, DaemonTransportPreference }; @@ -276,11 +276,6 @@ export function serverModeAnswersTransport( return preference === 'http' ? mode !== 'socket' : mode !== 'http'; } -const LOOPBACK_BLOCK_LIST = new net.BlockList(); -LOOPBACK_BLOCK_LIST.addSubnet('127.0.0.0', 8, 'ipv4'); -LOOPBACK_BLOCK_LIST.addAddress('::1', 'ipv6'); -LOOPBACK_BLOCK_LIST.addSubnet('::ffff:127.0.0.0', 104, 'ipv6'); - /** * Whether a daemon base URL addresses this machine. A caller on a non-loopback daemon drives devices * hosted elsewhere, so it must not read this machine's state to answer a question about them. @@ -297,18 +292,6 @@ export function daemonBaseUrlIsLocal(raw: string | undefined): boolean { return isLoopbackHostname(hostname); } -/** Whether an address names this machine: `localhost` or a loopback literal. */ -export function isLoopbackHostname(hostname: string): boolean { - const normalized = hostname - .trim() - .toLowerCase() - .replace(/^\[(.*)\]$/, '$1'); - if (normalized === 'localhost') return true; - if (net.isIPv4(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv4'); - if (net.isIPv6(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv6'); - return false; -} - export function resolveDaemonTransportPreference( raw: string | undefined, ): DaemonTransportPreference { diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index 098e6076e4..673cb86700 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -22,6 +22,30 @@ test('uses the public Revyl backend when no URL is configured', () => { assert.equal(client.backendUrl, REVYL_DEFAULT_BACKEND_URL); }); +test('a presigned upload URL over plain http off loopback receives nothing', async () => { + const sent: string[] = []; + const client = createRevylClient({ + apiKey: 'test-key', + clientVersion: '0.0.0-test', + fetch: stubFetch((request) => { + sent.push(request.url); + return jsonResponse({}); + }), + }); + + await assert.rejects( + async () => + await client.uploadSessionArtifact( + 'http://storage.invalid/upload?signature=signed', + { filePath: import.meta.filename, size: 1 }, + 'application/zip', + ), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'insecure_credential_transport', + ); + assert.deepEqual(sent, []); +}); + test('keeps plain HTTP only on loopback', () => { assert.equal(resolveRevylBackendUrl('http://127.0.0.1:8787'), 'http://127.0.0.1:8787'); assert.equal(resolveRevylBackendUrl('http://localhost:8787'), 'http://localhost:8787'); diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index fb4b720a18..59f0c8b1e2 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -5,8 +5,9 @@ import { type ReasonTable, } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; +import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; import fs from 'node:fs'; -import net from 'node:net'; import { Readable } from 'node:stream'; import { setTimeout as sleep } from 'node:timers/promises'; import type { @@ -300,6 +301,9 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { }); }, async uploadSessionArtifact(uploadUrl, file, contentType, signal) { + // Revyl chooses this URL, and its signature is the credential: refused before the file is + // opened. + assertSecureCredentialTransport(uploadUrl, 'Revyl upload URL'); // Node streams a request body only in half-duplex mode, which the DOM `RequestInit` type omits. const init: RequestInit & { duplex: 'half' } = { method: 'PUT', @@ -682,20 +686,6 @@ export function isRevylSessionGone(error: unknown): boolean { ); } -/** The loopback ranges, the same set the daemon client trusts for a local daemon. */ -const LOOPBACK_BLOCK_LIST = new net.BlockList(); -LOOPBACK_BLOCK_LIST.addSubnet('127.0.0.0', 8, 'ipv4'); -LOOPBACK_BLOCK_LIST.addAddress('::1', 'ipv6'); -LOOPBACK_BLOCK_LIST.addSubnet('::ffff:127.0.0.0', 104, 'ipv6'); - -/** Whether a WHATWG-normalized hostname (IPv6 in brackets) names a loopback address. */ -function isLoopbackHostname(hostname: string): boolean { - if (hostname === 'localhost') return true; - const address = hostname.startsWith('[') ? hostname.slice(1, -1) : hostname; - const family = net.isIP(address); - return family !== 0 && LOOPBACK_BLOCK_LIST.check(address, family === 6 ? 'ipv6' : 'ipv4'); -} - /** HTTPS everywhere; plain HTTP only on loopback, and never with credentials, query, or fragment. */ export function resolveRevylBackendUrl(raw: string): string { let url: URL; diff --git a/packages/proxy/README.md b/packages/proxy/README.md index 5d92ac6894..1e409e0aaa 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -144,7 +144,7 @@ host opened to your gateway: ```ts const proxy = createDaemonProxy({ - upstreamBaseUrl: 'http://device-host-17.internal', + upstreamBaseUrl: 'https://device-host-17.internal', upstreamToken: daemonToken, clientToken, upstreamFetch: (request) => deviceHostTunnel.send(request), @@ -152,12 +152,21 @@ const proxy = createDaemonProxy({ ``` `upstreamFetch` receives a `Request` addressed to `upstreamBaseUrl` and must resolve with the -daemon's `Response`. Abort the exchange when `request.signal` aborts. - -Honor `request.redirect`. On `/rpc/checked` it is `'error'`: never follow a redirect there, because -a followed redirect resends the call with the daemon token, possibly to the unchecked `/rpc`. The -proxy refuses a checked answer that is a redirect or reports `redirected`, but it cannot undo a -request your transport already resent. +daemon's `Response`. Abort the exchange when `request.signal` aborts. The request carries the +upstream token and `redirect: 'manual'`: return a 3xx response as it is and never follow it. The +proxy relays a 3xx status, such as the daemon's `308` resume response, to its client without a +`Location` header. On `/rpc/checked`, a followed redirect would resend the call with the daemon +token, possibly to the unchecked `/rpc`; the proxy refuses a checked answer that is a 3xx or reports +`redirected`, but it cannot undo a request your transport already resent. `/health` refuses such an +answer too: the proxy then answers `/health` with HTTP 500 and `ok: false`. + +`upstreamBaseUrl` must use https, or plain http to a loopback host, with or without +`upstreamFetch`, and must not carry a username or password. With your own transport, give it a +logical URL that meets this rule, such as `https://device-host-17.internal`, and route it inside +the transport. For any other URL, the proxy sends nothing upstream and answers every request with +`INVALID_ARGS`. The reason is `proxy_upstream_userinfo` for a username or password, and +`insecure_credential_transport` otherwise: `details.reason` on `/rpc`, and `reason` on every other +route. On transfer routes, the proxy bounds its wait for your transport and response body. It settles on your abort, your `upstreamTimeoutMs`, its 600-second aggregate and its demand-aware response-body @@ -213,7 +222,7 @@ authenticate: async (request) => { | Option | Default | Meaning | | --- | --- | --- | -| `upstreamBaseUrl` | required | Base URL of the daemon's HTTP server. | +| `upstreamBaseUrl` | required | Base URL of the daemon's HTTP server: https, or plain http to loopback. | | `upstreamToken` | required | The daemon's auth token. | | `clientToken` | required without `authenticate` | Token clients must send as their daemon auth token. | | `authenticate` | none | Authenticates each client and names its tenant; replaces `clientToken`. | diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts index ac3e609b69..e0072965c0 100644 --- a/packages/proxy/src/daemon-proxy-cancellation.test.ts +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -53,7 +53,7 @@ function abortObservingUpstream(): { function proxyWith(upstreamFetch: DaemonProxyUpstreamFetch) { return createDaemonProxy({ - upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamBaseUrl: 'https://daemon.internal:4310', upstreamToken: 'daemon-secret', clientToken: 'client-secret', upstreamFetch, @@ -131,7 +131,7 @@ test('a health request handled by two proxies at once aborts both upstream probe test('a client leaving the Node adapter mid-response after a garbage collection aborts the upstream request', async () => { const upstreamAborted = signalled(); const server = createDaemonProxyServer({ - upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamBaseUrl: 'https://daemon.internal:4310', upstreamToken: 'daemon-secret', clientToken: 'client-secret', upstreamFetch: async (request) => { @@ -191,7 +191,7 @@ test('the upstream health probe has its own bound without upstreamTimeoutMs', as test('upstreamTimeoutMs still ends an rpc exchange after a garbage collection', async () => { const upstream = abortObservingUpstream(); const proxy = createDaemonProxy({ - upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamBaseUrl: 'https://daemon.internal:4310', upstreamToken: 'daemon-secret', clientToken: 'client-secret', upstreamFetch: upstream.fetch, @@ -217,7 +217,7 @@ test('aborting the client request after a garbage collection aborts a pending au const authenticateReceived = signalled(); const authenticateAborted = signalled(); const proxy = createDaemonProxy({ - upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamBaseUrl: 'https://daemon.internal:4310', upstreamToken: 'daemon-secret', upstreamFetch: async () => Response.json({}), authenticate: (request) => diff --git a/packages/proxy/src/daemon-proxy-checked-rpc.test.ts b/packages/proxy/src/daemon-proxy-checked-rpc.test.ts index 60e76d32f5..8475ff5b72 100644 --- a/packages/proxy/src/daemon-proxy-checked-rpc.test.ts +++ b/packages/proxy/src/daemon-proxy-checked-rpc.test.ts @@ -22,7 +22,7 @@ function recordingUpstream(respond: (request: Request) => Response | Promise { const upstream = recordingUpstream(() => Response.json({})); const proxy = createDaemonProxy({ - upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamBaseUrl: 'https://daemon.internal:4310', upstreamToken: 'daemon-secret', authenticate: () => ({ tenantId: 'tenant-a' }), upstreamFetch: upstream.fetch, diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts new file mode 100644 index 0000000000..527731fe7e --- /dev/null +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -0,0 +1,197 @@ +// The upstream daemon token never leaves the proxy in cleartext: not to a plain-http upstream off +// loopback, whatever transport carries it, and not to wherever an upstream redirect points. + +import { afterEach, expect, test, vi } from 'vitest'; +import http from 'node:http'; +import https from 'node:https'; +import type { AddressInfo } from 'node:net'; +import { + DAEMON_HTTP_RPC_PROTOCOL_HEADER, + DAEMON_RPC_PROTOCOL_VERSION, +} from '@agent-device/contracts/daemon-http'; +import { createDaemonProxy, type DaemonProxyUpstreamFetch } from './daemon-proxy.ts'; + +async function listenLocal(server: http.Server): Promise { + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + return (server.address() as AddressInfo).port; +} + +async function closeLocal(server: http.Server): Promise { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); +} + +const servers: http.Server[] = []; +afterEach(async () => { + vi.restoreAllMocks(); + await Promise.all(servers.splice(0).map((server) => closeLocal(server))); +}); + +async function serve(handler: http.RequestListener): Promise { + const server = http.createServer(handler); + servers.push(server); + return `http://127.0.0.1:${await listenLocal(server)}`; +} + +const rpc = (route = 'rpc', headers: Record = {}) => + new Request(`https://gateway.example.test/agent-device/${route}`, { + method: 'POST', + headers: { + authorization: 'Bearer client-secret', + 'content-type': 'application/json', + ...headers, + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent_device.command', params: {} }), + }); +const checkedRpc = () => + rpc('rpc/checked', { [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: String(DAEMON_RPC_PROTOCOL_VERSION) }); + +test.each([ + ['the default transport', 'plain http off loopback', 'http://daemon.invalid:4310', undefined], + ['a custom transport', 'plain http off loopback', 'http://daemon.invalid:4310', 'custom'], + ['the default transport', 'a URL without a host', 'http://', undefined], + ['a custom transport', 'a URL without a host', 'http://', 'custom'], + [ + 'the default transport', + 'a URL with a username and password', + 'https://operator:hunter2@daemon.example.test', + undefined, + ], + ['a custom transport', 'a URL with a username', 'https://operator@daemon.example.test', 'custom'], + [ + 'the default transport', + 'a loopback URL with a username', + 'http://operator@127.0.0.1:4310', + undefined, + ], +] as const)( + '%s never sends the upstream token to %s', + async (_label, _destination, upstreamBaseUrl, transport) => { + const sent: unknown[] = []; + for (const spy of [ + vi.spyOn(globalThis, 'fetch'), + vi.spyOn(http, 'request'), + vi.spyOn(https, 'request'), + ]) { + spy.mockImplementation((input: unknown) => { + sent.push(input); + throw new Error('nothing may be sent'); + }); + } + const upstreamFetch: DaemonProxyUpstreamFetch | undefined = + transport === 'custom' + ? async (request) => { + sent.push(request); + return Response.json({}); + } + : undefined; + const proxy = createDaemonProxy({ + upstreamBaseUrl, + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + ...(upstreamFetch ? { upstreamFetch } : {}), + }); + + for (const request of [ + rpc(), + checkedRpc(), + new Request('https://gateway.example.test/agent-device/health'), + new Request('https://gateway.example.test/agent-device/artifacts/build', { + headers: { authorization: 'Bearer client-secret' }, + }), + new Request( + 'https://gateway.example.test/agent-device/sessions/default/requests/ref-1/diagnostics', + { headers: { authorization: 'Bearer client-secret' } }, + ), + rpc('upload/preflight'), + ]) { + const response = await proxy.handle(request); + expect(response.status, request.url).toBe(400); + const refusal = await response.text(); + expect(refusal, request.url).toContain('Proxy upstreamBaseUrl'); + expect(refusal, request.url).not.toMatch(/operator|hunter2|daemon\.(invalid|example)/); + const body = JSON.parse(refusal) as { + reason?: string; + error?: { data?: { details?: { reason?: string } } }; + }; + expect(body.error?.data?.details?.reason ?? body.reason, request.url).toBe( + upstreamBaseUrl.includes('@') ? 'proxy_upstream_userinfo' : 'insecure_credential_transport', + ); + } + expect(sent).toEqual([]); + }, +); + +test('the default transports relay an upstream redirect and never follow it', async () => { + const reached: string[] = []; + const target = await serve((req, res) => { + reached.push(`${req.method} ${req.url}`); + res.end('{}'); + }); + const daemon = await serve((req, res) => { + req.resume(); + res.writeHead(307, { location: `${target}/redirected` }).end(); + }); + const proxy = createDaemonProxy({ + upstreamBaseUrl: daemon, + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + }); + const read = (path: string) => + new Request(`https://gateway.example.test/agent-device/${path}`, { + headers: { authorization: 'Bearer client-secret' }, + }); + + expect((await proxy.handle(rpc())).status).toBe(307); + expect((await proxy.handle(checkedRpc())).status).toBe(500); + expect((await proxy.handle(read('artifacts/build'))).status).toBe(307); + expect((await proxy.handle(read('health'))).status).toBe(500); + + expect(reached).toEqual([]); +}); + +test('a relayed upstream redirect keeps its status and carries no Location', async () => { + const location = 'https://daemon.example.test/artifacts/other?token=daemon-secret'; + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'https://daemon.example.test', + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + upstreamFetch: async (request) => { + expect(request.redirect).toBe('manual'); + return new Response(null, { status: 307, headers: { location } }); + }, + }); + + for (const request of [ + rpc(), + new Request('https://gateway.example.test/agent-device/artifacts/build', { + headers: { authorization: 'Bearer client-secret' }, + }), + ]) { + const response = await proxy.handle(request); + expect(response.status, request.url).toBe(307); + expect(response.headers.get('location'), request.url).toBe(null); + } +}); + +test.each([ + ['a 302 whose body claims health', () => Response.json({ ok: true }, { status: 302 })], + [ + 'an answer its transport reached through a redirect', + () => Object.defineProperty(Response.json({ ok: true }), 'redirected', { value: true }), + ], +])('an upstream health answer that is %s reports the proxy unhealthy', async (_label, answer) => { + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'https://daemon.example.test', + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + upstreamFetch: async () => answer(), + }); + + const response = await proxy.handle( + new Request('https://gateway.example.test/agent-device/health'), + ); + + expect(response.status).toBe(500); + expect(await response.json()).toMatchObject({ ok: false, code: 'COMMAND_FAILED' }); +}); diff --git a/packages/proxy/src/daemon-proxy-transfer-loading.test.ts b/packages/proxy/src/daemon-proxy-transfer-loading.test.ts index d2df471d0f..1a476f0aac 100644 --- a/packages/proxy/src/daemon-proxy-transfer-loading.test.ts +++ b/packages/proxy/src/daemon-proxy-transfer-loading.test.ts @@ -2,7 +2,7 @@ import { expect, onTestFinished, test, vi } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; const options = { - upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamBaseUrl: 'https://daemon.internal:4310', upstreamToken: 'daemon-secret', clientToken: 'client-secret', }; diff --git a/packages/proxy/src/daemon-proxy-transfer.test.ts b/packages/proxy/src/daemon-proxy-transfer.test.ts index b6546cbb52..cf1a170978 100644 --- a/packages/proxy/src/daemon-proxy-transfer.test.ts +++ b/packages/proxy/src/daemon-proxy-transfer.test.ts @@ -11,7 +11,7 @@ import { } from './daemon-proxy.ts'; const options = { - upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamBaseUrl: 'https://daemon.internal:4310', upstreamToken: 'daemon-secret', clientToken: 'client-secret', }; @@ -240,7 +240,7 @@ test('a custom transport receives every route family including transfers', async if (path === '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/upload/preflight') return Response.json({ uploadId: 'ticket', - upload: { url: 'http://daemon.internal:4310/upload/direct/ticket' }, + upload: { url: 'https://daemon.internal:4310/upload/direct/ticket' }, }); if (path === '/rpc') return Response.json({ jsonrpc: '2.0', id: 1, result: { ok: true } }); return new Response('custom answer'); diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index da03369607..a9ed0984ee 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -25,7 +25,7 @@ function recordingUpstream(respond: (request: Request) => Response | Promise Response.json({ jsonrpc: '2.0', id: 4, result: {} }), @@ -268,7 +268,7 @@ test('an unsupported route answers a bare 404 without reaching the daemon', asyn function proxyAuthenticatingWith(upstreamFetch: DaemonProxyUpstreamFetch) { const seen: Request[] = []; const proxy = createDaemonProxy({ - upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamBaseUrl: 'https://daemon.internal:4310', upstreamToken: 'daemon-secret', upstreamFetch, authenticate: async (request) => { @@ -393,7 +393,7 @@ function daemonTicketUpstream() { /** Admits `alice-key` from any of four credential headers, naming its own upload headers. */ function proxyAuthenticatingByAnyCredential(upstreamFetch: DaemonProxyUpstreamFetch) { return createDaemonProxy({ - upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamBaseUrl: 'https://daemon.internal:4310', upstreamToken: DAEMON_TOKEN, upstreamFetch, authenticate: (request): DaemonProxyAuthenticatedClient | null => { @@ -488,7 +488,7 @@ test('with authenticate, a custom upload header passes authenticate on the direc test('an authenticate that never reads headers still yields a working ticket', async () => { const upstream = daemonTicketUpstream(); const proxy = createDaemonProxy({ - upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamBaseUrl: 'https://daemon.internal:4310', upstreamToken: DAEMON_TOKEN, upstreamFetch: upstream.fetch, authenticate: () => ({ tenantId: 'alice' }), @@ -581,7 +581,7 @@ test('without authenticate, the tenant a client declares is forwarded unchanged' test('authenticate returning a tenantId the daemon rejects refuses the request before the daemon', async () => { const upstream = recordingUpstream(() => Response.json({ ok: true })); const proxy = createDaemonProxy({ - upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamBaseUrl: 'https://daemon.internal:4310', upstreamToken: 'daemon-secret', upstreamFetch: upstream.fetch, authenticate: () => ({ tenantId: 'alice@example.com' }), @@ -604,7 +604,7 @@ test.each(['http, https', 'HTTPS', 'http://evil.example/path?'])( ok: true, uploadId: 'abc', upload: { - url: 'http://daemon:4310/upload/direct/abc?part=1', + url: 'https://daemon:4310/upload/direct/abc?part=1', headers: { authorization: 'Bearer upstream-secret', 'content-type': 'application/zip' }, }, }), @@ -639,11 +639,11 @@ test('fixed public origin rewrites a prefixed ticket and preserves its query', a const upstream = recordingUpstream(() => Response.json({ uploadId: 'abc', - upload: { url: 'http://daemon/upload/direct/abc?part=1', headers: {} }, + upload: { url: 'https://daemon/upload/direct/abc?part=1', headers: {} }, }), ); const proxy = createDaemonProxy({ - upstreamBaseUrl: 'http://daemon', + upstreamBaseUrl: 'https://daemon', upstreamToken: 'secret', clientToken: 'client', publicOrigin: 'https://PUBLIC.example:8443/', @@ -677,7 +677,7 @@ test.each([ ])('rejects invalid public origin %s at construction', (publicOrigin) => { expect(() => createDaemonProxy({ - upstreamBaseUrl: 'http://daemon', + upstreamBaseUrl: 'http://127.0.0.1:4310', upstreamToken: 'secret', clientToken: 'client', publicOrigin, @@ -713,7 +713,7 @@ test.each([ Response.json({ ok: true, uploadId, - upload: { url: `http://daemon${path}`, headers: buildDaemonHttpAuthHeaders(DAEMON_TOKEN) }, + upload: { url: `https://daemon${path}`, headers: buildDaemonHttpAuthHeaders(DAEMON_TOKEN) }, }), ); const response = await proxyWith(upstream.fetch).handle( @@ -739,7 +739,7 @@ test.each([400, 401, 503])( code: 'UPLOAD_FAILED', uploadId: 'abc', upload: { - url: 'http://daemon/upload/direct/abc', + url: 'https://daemon/upload/direct/abc', headers: buildDaemonHttpAuthHeaders(DAEMON_TOKEN), }, }, diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 5e1bb8d15e..959cfcf7aa 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -33,12 +33,13 @@ import { * Carries one request to the upstream daemon and resolves with its response. Without `upstreamFetch` * the proxy reaches the daemon over `node:http(s)` on artifact transfer routes and over the global * `fetch` on `/rpc`, health and diagnostics. Supply your own to reach the daemon over another - * transport, such as a WebSocket tunnel. Abort the exchange when `request.signal` aborts. + * transport, such as a WebSocket tunnel. Abort the exchange when `request.signal` aborts. Every + * request carries `redirect: 'manual'`: honor it by returning a 3xx as the response and never + * following it, because the request carries the upstream token. The proxy relays a 3xx status to + * its client without `Location`. On the checked RPC route and the health probe it refuses a 3xx or + * `redirected` answer instead, but it cannot undo a resend the transport already made. * * A custom transport owns its phase guarantees and must observe `request.signal` on every route. - * It must also honor `request.redirect`: the checked RPC route sets `'error'`, so the transport must - * never follow a redirect there. The proxy refuses a checked answer that is a redirect or that - * reports `redirected`, but it cannot undo a resend the transport already made. * On transfer routes, the proxy bounds its own response and body waits, even if the transport * ignores cancellation. It cannot forcibly join work started by that transport. */ @@ -65,7 +66,12 @@ export type DaemonProxyAuthenticate = ( ) => Promise | DaemonProxyAuthenticatedClient | null; export type DaemonProxyOptions = { - /** Base URL of the upstream agent-device daemon HTTP server. */ + /** + * Base URL of the upstream agent-device daemon HTTP server. It must use https, or plain http to + * loopback, because every upstream request carries `upstreamToken`, and must not carry a username + * or password; with `upstreamFetch` it is the logical URL your transport routes. Any other URL + * refuses every request before it is sent. + */ upstreamBaseUrl: string; /** Auth token of the upstream daemon. Never leaves the proxy. */ upstreamToken: string; @@ -117,6 +123,8 @@ type NormalizedProxyOptions = { authenticate: DaemonProxyAuthenticate | undefined; maxRpcBodyBytes: number; upstreamTimeoutMs: number | undefined; + /** Refuses an upstream base URL the token may not go to. Runs before any URL is built on it. */ + admitUpstream: () => Promise; upstreamFetch: DaemonProxyUpstreamFetch; upstreamTransport: (route: string, request: Request) => Promise; }; @@ -358,13 +366,23 @@ async function readUpstreamHealth( request: Request, options: NormalizedProxyOptions, ): Promise { + // The bound starts with the probe, so it covers admission too. + const signal = AbortSignal.any([request.signal, AbortSignal.timeout(UPSTREAM_HEALTH_TIMEOUT_MS)]); + await options.admitUpstream(); const response = await options.upstreamFetch( forwardedRequest(request, buildDaemonHttpUrl(options.upstreamBaseUrl, 'health'), { method: 'GET', headers: buildUpstreamHeaders(new Headers(), options.upstreamToken, '/health'), - signal: AbortSignal.any([request.signal, AbortSignal.timeout(UPSTREAM_HEALTH_TIMEOUT_MS)]), + signal, }), ); + // A redirect the proxy did not follow, or one a custom transport did, is not the daemon's health. + if (response.redirected || (response.status >= 300 && response.status < 400)) { + await response.body?.cancel(); + throw new AppError('COMMAND_FAILED', 'The daemon answered the health check with a redirect', { + hint: 'The proxy never follows a redirect. Point upstreamBaseUrl at the daemon itself.', + }); + } const text = await response.text(); try { return text ? JSON.parse(text) : { ok: response.ok, status: response.status }; @@ -381,6 +399,7 @@ async function forwardProxyRequest(params: { caller: ProxyCaller; }): Promise { const { request, route, options, rpcBody, caller } = params; + await options.admitUpstream(); const body = resolveUpstreamBody(request, route, rpcBody, options.upstreamToken, caller.tenantId); const checked = route === DAEMON_HTTP_CHECKED_RPC_ROUTE; const upstreamResponse = await options.upstreamTransport( @@ -389,8 +408,6 @@ async function forwardProxyRequest(params: { method: request.method, headers: buildUpstreamHeaders(request.headers, options.upstreamToken, route, caller.tenantId), signal: upstreamSignal(request, options), - // A redirect would resend the call with the daemon token, possibly to unchecked `/rpc`. - ...(checked ? { redirect: 'error' as const } : {}), ...(body ? { body, duplex: 'half' as const } : {}), }), ); @@ -428,9 +445,12 @@ function keepAliveWith(owner: object, request: Request): Request { return request; } -/** Builds a request for `owner` to send on, kept reachable for as long as `owner` is. */ +/** + * Builds an upstream request for `owner`. It never follows a redirect: a followed one would resend + * the upstream token, on the checked route possibly to the unchecked `/rpc`. + */ function forwardedRequest(owner: Request, url: string | URL, init: RequestInit): Request { - return keepAliveWith(owner, new Request(url, init)); + return keepAliveWith(owner, new Request(url, { ...init, redirect: 'manual' })); } function upstreamSignal(request: Request, options: NormalizedProxyOptions): AbortSignal { @@ -569,11 +589,17 @@ function rewriteUploadDirectUrl( } function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOptions { - const upstreamBaseUrl = normalizeBaseUrl(options.upstreamBaseUrl, 'upstreamBaseUrl'); + const upstreamBaseUrl = normalizeUpstreamBaseUrl(options.upstreamBaseUrl); const upstreamToken = normalizeToken(options.upstreamToken, 'upstreamToken'); const clientToken = options.authenticate ? undefined : normalizeToken(options.clientToken ?? '', 'clientToken'); + // Loaded on the first upstream exchange, never at module scope: the proxy entry stays lean. + let upstreamAdmission: Promise | undefined; + const admitUpstream = () => + (upstreamAdmission ??= import('./upstream-admission.ts').then(({ assertAdmittedUpstream }) => { + assertAdmittedUpstream(upstreamBaseUrl); + })); const upstreamFetch = options.upstreamFetch ?? ((request) => fetch(request)); const customUpstreamFetch = options.upstreamFetch; return { @@ -587,6 +613,7 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti authenticate: options.authenticate, maxRpcBodyBytes: options.maxRpcBodyBytes ?? DEFAULT_MAX_RPC_BODY_BYTES, upstreamTimeoutMs: options.upstreamTimeoutMs, + admitUpstream, upstreamFetch, upstreamTransport: async (route, request) => { if (!isTransferRoute(route, request.method)) return upstreamFetch(request); @@ -602,16 +629,12 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti }; } -function normalizeBaseUrl(value: string, label: string): string { - try { - const parsed = new URL(value); - if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { - throw new Error('unsupported protocol'); - } - return parsed.toString().replace(/\/+$/, ''); - } catch (error) { - throw new AppError('INVALID_ARGS', `Invalid ${label}`, { [label]: value }, error); - } +/** + * A URL that does not parse stays as given and never throws here: `admitUpstream` refuses it on + * every request, as it refuses any other URL the token may not go to. + */ +function normalizeUpstreamBaseUrl(value: string): string { + return URL.parse(value)?.toString().replace(/\/+$/, '') ?? value; } function normalizeToken(value: string, label: string): string { @@ -954,12 +977,14 @@ async function proxyErrorResponse(error: unknown, request: Request): Promise { let calls = 0; const server = createDaemonProxyServer({ - upstreamBaseUrl: 'http://daemon', + upstreamBaseUrl: 'https://daemon', upstreamToken: 'daemon-secret', clientToken: 'client-secret', publicOrigin, @@ -158,7 +158,7 @@ test.each([undefined, 'https://public.example:8443'])( return Response.json({ uploadId: 'id', upload: { - url: 'http://daemon/upload/direct/id?part=1', + url: 'https://daemon/upload/direct/id?part=1', headers: { authorization: 'Bearer daemon-secret' }, }, }); diff --git a/packages/proxy/src/upstream-admission.ts b/packages/proxy/src/upstream-admission.ts new file mode 100644 index 0000000000..4d0dfc7114 --- /dev/null +++ b/packages/proxy/src/upstream-admission.ts @@ -0,0 +1,44 @@ +import { + assertSecureCredentialTransport, + isCredentialTransportRefusal, +} from '@agent-device/contracts/credential-transport'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; + +// Whether the upstream token may go to the configured daemon. Loaded with the first upstream +// exchange, never at module scope. + +const UPSTREAM_ADMISSION_REASONS = { + // The proxy's `upstreamBaseUrl` carries a username or password. The upstream credential is + // `upstreamToken` alone, and a request cannot be built from such a URL. + userinfo: { reason: 'proxy_upstream_userinfo' }, +} as const satisfies ReasonTable<'proxy'>; + +/** Refuses every upstream base URL the proxy must not send to. The refusal never quotes it. */ +export function assertAdmittedUpstream(upstreamBaseUrl: string): void { + // Checked first, so that a username or password gets this refusal whatever the scheme. + const upstream = URL.parse(upstreamBaseUrl); + if (!upstream?.username && !upstream?.password) { + assertSecureCredentialTransport(upstreamBaseUrl, 'Proxy upstreamBaseUrl'); + return; + } + throw new AppError( + 'INVALID_ARGS', + 'Proxy upstreamBaseUrl must not carry a username or password.', + { + reason: UPSTREAM_ADMISSION_REASONS.userinfo.reason, + hint: 'Pass the daemon credential as upstreamToken, and remove it from the URL.', + }, + ); +} + +/** + * The reason an answer outside `/rpc` names when the upstream may not receive the token: that + * reason alone, never the destination or other error details. + */ +export function admissionWireDetails(error: unknown): { reason?: string } { + if (!(error instanceof AppError)) return {}; + const reason = error.details?.reason as string | undefined; + const refused = + isCredentialTransportRefusal(error) || reason === UPSTREAM_ADMISSION_REASONS.userinfo.reason; + return refused ? { reason } : {}; +} diff --git a/packages/react-native/src/companion/client-companion-local-relay.ts b/packages/react-native/src/companion/client-companion-local-relay.ts new file mode 100644 index 0000000000..492763108e --- /dev/null +++ b/packages/react-native/src/companion/client-companion-local-relay.ts @@ -0,0 +1,39 @@ +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; +import { AppError } from '@agent-device/kernel/errors'; +import { normalizeBaseUrl } from '../metro/base-url.ts'; + +// Where the companion tunnel sends the requests and sockets a bridge relays to the local dev server. + +/** The relayed request headers that carry a credential. */ +const CREDENTIAL_HEADERS = [ + 'authorization', + 'proxy-authorization', + 'cookie', + 'x-agent-device-token', +]; + +/** The URL a relayed request goes to: its path resolved on the local base, on that origin only. */ +export function relayTarget(localBaseUrl: string, requestPath: string): URL { + const base = new URL(`${normalizeBaseUrl(localBaseUrl)}/`); + const target = URL.parse(requestPath, base); + if (!target || target.origin !== base.origin) { + throw new AppError( + 'INVALID_ARGS', + 'The Metro companion refuses a relayed path that leaves the local base URL.', + ); + } + return target; +} + +/** + * Sends one relayed request. One that carries a known credential header meets the credential + * transport rule. A redirect goes back to the bridge as the answer: `fetch` would resend any + * custom header to another origin, and the relay cannot tell which ones are secret. + */ +export async function fetchRelayedRequest(target: URL, init: RequestInit): Promise { + const headers = new Headers(init.headers); + if (CREDENTIAL_HEADERS.some((name) => headers.has(name))) { + assertSecureCredentialTransport(target, 'Metro companion local base URL'); + } + return await fetch(target, { ...init, redirect: 'manual' }); +} diff --git a/packages/react-native/src/companion/client-companion-tunnel-worker-credential-transport.test.ts b/packages/react-native/src/companion/client-companion-tunnel-worker-credential-transport.test.ts new file mode 100644 index 0000000000..682a69c89f --- /dev/null +++ b/packages/react-native/src/companion/client-companion-tunnel-worker-credential-transport.test.ts @@ -0,0 +1,316 @@ +// The companion's bearer token, its bridge socket URL and relayed credentials never go in cleartext +// to a destination off loopback. + +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import fs from 'node:fs'; +import http from 'node:http'; +import net, { type AddressInfo } from 'node:net'; +import path from 'node:path'; +import type { Duplex } from 'node:stream'; +import { afterEach, test, vi } from 'vitest'; +import { isCredentialTransportRefusal } from '@agent-device/contracts/credential-transport'; +import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import { + ENV_COMPANION_TUNNEL_BEARER_TOKEN, + ENV_COMPANION_TUNNEL_LOCAL_BASE_URL, + ENV_COMPANION_TUNNEL_REGISTER_PATH, + ENV_COMPANION_TUNNEL_SCOPE_LEASE_ID, + ENV_COMPANION_TUNNEL_SCOPE_RUN_ID, + ENV_COMPANION_TUNNEL_SCOPE_TENANT_ID, + ENV_COMPANION_TUNNEL_SERVER_BASE_URL, + METRO_COMPANION_RUN_ARG, +} from './client-companion-tunnel-contract.ts'; +import { + acceptWebSocketUpgrade, + attachWebSocketFrameParser, + encodeTextFrame, +} from './client-companion-tunnel-worker.fixtures.ts'; +import { runCompanionTunnelWorker } from './client-companion-tunnel-worker.ts'; + +const REGISTER_PATH = '/api/metro/companion/register'; +const UNREGISTER_PATH = '/api/metro/companion/unregister'; + +const cleanupTasks: Array<() => Promise> = []; + +afterEach(async () => { + while (cleanupTasks.length > 0) await cleanupTasks.pop()!(); + vi.restoreAllMocks(); +}); + +/** Runs the worker in process; `done` settles when it exits, and `stop` ends its lease first. */ +function startWorker(serverBaseUrl: string, localBaseUrl = 'http://127.0.0.1:1') { + const statePath = path.join(mkdtempForTestSync('metro-companion-transport-'), 'state.json'); + fs.writeFileSync(statePath, '{}'); + const done = runCompanionTunnelWorker( + { + serverBaseUrl, + bearerToken: 'test-token', + localBaseUrl, + registerPath: REGISTER_PATH, + unregisterPath: UNREGISTER_PATH, + bridgeScope: { tenantId: 'tenant-1', runId: 'run-1', leaseId: 'lease-1' }, + statePath, + }, + { leaseCheckIntervalMs: 25, reconnectDelayMs: 25 }, + ); + const stop = async () => { + fs.rmSync(statePath, { force: true }); + await done.catch(() => undefined); + }; + cleanupTasks.push(stop); + return { done, stop }; +} + +/** + * A socket taken from an HTTP server on `upgrade` has no `error` listener left, and a peer that + * dies with it open can reset it. These cases judge what arrived, not how it closed. + */ +function tolerateReset(socket: Duplex): void { + socket.on('error', () => undefined); +} + +/** + * A loopback bridge whose registration answers `wsUrl(port)`, recording what reaches it and what + * the companion sends on the socket. + */ +async function listenBridge(wsUrl: (port: number) => string) { + const received: string[] = []; + let upgrade!: (socket: Duplex) => void; + const upgraded = new Promise((resolve) => (upgrade = resolve)); + let port = 0; + let socketRef: Duplex | undefined; + const replies: Array> = []; + const server = http.createServer((req, res) => { + received.push(`${req.url} ${req.headers.authorization}`); + req.resume(); + res.end(JSON.stringify({ ok: true, data: { ws_url: wsUrl(port) } })); + }); + server.on('upgrade', (req, socket) => { + tolerateReset(socket); + received.push(`UPGRADE ${req.url}`); + socketRef = socket; + if (!acceptWebSocketUpgrade(req, socket)) return; + attachWebSocketFrameParser(socket, (text) => replies.push(JSON.parse(text))); + upgrade(socket); + }); + cleanupTasks.push(() => closeLoopbackServer(server)); + cleanupTasks.push(async () => socketRef?.destroy()); + port = await listenOnLoopback(server); + /** Sends one tunnel message and waits for the companion's answer to it. */ + const relay = async (message: Record) => { + const answered = replies.length; + (await upgraded).write(encodeTextFrame(JSON.stringify(message))); + await vi.waitFor(() => assert.ok(replies.length > answered)); + return replies[answered]!; + }; + return { origin: `http://127.0.0.1:${port}`, received, upgraded, relay }; +} + +const registered = `${REGISTER_PATH} Bearer test-token`; +const unregistered = `${UNREGISTER_PATH} Bearer test-token`; + +// A base without a host gains one from the appended path: `https://` would reach `https://api/...`. +test.for(['http://bridge.invalid', 'https://'])( + 'the worker never sends its bearer token to %s and exits', + async (serverBaseUrl) => { + const send = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValue(new Response(null, { status: 401 })); + + await assert.rejects(startWorker(serverBaseUrl).done, isCredentialTransportRefusal); + + assert.equal(send.mock.calls.length, 0); + }, +); + +/** A TCP listener that records every connection, whatever protocol its caller speaks. */ +async function listenSink() { + const connections: unknown[] = []; + const server = net.createServer((socket) => { + connections.push(socket.remoteAddress); + socket.destroy(); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + cleanupTasks.push(() => new Promise((resolve) => server.close(resolve))); + return { port: (server.address() as AddressInfo).port, connections }; +} + +// `0.0.0.0` reaches this machine's listener and is not a loopback address, so a socket opened +// without the check would show up at the sink. So would `http` on loopback, which a `WebSocket` +// accepts. +test.for([ + (port: number) => `ws://0.0.0.0:${port}/bridge?ticket=secret`, + (port: number) => `http://127.0.0.1:${port}/bridge?ticket=secret`, +])('the worker refuses any socket but wss or loopback ws before it opens', async (wsUrl) => { + const sink = await listenSink(); + const bridge = await listenBridge(() => wsUrl(sink.port)); + + await assert.rejects(startWorker(bridge.origin).done, isCredentialTransportRefusal); + + assert.deepEqual(sink.connections, []); + assert.deepEqual(bridge.received, [registered, unregistered]); +}); + +test('a refused socket URL ends the worker process as failed', async () => { + const bridge = await listenBridge(() => 'ws://0.0.0.0:1/bridge'); + const worker = spawn( + process.execPath, + [ + '--experimental-strip-types', + path.join(import.meta.dirname, 'companion-tunnel.ts'), + METRO_COMPANION_RUN_ARG, + ], + { + env: { + ...process.env, + [ENV_COMPANION_TUNNEL_SERVER_BASE_URL]: bridge.origin, + [ENV_COMPANION_TUNNEL_BEARER_TOKEN]: 'test-token', + [ENV_COMPANION_TUNNEL_LOCAL_BASE_URL]: 'http://127.0.0.1:1', + [ENV_COMPANION_TUNNEL_REGISTER_PATH]: REGISTER_PATH, + [ENV_COMPANION_TUNNEL_SCOPE_TENANT_ID]: 'tenant-1', + [ENV_COMPANION_TUNNEL_SCOPE_RUN_ID]: 'run-1', + [ENV_COMPANION_TUNNEL_SCOPE_LEASE_ID]: 'lease-1', + }, + stdio: 'ignore', + }, + ); + const exited = once(worker, 'exit'); + cleanupTasks.push(async () => { + worker.kill('SIGKILL'); + await exited; + }); + + const [exitCode] = await exited; + + assert.equal(exitCode, 1); + assert.deepEqual(bridge.received, [registered]); +}); + +/** A server recording the credential headers of each request that reaches it. */ +async function listenLocalServer(location?: () => string, redirectPath = '/redirect') { + const received: string[] = []; + const server = http.createServer((req, res) => { + const { authorization, cookie, 'x-app-secret': custom } = req.headers; + received.push(`${req.url} ${authorization ?? cookie ?? custom ?? '-'}`); + req.resume(); + if (location && req.url === redirectPath) res.writeHead(307, { location: location() }).end(); + else res.end('bundle'); + }); + cleanupTasks.push(() => closeLoopbackServer(server)); + const port = await listenOnLoopback(server); + return { port, origin: `http://127.0.0.1:${port}`, received }; +} + +/** Starts a worker for `localBaseUrl` and returns the bridge that relays to it. */ +async function relayingBridge(localBaseUrl: string) { + const bridge = await listenBridge((port) => `ws://127.0.0.1:${port}/bridge`); + startWorker(bridge.origin, localBaseUrl); + await bridge.upgraded; + return bridge; +} + +const httpRequest = (path: string, headers: Record = {}) => ({ + type: 'http-request', + requestId: 'request-1', + method: 'GET', + path, + headers, +}); + +test('a relayed path that leaves the local base URL is refused, over HTTP and sockets', async () => { + const local = await listenLocalServer(); + const other = await listenLocalServer(); + const bridge = await relayingBridge(local.origin); + + for (const path of [`${other.origin}/steal`, `//127.0.0.1:${other.port}/steal`]) { + const answer = await bridge.relay(httpRequest(path, { authorization: 'Bearer app' })); + assert.equal(answer.type, 'http-error', path); + const opened = await bridge.relay({ type: 'ws-open', streamId: 'stream-1', path }); + assert.equal(opened.success, false, path); + } + + assert.deepEqual([local.received, other.received], [[], []]); +}); + +test('a relayed absolute path on the local base origin is served', async () => { + const local = await listenLocalServer(); + const bridge = await relayingBridge(local.origin); + + const answer = await bridge.relay(httpRequest(`${local.origin}/index.bundle`)); + + assert.equal(answer.status, 200); + assert.deepEqual(local.received, ['/index.bundle -']); +}); + +test.each([ + ['authorization', 'Bearer app'], + ['cookie', 'session=app'], +])('a relayed %s never goes over plain http off loopback', async (name, value) => { + const local = await listenLocalServer(); + // Reaches this machine's listener without being a loopback address, as a LAN dev server would. + const bridge = await relayingBridge(`http://0.0.0.0:${local.port}`); + + const refusedAnswer = await bridge.relay(httpRequest('/secret', { [name]: value })); + const openAnswer = await bridge.relay(httpRequest('/index.bundle')); + + assert.equal(refusedAnswer.type, 'http-error'); + assert.equal(openAnswer.status, 200); + assert.deepEqual(local.received, ['/index.bundle -']); +}); + +test.each(['same origin', 'another origin'])( + 'a relayed redirect to the %s goes back to the bridge unfollowed', + async (target) => { + const other = await listenLocalServer(); + const location = () => + target === 'same origin' ? '/redirected' : `${other.origin}/redirected`; + const local = await listenLocalServer(location); + const bridge = await relayingBridge(local.origin); + + // No list names this header, and `fetch` would carry it to any origin it followed to. + const answer = await bridge.relay(httpRequest('/redirect', { 'x-app-secret': 'app' })); + + assert.equal(answer.status, 307); + assert.equal((answer.headers as Record).location, location()); + assert.deepEqual(local.received, ['/redirect app']); + assert.deepEqual(other.received, []); + }, +); + +test('a relayed socket never opens over plain ws off loopback', async () => { + const sink = await listenSink(); + // Reaches this machine's listener without being a loopback address, as a LAN dev server would. + const bridge = await relayingBridge(`http://0.0.0.0:${sink.port}`); + + const opened = await bridge.relay({ + type: 'ws-open', + streamId: 'stream-1', + path: '/hot?ticket=secret', + }); + + assert.equal(opened.success, false); + assert.match(String(opened.error), /^Metro companion local base URL must use wss/); + assert.deepEqual(sink.connections, []); +}); + +test('a redirected registration fails without reaching the other origin', async () => { + const received: Array = []; + const other = http.createServer((req, res) => { + received.push(req.headers.authorization); + req.resume(); + res.writeHead(401).end(JSON.stringify({ ok: false, error: { code: 'UNAUTHORIZED' } })); + }); + cleanupTasks.push(() => closeLoopbackServer(other)); + const otherPort = await listenOnLoopback(other); + const bridge = await listenLocalServer( + () => `http://127.0.0.1:${otherPort}${REGISTER_PATH}`, + REGISTER_PATH, + ); + + await startWorker(bridge.origin).done; + + assert.deepEqual(bridge.received, [registered]); + assert.deepEqual(received, []); +}); diff --git a/packages/react-native/src/companion/client-companion-tunnel-worker.ts b/packages/react-native/src/companion/client-companion-tunnel-worker.ts index 13cbd01467..a09ec1e783 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.ts @@ -23,8 +23,15 @@ import type { MetroTunnelResponseMessage, } from './metro-tunnel-messages.ts'; import { normalizeBaseUrl } from '../metro/base-url.ts'; +import { + assertSecureCredentialSocket, + assertSecureCredentialTransport, + isCredentialTransportRefusal, +} from '@agent-device/contracts/credential-transport'; +import { fetchRelayedRequest, relayTarget } from './client-companion-local-relay.ts'; const COMPANION_REGISTER_TIMEOUT_MS = 5_000; +const BRIDGE_URL_SUBJECT = 'Metro companion bridge URL'; const COMPANION_REGISTER_MAX_RETRY_DELAY_MS = 60_000; export type CompanionTunnelWorkerRuntime = { @@ -81,12 +88,14 @@ async function registerCompanion( options: CompanionTunnelWorkerOptions, ): Promise<{ wsUrl: string }> { const registerPath = resolveRegisterPath(options); + const registerUrl = bearerDestination(options.serverBaseUrl, registerPath); let response: Response; try { - response = await fetch(`${normalizeBaseUrl(options.serverBaseUrl)}${registerPath}`, { + response = await fetch(registerUrl, { method: 'POST', headers: createHeaders(options.serverBaseUrl, options.bearerToken), body: JSON.stringify(buildCompanionPayload(options)), + redirect: 'manual', signal: AbortSignal.timeout(COMPANION_REGISTER_TIMEOUT_MS), }); } catch (error) { @@ -159,6 +168,27 @@ function clampRetryDelay(delayMs: number): number { return Math.max(0, Math.min(COMPANION_REGISTER_MAX_RETRY_DELAY_MS, Math.ceil(delayMs))); } +/** + * The URL a bearer request goes to. The base must be a destination on its own: appending a path can + * give a host to a base without one (`https://` becomes `https://api/...`). + */ +function bearerDestination(serverBaseUrl: string, path: string): URL { + assertSecureCredentialTransport(serverBaseUrl, BRIDGE_URL_SUBJECT); + const url = `${normalizeBaseUrl(serverBaseUrl)}${path}`; + return assertSecureCredentialTransport(url, BRIDGE_URL_SUBJECT); +} + +/** + * Reports a failed attempt and says whether to retry, and after how long if the bridge said. A + * refused destination stays refused, so it is thrown for the worker to fail with. + */ +function reportFailedAttempt(error: unknown): { retry: boolean; retryAfterMs?: number } { + console.error(error instanceof Error ? error.message : String(error)); + if (isCredentialTransportRefusal(error)) throw error; + if (!(error instanceof CompanionRegistrationError)) return { retry: true }; + return { retry: error.retryable, retryAfterMs: error.retryAfterMs }; +} + function nextRetryDelay(currentDelayMs: number): number { return Math.min(currentDelayMs * 2, COMPANION_REGISTER_MAX_RETRY_DELAY_MS); } @@ -167,10 +197,12 @@ async function unregisterCompanion(options: CompanionTunnelWorkerOptions): Promi const unregisterPath = resolveUnregisterPath(options); if (!unregisterPath) return; try { - await fetch(`${normalizeBaseUrl(options.serverBaseUrl)}${unregisterPath}`, { + const unregisterUrl = bearerDestination(options.serverBaseUrl, unregisterPath); + await fetch(unregisterUrl, { method: 'POST', headers: createHeaders(options.serverBaseUrl, options.bearerToken), body: JSON.stringify(buildCompanionPayload(options)), + redirect: 'manual', signal: AbortSignal.timeout(2_000), }); } catch (error) { @@ -196,9 +228,10 @@ async function parseBridgeMessage(event: MessageEvent): Promise { try { - const response = await fetch( - new URL(message.path, `${normalizeBaseUrl(options.localBaseUrl)}/`), - { - method: message.method, - headers: message.headers, - ...(message.bodyBase64 ? { body: Buffer.from(message.bodyBase64, 'base64') } : {}), - }, - ); + const response = await fetchRelayedRequest(relayTarget(options.localBaseUrl, message.path), { + method: message.method, + headers: message.headers, + ...(message.bodyBase64 ? { body: Buffer.from(message.bodyBase64, 'base64') } : {}), + }); const body = Buffer.from(await response.arrayBuffer()); sendJson(bridgeSocket, { type: 'http-response', @@ -314,7 +344,20 @@ async function handleBridgeWebSocketOpen( options: CompanionTunnelWorkerOptions, upstreamSockets: Map, ): Promise { - const upstreamSocket = new WebSocket(toUpstreamWebSocketUrl(options.localBaseUrl, message.path)); + const refuse = (error: unknown) => + sendJson(bridgeSocket, { + type: 'ws-open-result', + streamId: message.streamId, + success: false, + error: error instanceof Error ? error.message : String(error), + }); + let upstreamSocket: WebSocket; + try { + upstreamSocket = new WebSocket(toUpstreamWebSocketUrl(options.localBaseUrl, message.path)); + } catch (error) { + refuse(error); + return; + } upstreamSocket.binaryType = 'arraybuffer'; let opened = false; upstreamSocket.addEventListener('message', (event) => { @@ -363,12 +406,7 @@ async function handleBridgeWebSocketOpen( } catch (error) { upstreamSockets.delete(message.streamId); closeSocketQuietly(upstreamSocket, 1011, 'open failed'); - sendJson(bridgeSocket, { - type: 'ws-open-result', - streamId: message.streamId, - success: false, - error: error instanceof Error ? error.message : String(error), - }); + refuse(error); } } @@ -486,6 +524,8 @@ export async function runCompanionTunnelWorker( registerRetryDelayMs = runtime.reconnectDelayMs ?? COMPANION_TUNNEL_RECONNECT_DELAY_MS; registered = true; activeRegistrationComplete = true; + // The registered URL is what admits this companion to the bridge. + assertSecureCredentialSocket(registration.wsUrl, 'Metro companion bridge socket URL'); if (shutdownRequested || !shouldKeepWorkerRunning(options)) { await unregisterActiveRegistration(); registered = false; @@ -525,12 +565,11 @@ export async function runCompanionTunnelWorker( if (shutdownRequested || !shouldKeepWorkerRunning(options)) { break; } - console.error(error instanceof Error ? error.message : String(error)); - if (error instanceof CompanionRegistrationError && !error.retryable) { + const next = reportFailedAttempt(error); + if (!next.retry) { break; } - retryDelayOverrideMs = - error instanceof CompanionRegistrationError ? error.retryAfterMs : undefined; + retryDelayOverrideMs = next.retryAfterMs; } if (shutdownRequested || !shouldKeepWorkerRunning(options)) { break; diff --git a/packages/react-native/src/index-metro.test.ts b/packages/react-native/src/index-metro.test.ts index 707ad64a52..fa64379eeb 100644 --- a/packages/react-native/src/index-metro.test.ts +++ b/packages/react-native/src/index-metro.test.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import assert from 'node:assert/strict'; import { once } from 'node:events'; import { createHash } from 'node:crypto'; @@ -422,6 +422,31 @@ test('prepareMetroRuntime rejects incomplete proxy configuration', async () => { ); }); +test.for(['http://proxy.example.test', 'http:'])( + 'prepareMetroRuntime never sends a bridge bearer token to %s', + async (proxyBaseUrl) => { + const fetchSpy = vi.spyOn(globalThis, 'fetch'); + try { + await assert.rejects( + () => + prepareMetroRuntime( + { + publicBaseUrl: 'https://sandbox.example.test', + proxyBaseUrl, + env: { AGENT_DEVICE_DAEMON_AUTH_TOKEN: TEST_TOKEN }, + }, + createTestHostEnvironment(), + ), + (error) => + error instanceof AppError && error.details?.reason === 'insecure_credential_transport', + ); + assert.equal(fetchSpy.mock.calls.length, 0); + } finally { + fetchSpy.mockRestore(); + } + }, +); + test('prepareMetroRuntime falls back to daemon auth token for proxy auth', async () => { await assert.rejects( () => diff --git a/packages/react-native/src/metro/client-metro-auto-companion.test.ts b/packages/react-native/src/metro/client-metro-auto-companion.test.ts index 33bbb9aa84..4bc2dd803f 100644 --- a/packages/react-native/src/metro/client-metro-auto-companion.test.ts +++ b/packages/react-native/src/metro/client-metro-auto-companion.test.ts @@ -1,8 +1,14 @@ import { afterEach, test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; +import http from 'node:http'; import path from 'node:path'; -import { mkdtempForTestSync, createTestHostEnvironment } from '@agent-device/test-kit'; +import { + closeLoopbackServer, + createTestHostEnvironment, + listenOnLoopback, + mkdtempForTestSync, +} from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; vi.mock('../companion/client-metro-companion.ts', () => ({ @@ -22,6 +28,7 @@ afterEach(() => { vi.useRealTimers(); vi.clearAllMocks(); vi.restoreAllMocks(); + vi.unstubAllGlobals(); }); test('prepareMetroRuntime starts the local companion only after bridge setup needs it', async () => { @@ -550,3 +557,48 @@ test('prepareMetroRuntime retries malformed retryable bridge responses after com fs.rmSync(tempRoot, { recursive: true, force: true }); } }); + +test('a redirected bridge request fails without reaching the other origin', async () => { + const projectRoot = mkdtempForTestSync('agent-device-metro-redirect-'); + fs.mkdirSync(path.join(projectRoot, 'node_modules'), { recursive: true }); + fs.writeFileSync( + path.join(projectRoot, 'package.json'), + JSON.stringify({ name: 'metro-redirect-test', dependencies: { 'react-native': '0.0.0-test' } }), + ); + const received: Array<[string | undefined, string | undefined]> = []; + const other = http.createServer((req, res) => { + received.push([req.url, req.headers.authorization]); + req.resume(); + res.writeHead(401).end(JSON.stringify({ ok: false })); + }); + const otherPort = await listenOnLoopback(other); + // The local dev server and the bridge in one. + const bridge = http.createServer((req, res) => { + req.resume(); + if (req.url === '/status') return void res.end('packager-status:running'); + received.push([req.url, req.headers.authorization]); + res.writeHead(307, { location: `http://127.0.0.1:${otherPort}/moved` }).end(); + }); + const bridgePort = await listenOnLoopback(bridge); + + try { + await assert.rejects( + prepareMetroRuntime( + { + projectRoot, + proxyBaseUrl: `http://127.0.0.1:${bridgePort}`, + proxyBearerToken: 'shared-token', + bridgeScope: TEST_BRIDGE_SCOPE, + metroPort: bridgePort, + installDependenciesIfNeeded: false, + }, + createTestHostEnvironment(), + ), + ); + + assert.deepEqual(received, [['/api/metro/bridge', 'Bearer shared-token']]); + } finally { + await closeLoopbackServer(bridge); + await closeLoopbackServer(other); + } +}); diff --git a/packages/react-native/src/metro/client-metro.ts b/packages/react-native/src/metro/client-metro.ts index 7790b69585..0d9554901e 100644 --- a/packages/react-native/src/metro/client-metro.ts +++ b/packages/react-native/src/metro/client-metro.ts @@ -21,6 +21,7 @@ import { type ConfirmedProcessStop, } from '@agent-device/host-kit/process'; import { sleep } from '@agent-device/host-kit/retry'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { ensureMetroCompanion } from '../companion/client-metro-companion.ts'; import type { MetroBridgeDescriptor, @@ -458,6 +459,7 @@ async function configureMetroBridge(input: ProxyBridgeRequestOptions): Promise { + for await (const _chunk of req) { + // Drained so the response can be written. + } +} + +test('a ticket over plain http off loopback is never used, whatever carries its credential', async () => { + const localPath = path.join(mkdtempForTestSync('agent-device-upload-ticket-'), 'app.apk'); + fs.writeFileSync(localPath, 'cleartext-ticket'); + const requests: string[] = []; + const server = http.createServer((req, res) => { + requests.push(`${req.method} ${req.url}`); + void readRequestBody(req).then(() => { + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify( + req.url === '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/upload/preflight' + ? { + ok: true, + cacheHit: false, + uploadId: 'cleartext-ticket', + upload: { + url: 'http://ticket.invalid/upload/direct/cleartext-ticket?signature=secret', + headers: {}, + }, + } + : { ok: true, uploadId: 'legacy-upload' }, + ), + ); + }); + }); + const port = await listenOnLoopback(server); + + try { + const uploadId = await uploadArtifact({ + localPath, + baseUrl: `http://127.0.0.1:${port}`, + token: 'agent-device-upload-test-token', + env: process.env, + }); + // One preflight, then the legacy route: no ticket attempt, so no retry preflight either. + assert.equal(uploadId, 'legacy-upload'); + assert.deepEqual(requests, ['POST /upload/preflight', 'POST /upload']); + } finally { + await closeLoopbackServer(server); + } +}); diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index b390acbbf4..69c8e5338a 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -317,7 +317,15 @@ async function requestUploadPreflight(options: { return undefined; } - return parseUploadPreflightResult(result.body); + const preflight = parseUploadPreflightResult(result.body); + if (preflight?.kind !== 'direct-upload') return preflight; + // A ticket can carry a credential in its headers, a cookie, or its query, so every ticket URL + // must be https or plain http to loopback. Any other ticket is not usable, and the upload takes + // the legacy route through the base URL the client already admitted. + const { isSecureCredentialDestination } = + await import('@agent-device/contracts/credential-transport'); + const ticketUrl = URL.parse(preflight.url); + return ticketUrl && isSecureCredentialDestination(ticketUrl) ? preflight : undefined; } async function requestUploadControl( diff --git a/scripts/layering/contracts-exports.snapshot.json b/scripts/layering/contracts-exports.snapshot.json index 085de6563f..eaabe50cbf 100644 --- a/scripts/layering/contracts-exports.snapshot.json +++ b/scripts/layering/contracts-exports.snapshot.json @@ -38,6 +38,7 @@ "@agent-device/contracts/command", "@agent-device/contracts/command-platform-execution", "@agent-device/contracts/command-policy", + "@agent-device/contracts/credential-transport", "@agent-device/contracts/daemon-command-surface", "@agent-device/contracts/daemon-http", "@agent-device/contracts/deploy-result-target", @@ -72,6 +73,7 @@ "@agent-device/contracts/lease-scope", "@agent-device/contracts/local-interactor-operation-set", "@agent-device/contracts/logs-runtime-plan", + "@agent-device/contracts/loopback-host", "@agent-device/contracts/managed-web-backend", "@agent-device/contracts/navigation", "@agent-device/contracts/network-runtime", diff --git a/src/cli/__tests__/cloud-auth-request.test.ts b/src/cli/__tests__/cloud-auth-request.test.ts index 0b7584669e..54dcc02f8d 100644 --- a/src/cli/__tests__/cloud-auth-request.test.ts +++ b/src/cli/__tests__/cloud-auth-request.test.ts @@ -163,3 +163,19 @@ test.each([ expect(other.received).toEqual([]); }, ); + +test('a cloud base URL over plain http off loopback is refused before anything is sent', async () => { + let sent = 0; + const refusal = await postCloudAuthJson({ + baseUrl: 'http://cloud.example.test', + pathName: '/start', + body: BODY, + fetchImpl: async () => { + sent += 1; + return new Response('{}'); + }, + }).catch(normalizeError); + + expect(refusal).toMatchObject({ details: { reason: 'insecure_credential_transport' } }); + expect(sent).toBe(0); +}); diff --git a/src/cli/cloud-auth-request.ts b/src/cli/cloud-auth-request.ts index e074cf5a03..c54e441d64 100644 --- a/src/cli/cloud-auth-request.ts +++ b/src/cli/cloud-auth-request.ts @@ -1,3 +1,4 @@ +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { readCloudJsonResponse } from './cloud-response.ts'; @@ -30,7 +31,11 @@ export async function postCloudAuthJson(options: { classifyRejectedBody?: (parsed: unknown) => AppError | undefined; }): Promise { const fetchImpl = options.fetchImpl ?? fetch; - const requestUrl = new URL(options.pathName, options.baseUrl); + // Every followed hop stays on this origin, so one check covers the chain. + const requestUrl = assertSecureCredentialTransport( + new URL(options.pathName, options.baseUrl), + 'Cloud base URL', + ); const post: RequestInit = { method: 'POST', headers: { 'content-type': 'application/json' }, diff --git a/src/cli/connection/cloud-profile-transport.test.ts b/src/cli/connection/cloud-profile-transport.test.ts new file mode 100644 index 0000000000..ab9c4fc430 --- /dev/null +++ b/src/cli/connection/cloud-profile-transport.test.ts @@ -0,0 +1,89 @@ +// `connect cloud` sends its bearer token to the cloud profile endpoint only over https, or plain +// http to loopback. + +import { afterEach, test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import path from 'node:path'; +import { connectCommand } from '../commands/connection.ts'; +import { resolveCloudAccessForConnect } from '../auth-session.ts'; +import type { AgentDeviceClient } from '@agent-device/command-surface'; +import { normalizeError } from '@agent-device/kernel/errors'; +import { + beginStdoutCapture, + bindTestCommandHost, + closeLoopbackServer, + listenOnLoopback, + createTestHostEnvironment, + mkdtempForTestSync, +} from '@agent-device/test-kit'; + +bindTestCommandHost(); + +const servers: http.Server[] = []; +afterEach(async () => { + await Promise.all(servers.splice(0).map((server) => closeLoopbackServer(server))); +}); + +/** A loopback cloud that records the `authorization` of each request it answers. */ +async function serveCloud(answer: (res: http.ServerResponse) => void) { + const received: Array = []; + const server = http.createServer((req, res) => { + received.push(req.headers.authorization); + answer(res); + }); + servers.push(server); + return { origin: `http://127.0.0.1:${await listenOnLoopback(server)}`, received }; +} + +vi.mock('../auth-session.ts', async (importOriginal) => ({ + ...(await importOriginal()), + resolveCloudAccessForConnect: vi.fn(), +})); + +async function connectCloud(stateDir: string) { + return await connectCommand({ + host: createTestHostEnvironment(), + positionals: [], + flags: { json: true, help: false, version: false, stateDir }, + client: {} as AgentDeviceClient, + }); +} + +test('connect cloud never sends its bearer token to a plain http cloud off loopback', async () => { + const stateDir = path.join(mkdtempForTestSync('agent-device-connect-cloud-transport-'), '.state'); + vi.mocked(resolveCloudAccessForConnect).mockResolvedValue({ + accessToken: 'adc_agent_cloud', + cloudBaseUrl: 'http://cloud.example', + }); + const send = vi.spyOn(globalThis, 'fetch'); + const stdoutCapture = beginStdoutCapture(); + + try { + await assert.rejects( + async () => await connectCloud(stateDir), + (error: unknown) => normalizeError(error).details?.reason === 'insecure_credential_transport', + ); + assert.equal(send.mock.calls.length, 0); + } finally { + stdoutCapture.restore(); + send.mockRestore(); + } +}); + +test('a redirected profile request fails without reaching the other origin', async () => { + const other = await serveCloud((res) => res.writeHead(401).end('{}')); + const cloud = await serveCloud((res) => + res.writeHead(307, { location: `${other.origin}/profile` }).end(), + ); + const stateDir = path.join(mkdtempForTestSync('agent-device-connect-cloud-redirect-'), '.state'); + vi.mocked(resolveCloudAccessForConnect).mockResolvedValue({ + accessToken: 'adc_agent_cloud', + cloudBaseUrl: cloud.origin, + }); + + await assert.rejects(async () => await connectCloud(stateDir)); + + assert.deepEqual(cloud.received, ['Bearer adc_agent_cloud']); + assert.deepEqual(other.received, []); +}); diff --git a/src/cli/connection/cloud-profile.ts b/src/cli/connection/cloud-profile.ts index fe58324e96..bb4598099b 100644 --- a/src/cli/connection/cloud-profile.ts +++ b/src/cli/connection/cloud-profile.ts @@ -1,6 +1,7 @@ import type { RemoteConfigProfile } from '@agent-device/remote/remote-config-schema'; import { AppError } from '@agent-device/kernel/errors'; import type { CliFlags } from '@agent-device/contracts/command'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { CLOUD_LEASE_PROVIDER } from '@agent-device/contracts/lease-scope'; import { type EnvMap } from '@agent-device/kernel/source-value'; import { resolveCloudAccessForConnect } from '../auth-session.ts'; @@ -72,8 +73,13 @@ async function fetchConnectionProfile(options: { fetchImpl?: typeof fetch; }): Promise { const fetchImpl = options.fetchImpl ?? fetch; - const response = await fetchImpl(new URL(CONNECTION_PROFILE_PATH, options.cloudBaseUrl), { + const profileUrl = assertSecureCredentialTransport( + new URL(CONNECTION_PROFILE_PATH, options.cloudBaseUrl), + 'Cloud base URL', + ); + const response = await fetchImpl(profileUrl, { method: 'GET', + redirect: 'manual', headers: { authorization: `Bearer ${options.accessToken}` }, signal: AbortSignal.timeout(HTTP_TIMEOUT_MS), }); diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 353a860905..12340aa2a5 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -469,7 +469,7 @@ Remote connection providers use the same lifecycle: Providers: Cloud: agent-device connect or agent-device connect cloud discovers the agent-device cloud profile. Remote config: agent-device connect --remote-config ./remote-config.json uses a local profile. - Direct proxy: agent-device connect proxy --daemon-base-url stores the shared proxy profile and client identity. + Direct proxy: agent-device connect proxy --daemon-base-url stores the shared proxy profile and client identity. The client sends the token only over https or to a loopback http URL; for a LAN or VPN host, use https or a port forward to 127.0.0.1 (reason insecure_credential_transport). BrowserStack: agent-device connect browserstack verifies credentials, the exact device, and a bs:// app reference, then stores a local provider profile. It does not create an App Automate session. AWS Device Farm: agent-device connect aws-device-farm verifies credentials and the exact project, device, and optional app upload, then stores a local provider profile. It does not create a remote access session. TestMu AI (plugin, install separately): agent-device connect testmu verifies credentials and the exact virtual device (emulator or simulator) or, with --provider-device-type real, real device and OS version, then stores a local provider profile. --provider-app takes an lt:// app reference, an https URL, or a local path: connect looks an lt:// id up among your uploads for that device pool, while URL and local sources are uploaded and validated when open creates the session. It does not create a hub session. diff --git a/src/core/interactors/limrun-ios-files.test.ts b/src/core/interactors/limrun-ios-files.test.ts index e8718dc088..d3015aef8a 100644 --- a/src/core/interactors/limrun-ios-files.test.ts +++ b/src/core/interactors/limrun-ios-files.test.ts @@ -374,3 +374,20 @@ test('concurrent metadata reads do not inherit another caller cancellation', asy f.storage.finishDownloads(); await expect(second).resolves.toMatchObject({ CFBundleExecutable: 'Example' }); }); + +test('a provider API URL over plain http off loopback never receives the instance token', async () => { + const f = await fixture({}); + const local = path.join(f.directory, 'push.apns'); + await fs.writeFile(local, '{}'); + const fetchSpy = vi.spyOn(globalThis, 'fetch'); + try { + const session = { ...f.session, apiUrl: 'http://limrun.invalid/v1/ios_test/api' }; + const tools = createLimrunAppleToolProvider(session, new AbortController().signal); + await expect(tools.simulatorFiles.stageFile(local)).rejects.toMatchObject({ + details: { reason: 'insecure_credential_transport' }, + }); + expect(fetchSpy).not.toHaveBeenCalled(); + } finally { + fetchSpy.mockRestore(); + } +}); diff --git a/src/core/interactors/limrun-ios-files.ts b/src/core/interactors/limrun-ios-files.ts index 9ad197b71d..c49f27011e 100644 --- a/src/core/interactors/limrun-ios-files.ts +++ b/src/core/interactors/limrun-ios-files.ts @@ -7,6 +7,7 @@ import { type AppleToolExecOptions, } from '@agent-device/platform-apple/tool-provider'; import type { LimrunRuntimeDependencies } from '@agent-device/provider-limrun'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import { downloadLimrunFile } from '../limrun-download-file.ts'; @@ -63,6 +64,7 @@ export function createLimrunSimulatorFiles( }; const request = async (method: string, url: URL, signal: AbortSignal, body?: Uint8Array) => { signal.throwIfAborted(); + assertSecureCredentialTransport(url, 'Limrun API URL'); const response = await fetch(url, { method, headers: { diff --git a/src/core/interactors/limrun-ios-runner-products.ts b/src/core/interactors/limrun-ios-runner-products.ts index 3e947191c6..9bb873a016 100644 --- a/src/core/interactors/limrun-ios-runner-products.ts +++ b/src/core/interactors/limrun-ios-runner-products.ts @@ -12,6 +12,7 @@ import { pipeline } from 'node:stream/promises'; import { createGzip } from 'node:zlib'; import { extractArchiveSafely } from '@agent-device/host-kit/archive'; import { escapeXmlTextAndAttribute } from '@agent-device/xml'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { downloadLimrunFile } from '../limrun-download-file.ts'; /** Stages the version-matched release runner, or an explicitly supplied development build. */ @@ -246,6 +247,7 @@ export async function uploadLimrunRunnerProducts( for (const file of payloads) yield* createReadStream(path.join(directory, file.path), { signal }); } + assertSecureCredentialTransport(apiUrl, 'Limrun API URL'); const stream = createGzip(); const compression = pipeline(Readable.from(body()), stream, { signal }).catch(() => {}); try { diff --git a/src/core/interactors/limrun-ios-runner.test.ts b/src/core/interactors/limrun-ios-runner.test.ts index d39348077a..2173e352ae 100644 --- a/src/core/interactors/limrun-ios-runner.test.ts +++ b/src/core/interactors/limrun-ios-runner.test.ts @@ -8,6 +8,8 @@ import { } from '@agent-device/host-kit/request'; import { expect, test, vi } from 'vitest'; import { fixture } from './limrun-ios-runner.fixtures.ts'; +import { uploadLimrunRunnerProducts } from './limrun-ios-runner-products.ts'; +import { mkdtempForTest } from '@agent-device/test-kit'; test('stages a token-authenticated runner once and presents forwarded XCTest snapshots', async () => { const f = await fixture(); const snapshot = await f.runner.createInteractor().snapshot({ @@ -48,6 +50,24 @@ test('stages a token-authenticated runner once and presents forwarded XCTest sna ).rejects.toThrow(); }); +test('a runner upload never sends the instance token over plain http off loopback', async () => { + const directory = await mkdtempForTest('limrun-runner-upload-'); + const fetchSpy = vi.spyOn(globalThis, 'fetch'); + try { + await expect( + uploadLimrunRunnerProducts( + directory, + 'http://limrun.invalid/v1/ios_test/api', + 'instance-token', + new AbortController().signal, + ), + ).rejects.toMatchObject({ details: { reason: 'insecure_credential_transport' } }); + expect(fetchSpy).not.toHaveBeenCalled(); + } finally { + fetchSpy.mockRestore(); + } +}); + test('launches a Watch session with the watchOS runner and XCTest frameworks', async () => { const f = await fixture({ appleOs: 'watchos' }); await f.runner.createInteractor().snapshot({ appBundleId: 'com.apple.NanoSettings' }); diff --git a/src/core/interactors/limrun-ios-runner.ts b/src/core/interactors/limrun-ios-runner.ts index 2fa477f958..7e1aee6aad 100644 --- a/src/core/interactors/limrun-ios-runner.ts +++ b/src/core/interactors/limrun-ios-runner.ts @@ -14,6 +14,7 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { AppError, TIMEOUT_REASONS } from '@agent-device/kernel/errors'; import { readVersion } from '@agent-device/host-kit/version'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { prepareLimrunRunnerProducts, uploadLimrunRunnerProducts, @@ -163,6 +164,7 @@ export async function createLimrunIosRunner( const remainingMs = deadline?.remainingMs() ?? 120_000; const launchTimeoutMs = Math.max(1, Math.floor(Math.min(90_000, remainingMs * 0.75))); const launchSignal = AbortSignal.any([signal, AbortSignal.timeout(launchTimeoutMs)]); + assertSecureCredentialTransport(apiUrl, 'Limrun API URL'); response = await retryWithPolicy( async () => { runRequested = true; diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index 324128028c..dcff1f8997 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -3,13 +3,14 @@ import http from 'node:http'; import path from 'node:path'; import type { AddressInfo } from 'node:net'; import { afterEach, expect, test, vi } from 'vitest'; -import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; +import { AppError, createRequestCanceledError, normalizeError } from '@agent-device/kernel/errors'; import { mkdtempForTest } from '@agent-device/test-kit'; import { downloadLimrunFile } from './limrun-download-file.ts'; const servers: http.Server[] = []; afterEach(async () => { + vi.restoreAllMocks(); await Promise.all( servers.splice(0).map( (server) => @@ -200,3 +201,114 @@ test.each(['default', 'typed', 'deadline'] as const)( expect(fs.existsSync(destinationPath)).toBe(false); }, ); + +test('a download URL over plain http off loopback is never requested and writes nothing', async () => { + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + fs.writeFileSync(destinationPath, 'earlier download'); + const fetchSpy = vi.spyOn(globalThis, 'fetch'); + + await expect( + downloadLimrunFile({ + url: 'http://limrun.invalid/files?signature=signed', + headers: {}, + destinationPath, + timeoutMs: 5_000, + }), + ).rejects.toMatchObject({ details: { reason: 'insecure_credential_transport' } }); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(fs.readFileSync(destinationPath, 'utf8')).toBe('earlier download'); +}); + +test('an https redirect to another origin is followed without the caller headers', async () => { + const sent: Array<[string, string | null]> = []; + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + sent.push([String(input), new Headers(init?.headers).get('authorization')]); + if (sent.length > 1) return new Response('payload'); + const location = 'https://storage.example/clip?signature=signed'; + return new Response(null, { status: 302, headers: { location } }); + }); + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + + await downloadLimrunFile({ + url: 'https://limrun.example/files', + headers: { Authorization: 'Bearer instance-token' }, + destinationPath, + timeoutMs: 5_000, + }); + + expect(fs.readFileSync(destinationPath, 'utf8')).toBe('payload'); + expect(sent).toEqual([ + ['https://limrun.example/files', 'Bearer instance-token'], + ['https://storage.example/clip?signature=signed', null], + ]); +}); + +/** A loopback server that answers `redirects` same-origin 307s before it serves the file. */ +async function serveRedirectChain(redirects: number) { + const requests: string[] = []; + const url = await serve((request, response) => { + requests.push(request.headers.authorization ?? '-'); + if (requests.length > redirects) return void response.end('payload'); + response.writeHead(307, { location: `/hop-${requests.length}` }).end(); + }); + return { url, requests }; +} + +test.each([4, 20])('a chain of %i same-origin redirects ends with the file', async (redirects) => { + const { url, requests } = await serveRedirectChain(redirects); + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + + await downloadLimrunFile({ + url, + headers: { Authorization: 'Bearer instance-token' }, + destinationPath, + timeoutMs: 5_000, + }); + + expect(fs.readFileSync(destinationPath, 'utf8')).toBe('payload'); + expect(requests).toEqual(Array(redirects + 1).fill('Bearer instance-token')); +}); + +test('a twenty-first redirect is not followed', async () => { + const { url, requests } = await serveRedirectChain(21); + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + + await expect( + downloadLimrunFile({ url, headers: {}, destinationPath, timeoutMs: 5_000 }), + ).rejects.toMatchObject({ details: { statusCode: 307 } }); + expect(requests).toHaveLength(21); +}); + +test.each([ + ['plain http', 'http://storage.example/clip?signature=target-secret'], + ['a URL with a username', 'https://target-secret@limrun.example/clip'], +])( + 'a redirect to %s is not followed, and its failure keeps no URL, Location or body', + async (_label, location) => { + const cancel = vi.fn(); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => { + const echo = new TextEncoder().encode(`${location} Bearer instance-token`); + const body = new ReadableStream({ start: (stream) => stream.enqueue(echo), cancel }); + return new Response(body, { status: 307, headers: { location } }); + }); + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + + const failure = await downloadLimrunFile({ + url: 'https://limrun.example/files?signature=source-secret', + headers: { Authorization: 'Bearer instance-token' }, + destinationPath, + timeoutMs: 5_000, + }).catch(normalizeError); + + expect(failure).toMatchObject({ + code: 'COMMAND_FAILED', + message: 'Limrun download did not follow a redirect', + details: { statusCode: 307, reason: 'limrun_download_http_error' }, + }); + expect(JSON.stringify(failure)).not.toMatch(/secret|instance-token|\.example/); + expect(fetchSpy).toHaveBeenCalledOnce(); + expect(cancel).toHaveBeenCalledOnce(); + expect(fs.existsSync(destinationPath)).toBe(false); + }, +); diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index de48670507..6b04e35c74 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -9,13 +9,18 @@ import { type ReasonTable, } from '@agent-device/kernel/errors'; import type { LimrunFileDownload } from '@agent-device/provider-limrun'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; const RESPONSE_BODY_PREVIEW_BYTES = 500; +// The limit `fetch` applies to the redirects it follows itself. +const MAX_DOWNLOAD_REDIRECTS = 20; +const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); -// Why a Limrun file download did not land. The destination is removed on every failure, so each row -// means "retry from the same URL", and `limrun_download_failed` adds that the transport itself broke. +// Why a Limrun file download did not land. A started download removes its destination on every +// failure, so each row means "retry from the same URL", and `limrun_download_failed` adds that the +// transport itself broke. const LIMRUN_DOWNLOAD_REASONS = { - // The service answered the download with an error status; `details.statusCode` and `details.body` carry its reply. + // The service answered with an error status or a redirect that is not followed. `details.statusCode` carries it; `details.body` carries an error reply, never a redirect's. httpError: { reason: 'limrun_download_http_error' }, // The download passed its deadline; `details.timeoutMs` is that deadline. timeout: { reason: 'limrun_download_timeout' }, @@ -26,18 +31,18 @@ const LIMRUN_DOWNLOAD_REASONS = { /** * Streams one authenticated Limrun download to disk. The transfer is bounded by `timeoutMs`; a * failed or timed-out attempt leaves no file at the destination, so the caller can retry from the - * same URL and never mistakes an earlier attempt's file for this one's. + * same URL and never mistakes an earlier attempt's file for this one's. A URL that may not carry a + * credential is refused before any attempt, and the destination stays as it was. */ export async function downloadLimrunFile(options: LimrunFileDownload): Promise { + const url = assertSecureCredentialTransport(options.url, 'Limrun download URL'); const timeout = AbortSignal.timeout(options.timeoutMs); const signal = options.signal ? AbortSignal.any([timeout, options.signal]) : timeout; try { await fs.promises.mkdir(path.dirname(options.destinationPath), { recursive: true }); - const response = await fetch(options.url, { - method: 'GET', - headers: options.headers, - signal, - }); + // The URL comes from the provider and can be signed, and the headers carry its bearer token. + const response = await fetchDownload(url, options.headers, signal); + if (response.status >= 300 && response.status < 400) throw await unfollowedRedirect(response); if (!response.ok) throw await httpFailure(response, options); if (!response.body) { throw new AppError('COMMAND_FAILED', 'Limrun download returned no body', { @@ -55,6 +60,47 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise { + let target = url; + let sent: LimrunFileDownload['headers'] | undefined = headers; + for (let followed = 0; ; followed += 1) { + const response = await fetch(target.href, { headers: sent, signal, redirect: 'manual' }); + const next = followed < MAX_DOWNLOAD_REDIRECTS ? redirectTarget(response, target) : undefined; + if (!next) return response; + await response.body?.cancel().catch(() => undefined); + if (next.origin !== target.origin) sent = undefined; + target = next; + } +} + +function redirectTarget(response: Response, from: URL): URL | undefined { + const location = response.headers.get('location'); + if (!REDIRECT_STATUSES.has(response.status) || location === null) return undefined; + const to = URL.parse(location, from); + // `fetch` rejects a URL with userinfo with an error that quotes it. + if (!to || to.username || to.password) return undefined; + const staysOnHttps = from.protocol === 'https:' && to.protocol === 'https:'; + return to.origin === from.origin || staysOnHttps ? to : undefined; +} + +/** Keeps no URL, `Location` or body: each can hold the download's signature or echo its token. */ +async function unfollowedRedirect(response: Response): Promise { + await response.body?.cancel().catch(() => undefined); + return new AppError('COMMAND_FAILED', 'Limrun download did not follow a redirect', { + statusCode: response.status, + reason: LIMRUN_DOWNLOAD_REASONS.httpError.reason, + }); +} + async function httpFailure(response: Response, options: LimrunFileDownload): Promise { return new AppError('COMMAND_FAILED', `Limrun download failed with HTTP ${response.status}`, { url: options.url, diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 72f5ee3432..03e95df3b4 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -176,7 +176,7 @@ "packages/remote/src/upload-client.ts#isStringRecord": "sha256:b6d6b571b90baf0976d9c347c4a45a4363a4df5ad184ea1087cb3b9febd4b624", "packages/remote/src/upload-client.ts#parseUploadPreflightResult": "sha256:7ce3f43b45c03df8b7f2690432beedc7a537c1bba540961716862f8a632d5623", "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:5689da0c0cd18d0293e5bb05ddc0d8a07d1bca9ab1d94f8ca185b03bc5b8d758", - "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:6976942601980c80ef069a0e1cbd7058840d0384e9e87c48f5dfd8d1c774703c", + "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:889d3e3c0c9215c739c13ba8f2be0857c4a16b776b59ae835d9a2079ecf491e8", "packages/remote/src/upload-client.ts#shouldRetryDirectUpload": "sha256:29059f076ff7f2b9540ad15408be48792b2d63a601ef2b9fb2d54f5576d49bbd", "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:cc5d33f38e047cf3be4bd412b64958c7495eb9a45e58eefadaa00eefa0cb6b53", "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:93a36a9d3dea88064569517f3cdc34f27b33df6bf5f0c0ecc9efc29b47f24b77", @@ -554,8 +554,8 @@ }, { "declaration": "packages/remote/src/upload-client.ts#requestUploadPreflight", - "digest": "sha256:6976942601980c80ef069a0e1cbd7058840d0384e9e87c48f5dfd8d1c774703c", - "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs." + "digest": "sha256:889d3e3c0c9215c739c13ba8f2be0857c4a16b776b59ae835d9a2079ecf491e8", + "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs. #5150 also stops using a ticket whose URL is plain http to a host that is not loopback; the client takes the legacy upload route a released daemon already serves when it hands out no usable ticket. The preflight request and response shapes are unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#finalizeDirectUpload", diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index da38550332..a24e8fc66d 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -445,7 +445,7 @@ Exact behavior: `agent-device help telephony`. Remote daemons and tenants: - `--tenant`, `--session-isolation tenant`, `--run-id`, and `--lease-id` enforce lease admission on tenant-scoped daemons. -- `--daemon-base-url http(s)://host:port[/base-path]` calls a remote HTTP daemon instead of a local one. Add `--daemon-auth-token ` (or `AGENT_DEVICE_DAEMON_AUTH_TOKEN`) for a non-loopback URL. +- `--daemon-base-url http(s)://host[:port][/base-path]` calls a remote HTTP daemon instead of a local one. Add `--daemon-auth-token ` (or `AGENT_DEVICE_DAEMON_AUTH_TOKEN`) for a non-loopback URL. The client sends a token only over https, or over plain http to a loopback host (`127.0.0.0/8`, `::1`, or `localhost`). With a token, it refuses a plain http URL to any other host before it sends a request, with `details.reason: "insecure_credential_transport"`. Without a token, it refuses any non-loopback URL with an `INVALID_ARGS` error that names daemon authentication. To reach a host on your LAN or VPN, use https, or forward a local port to it, for example `ssh -L 4310:127.0.0.1:4310 `, and connect to `http://127.0.0.1:4310`. - Remote screenshots download to the path you pass. When a remote `record stop` names no destination, the client saves the file in your working directory and warns. - To drive a Mac's simulators from another machine, see [Remote proxy](#remote-proxy). For hosted devices in CI, see [BrowserStack](/docs/browserstack), [AWS Device Farm](/docs/aws-device-farm), or [TestMu AI](/docs/testmu). For `connect --remote-config`, see [Remote Metro workflow](#remote-metro-workflow). diff --git a/website/docs/docs/configuration.md b/website/docs/docs/configuration.md index f90673ebbd..cba534196d 100644 --- a/website/docs/docs/configuration.md +++ b/website/docs/docs/configuration.md @@ -68,8 +68,9 @@ variables, or `connect`/`--remote-config`. For example, your user config can con For CI, provide both `AGENT_DEVICE_DAEMON_BASE_URL` and `AGENT_DEVICE_DAEMON_AUTH_TOKEN` from protected, operator-controlled configuration. Do not put either value in `./agent-device.json`. -Remote daemon URLs that aren't loopback always require authentication. Saved `connect` profiles and -explicit `--remote-config` files also work; generated profiles do not store tokens. +Remote daemon URLs that aren't loopback always require authentication, and they must use https: +the client never sends a token over plain http to a host that is not loopback. Saved `connect` +profiles and explicit `--remote-config` files also work; generated profiles do not store tokens. When a command fails against a remote daemon, its `Log:` path is on your machine; see [Capture a clean repro window](/docs/debugging-profiling#capture-a-clean-repro-window). diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 56ab349868..8e3a736d34 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -252,6 +252,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `transfer_forwarding_deadline_exceeded` | The whole exchange outlived the proxy's aggregate forwarding budget. | | `transfer_gateway_status` | The upstream daemon answered with a status that is not an HTTP response this proxy may relay. | | `transfer_upstream_closed` | The upstream daemon closed the connection before it answered, or during a write. | +| `proxy_upstream_userinfo` | The proxy's `upstreamBaseUrl` carries a username or password. The upstream credential is `upstreamToken` alone, and a request cannot be built from such a URL. | ### `react-devtools` @@ -815,7 +816,7 @@ These reasons can come from more than one command. | `limrun_runner_upload_failed` | The runner app could not be staged on the instance. | | `limrun_runner_bind_address_missing` | The simulator never reported the address its HTTP forward listens on. | | `limrun_runner_snapshot_unavailable` | The runner's snapshot capture came back too sparse to act on after a failed or unbudgeted capture. | -| `limrun_download_http_error` | The service answered the download with an error status; `details.statusCode` and `details.body` carry its reply. | +| `limrun_download_http_error` | The service answered with an error status or a redirect that is not followed. `details.statusCode` carries it; `details.body` carries an error reply, never a redirect's. | | `limrun_download_timeout` | The download passed its deadline; `details.timeoutMs` is that deadline. | | `limrun_download_failed` | The transfer broke for a reason the service never answered with, kept in `details.cause`. | @@ -899,6 +900,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | +| `insecure_credential_transport` | A credential would travel over plain http or ws to a host that is not loopback, to a socket URL that is not ws or wss, or to a URL that does not parse. The refusal names the setting, never the destination. | | `remote_instance_mismatch` | The daemon or proxy behind the remote URL was replaced since the client last read its health, so it refused a request addressed to the earlier instance. The client refreshes health and resends at most once; this reaches the caller when that resend is refused too. | | `remote_rpc_protocol_missing` | The checked RPC call named no RPC protocol. An intermediary that strips request headers causes this. | | `remote_rpc_protocol_mismatch` | The daemon or proxy speaks a different RPC protocol from the caller. After authentication, `details.service`, `details.version` and `details.rpcProtocolVersion` name the side that refused. | diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 31d00959a5..639681d9bc 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -27,7 +27,7 @@ agent-device proxy --port 4310 --public-origin https://example.trycloudflare.com The command prints the local proxy URL and a `daemon auth token`. Keep the token secret: anyone who has it can control the daemon behind the proxy. -By default the proxy binds `127.0.0.1`. Use `--host 0.0.0.0` only when you want the proxy reachable from the host network. +By default the proxy binds `127.0.0.1`. Use `--host 0.0.0.0` only when you want the proxy reachable from the host network. A client on another machine still has to reach it over https, for example through a TLS-terminating reverse proxy, or through a port forward to its own loopback. ## Connect from the agent machine @@ -46,6 +46,8 @@ agent-device disconnect Every command on a proxy connection that takes a session must name it, with `AGENT_DEVICE_SESSION`, `--session `, or a `session` in your config. The same applies to every device-cloud connection. A command that names none fails with `INVALID_ARGS` and `details.reason: "REMOTE_SESSION_REQUIRED"`, and sends nothing to the proxy. It never falls back to the connection that another agent on the same machine saved last. This includes `connect proxy` and `open --remote-config ` with a proxy profile. The client and run that the proxy leases under come from the session name, so two agents with different names never share a lease. +The client sends a token only over https, or over plain http to a loopback host (`127.0.0.0/8`, `::1`, or `localhost`). It refuses a plain http URL to any other host before it sends a request, with `details.reason: "insecure_credential_transport"`. To reach a host on your LAN or VPN, use https, or forward a local port to it, for example `ssh -L 4310:127.0.0.1:4310 `, and connect to `http://127.0.0.1:4310`. + `--daemon-auth-token ` works instead of the environment variable, but it authenticates only the command you pass it to. Later commands need the token again through the environment variable, a `daemonAuthToken` entry in your remote config profile, or the flag on each command. `connect proxy` stores the proxy profile and client identity. `open` leases the device for you, and the lease expires after five minutes without commands. A lease allocated directly over the RPC without `ttlMs` gets the daemon's one-minute inactivity default instead. Either window starts when allocation completes, not when it was requested. `close` releases the active session and its device lease, unless the lease was allocated with `retainOnClose`; only `leases.release`, expiry, or daemon shutdown ends that one. The reply to any request that closed a session lists the leases it ended in `endedLeases`, as `{ leaseId, outcome: 'released' }`. This covers `close`, a `batch` with a close step, and a `replay` or `test` script that closes, as well as the session cleanup `test` runs after each script. A successful reply has the field in `data`, and a failed one has it in `error.details`. A gateway in front of the daemon reads the lease end from that reply. When the reply names the stored lease, the CLI forgets it, so the next `open` leases a device again. `disconnect` clears local connection state. diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index c53335c7a9..3d7e6f3f52 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -21,6 +21,19 @@ CLI commands run through a per-user background daemon: - Artifact uploads are size-capped, filenames are sanitized, and archive extraction rejects path-traversal entries. Artifact downloads resolve through server-side IDs, never client-supplied paths. - `install-from-source` protects the daemon host while it downloads and extracts the artifact; it does not vouch for the app inside. An app installed and launched on an iOS simulator runs as a process on the host Mac, so treat permission to send install requests as permission to run code on that Mac. +These paths never send a credential over plain http to a host that is not loopback: the daemon client (commands, uploads, artifacts, and diagnostics), the proxy's requests to its upstream daemon, cloud sign-in and cloud profile requests, the Metro host bridge and its companion, Limrun API and download requests, Revyl requests, and the Apple runner. Such a URL is refused before anything is sent to it, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. + +- Loopback means `127.0.0.0/8`, `::1`, or `localhost`. Such traffic stays on this machine. If you relay a loopback port to another machine, the relay must encrypt it. +- A redirect never takes a token or key to another origin: + - Cloud sign-in follows redirects only on the same origin. + - Cloud profile requests, Metro host bridge setup, and companion registration follow no redirect. A redirect fails the request. + - A Limrun download follows redirects on the same origin, and from https to https without its headers. + - The proxy follows no upstream redirect. It relays the redirect status without `Location`. +- The Metro companion opens the host bridge's socket, and every WebSocket the bridge relays to your dev server, only over `wss`, or `ws` to loopback. A dev server on a LAN `http` address gets no relayed WebSocket. A relayed HTTP request with an `Authorization` or `Cookie` header follows the same rule. The companion follows no redirect from your dev server; it returns the redirect to the bridge. +- There is one exception: for a physical iOS device that is not attached over USB, the Apple runner token travels over plain http to the device's CoreDevice tunnel address, and that tunnel encrypts the traffic. The exception relies on two facts: Apple's `devicectl` reports the address for that device, and the address is a unique local IPv6 address (`fd00::/8`). Any other reported address is refused. + +Not covered: WebDriver providers, including their endpoint overrides, the headers you give `install-from-source`, and the Limrun SDK client. + For remote or cloud deployments, you can add a custom auth hook for remotely consumable HTTP routes: set `AGENT_DEVICE_HTTP_AUTH_HOOK` to a module path that the daemon imports, and `AGENT_DEVICE_HTTP_AUTH_EXPORT` to select the export. Relative hook paths resolve from the daemon host's working directory. The host-local `/admin/human-control/*` route uses the daemon token instead. The hook runs with the daemon's full privileges, so treat it as trusted code: point it only at a read-only path you control, never at a location that less-trusted users or processes can write to. Whoever controls the daemon's environment controls the hook. On the upload routes, the hook context carries a `signal` that aborts when the upload request times out or its client disconnects. The daemon stops waiting for the hook at that point, so a hook that calls a slow identity service can use the signal to stop that call. Lease-owner human-control RPCs pass normal authentication and tenant/lease admission. They can