From 58a95b20fbf39fbe0206d3c6ecfb1913943e2760 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 13:02:42 +0100 Subject: [PATCH 01/22] fix(remote)!: never send credentials over plain http off loopback A remote daemon base URL with a token, the proxy's upstream daemon URL, the Metro host bridge URL, and the cloud auth base URL are refused before the first request when they use plain http to a host that is not loopback (insecure_credential_transport). An upload ticket that would carry a daemon credential over such a URL takes the legacy upload route. isLoopbackHostname moves to @agent-device/contracts/daemon-http so the proxy shares the same matcher. BREAKING CHANGE: http:// remote URLs to LAN or VPN hosts with a token no longer work. Use https, or a port forward to 127.0.0.1. Co-Authored-By: Claude Opus 5.5 --- .../daemon-http-credential-transport.test.ts | 43 +++++++++++++ packages/contracts/src/daemon-http.ts | 52 +++++++++++++++- ...ient-remote-health-recovery-budget.test.ts | 12 ++-- ...n-client-remote-transport-security.test.ts | 62 +++++++++++++++++++ .../daemon-client/src/__tests__/index.test.ts | 39 ++++++------ .../src/daemon-client-lifecycle.ts | 10 ++- .../src/daemon-resolution-loopback.test.ts | 13 +--- .../daemon-contracts/src/daemon-resolution.ts | 19 +----- packages/proxy/README.md | 5 +- packages/proxy/src/daemon-proxy.test.ts | 23 ++++++- packages/proxy/src/daemon-proxy.ts | 9 ++- packages/react-native/src/index-metro.test.ts | 16 +++++ .../react-native/src/metro/client-metro.ts | 2 + .../src/__tests__/upload-client.test.ts | 36 +++++++++++ packages/remote/src/upload-client.ts | 17 +++++ src/cli/__tests__/cloud-auth-request.test.ts | 16 +++++ src/cli/cloud-auth-request.ts | 2 + src/commands/schema/cli-help.ts | 2 +- website/docs/docs/commands.md | 2 +- website/docs/docs/configuration.md | 5 +- website/docs/docs/error-reasons.md | 1 + website/docs/docs/remote-proxy.md | 4 +- website/docs/docs/security-trust.md | 2 + 23 files changed, 327 insertions(+), 65 deletions(-) create mode 100644 packages/contracts/src/daemon-http-credential-transport.test.ts create mode 100644 packages/daemon-client/src/__tests__/daemon-client-remote-transport-security.test.ts diff --git a/packages/contracts/src/daemon-http-credential-transport.test.ts b/packages/contracts/src/daemon-http-credential-transport.test.ts new file mode 100644 index 0000000000..874a602ab1 --- /dev/null +++ b/packages/contracts/src/daemon-http-credential-transport.test.ts @@ -0,0 +1,43 @@ +import { expect, test } from 'vitest'; +import { AppError } from '@agent-device/kernel/errors'; +import { assertSecureCredentialTransport, isLoopbackHostname } from './daemon-http.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')).not.toThrow(); +}); + +test.each([ + 'http://fleet.example.test/agent-device', + 'http://10.0.0.7:4310', + 'http://0.0.0.0:4310', +])('a credential never travels over plain http 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).toMatchObject({ + reason: 'insecure_credential_transport', + origin: new URL(url).origin, + }); +}); diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 9c849d8ccf..aa82dbc7ed 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -1,5 +1,6 @@ +import net from 'node:net'; import path from 'node:path'; -import type { ReasonTable } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; // The daemon HTTP wire vocabulary shared by the daemon server, the remote // proxy, and every client that talks to them: the base path, the tenant, lease @@ -94,6 +95,55 @@ export function buildDaemonHttpAuthHeaders(token: string | undefined): Record; + +/** 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); +} + +/** + * Refuses a credential-bearing destination that uses plain http to a host that is not loopback. + * Call it before the first request that carries the credential. A URL that does not parse reaches + * nothing, so it passes; the caller refuses it. `subject` names the destination in the message. + */ +export function assertSecureCredentialTransport(url: string | URL, subject: string): void { + const destination = typeof url === 'string' ? URL.parse(url) : url; + if (!destination || isSecureCredentialDestination(destination)) return; + throw new AppError( + 'INVALID_ARGS', + `${subject} must use https to send credentials to ${destination.host}; plain http is allowed only on loopback.`, + { + reason: CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason, + origin: destination.origin, + hint: 'Use an https 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.', + }, + ); +} + /** The tenant id every daemon route accepts, trimmed, or `undefined` when it breaks the rule. */ export function normalizeTenantId(raw: string | undefined): string | undefined { if (!raw) return undefined; 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__/daemon-client-remote-transport-security.test.ts b/packages/daemon-client/src/__tests__/daemon-client-remote-transport-security.test.ts new file mode 100644 index 0000000000..96c9cf0599 --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-remote-transport-security.test.ts @@ -0,0 +1,62 @@ +// 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 { createDaemonTransport } from '../index.ts'; +import { resolveClientSettings } from '../daemon-client-lifecycle.ts'; + +const REQUEST = { session: 'default', command: 'devices', positionals: [], flags: {} }; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +test('a token for a plain http daemon off loopback is refused before any request leaves', async () => { + const opened = [ + vi.spyOn(http, 'request'), + vi.spyOn(https, 'request'), + vi.spyOn(net, 'connect'), + vi.spyOn(net, 'createConnection'), + vi.spyOn(globalThis, 'fetch'), + ]; + const send = createDaemonTransport( + createTestHostEnvironment({ + env: { + AGENT_DEVICE_DAEMON_BASE_URL: 'http://remote-mac.example.test:7777/agent-device', + AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'remote-secret', + }, + }), + ); + + const refusal = await send(REQUEST).then( + () => assert.fail('expected the plain http base URL to be refused'), + (error: unknown) => error, + ); + + assert.ok(refusal instanceof AppError, String(refusal)); + assert.equal(refusal.code, 'INVALID_ARGS'); + assert.equal(refusal.details?.reason, 'insecure_credential_transport'); + assert.equal(refusal.details?.origin, 'http://remote-mac.example.test:7777'); + for (const spy of opened) assert.equal(spy.mock.calls.length, 0); +}); + +test.each([ + 'http://127.0.0.1:4310/agent-device', + 'http://[::1]:4310/agent-device', + 'http://localhost:4310/agent-device', + 'https://remote-mac.example.test/agent-device', +])('a token for %s is admitted', (daemonBaseUrl) => { + const settings = resolveClientSettings( + { ...REQUEST, flags: { daemonBaseUrl } }, + 'remote-secret', + createTestHostEnvironment(), + ); + assert.equal(settings.remoteBaseUrl, daemonBaseUrl); + assert.equal(settings.remoteAuthToken, 'remote-secret'); +}); 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..03ebd73d7a 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -15,7 +15,10 @@ import { type OwnedReplayStateDir, } from '@agent-device/daemon-contracts/daemon-registration-owner'; import { + assertSecureCredentialTransport, isLoopbackHostname, +} from '@agent-device/contracts/daemon-http'; +import { resolveDaemonPaths, resolveDaemonServerMode, resolveDaemonTransportPreference, @@ -610,8 +613,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..c4ee633146 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/daemon-http'; 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/proxy/README.md b/packages/proxy/README.md index 5d92ac6894..1349a11478 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -152,7 +152,10 @@ 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. +daemon's `Response`. Abort the exchange when `request.signal` aborts. The request carries the +upstream token, so your transport must keep it confidential. Without `upstreamFetch`, +`upstreamBaseUrl` must use https, or plain http to a loopback host; the proxy refuses any other +http URL at construction with `details.reason: "insecure_credential_transport"`. 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 diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index da03369607..5b650e942d 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -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, @@ -685,6 +685,27 @@ test.each([ ).toThrow(); }); +test('the default transport refuses an upstream token for plain http off loopback at construction', () => { + let refusal: unknown; + try { + createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'secret', + clientToken: 'client', + }); + } catch (error) { + refusal = error; + } + expect(refusal).toBeInstanceOf(AppError); + expect((refusal as AppError).details?.reason).toBe('insecure_credential_transport'); + + for (const upstreamBaseUrl of ['http://127.0.0.1:4310', 'https://daemon.internal']) { + expect(() => + createDaemonProxy({ upstreamBaseUrl, upstreamToken: 'secret', clientToken: 'client' }), + ).not.toThrow(); + } +}); + test('malformed successful tickets fail without exposing upstream credentials', async () => { const upstream = recordingUpstream(() => Response.json({ upload: { url: 'bad', headers: { authorization: 'secret' } } }), diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 5e1bb8d15e..4c7f49f1d8 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -12,6 +12,7 @@ import { DAEMON_HTTP_NETWORK_ACCESS_HEADER, DAEMON_HTTP_PUBLIC_NETWORK_ACCESS, DAEMON_HTTP_TENANT_HEADER, + assertSecureCredentialTransport, buildDaemonHttpAuthHeaders, buildDaemonHttpUrl, isTenantOwnedSessionName, @@ -65,7 +66,10 @@ 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. Without `upstreamFetch` it must use + * https, or http on loopback, because every upstream request carries `upstreamToken`. + */ upstreamBaseUrl: string; /** Auth token of the upstream daemon. Never leaves the proxy. */ upstreamToken: string; @@ -571,6 +575,9 @@ function rewriteUploadDirectUrl( function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOptions { const upstreamBaseUrl = normalizeBaseUrl(options.upstreamBaseUrl, 'upstreamBaseUrl'); const upstreamToken = normalizeToken(options.upstreamToken, 'upstreamToken'); + if (!options.upstreamFetch) { + assertSecureCredentialTransport(upstreamBaseUrl, 'Proxy upstreamBaseUrl'); + } const clientToken = options.authenticate ? undefined : normalizeToken(options.clientToken ?? '', 'clientToken'); diff --git a/packages/react-native/src/index-metro.test.ts b/packages/react-native/src/index-metro.test.ts index 707ad64a52..721069e0cd 100644 --- a/packages/react-native/src/index-metro.test.ts +++ b/packages/react-native/src/index-metro.test.ts @@ -422,6 +422,22 @@ test('prepareMetroRuntime rejects incomplete proxy configuration', async () => { ); }); +test('prepareMetroRuntime refuses a bridge bearer token over plain http off loopback', async () => { + await assert.rejects( + () => + prepareMetroRuntime( + { + publicBaseUrl: 'https://sandbox.example.test', + proxyBaseUrl: 'http://proxy.example.test', + env: { AGENT_DEVICE_DAEMON_AUTH_TOKEN: TEST_TOKEN }, + }, + createTestHostEnvironment(), + ), + (error) => + error instanceof AppError && error.details?.reason === 'insecure_credential_transport', + ); +}); + 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.ts b/packages/react-native/src/metro/client-metro.ts index 7790b69585..c9077a31ac 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/daemon-http'; import { ensureMetroCompanion } from '../companion/client-metro-companion.ts'; import type { MetroBridgeDescriptor, @@ -629,6 +630,7 @@ function resolveProxySettings( 'metro prepare requires --proxy-base-url when proxy auth is provided.', ); } + if (proxyBaseUrl) assertSecureCredentialTransport(proxyBaseUrl, 'metro prepare --proxy-base-url'); return { proxyEnabled: Boolean(proxyBaseUrl && resolvedProxyBearerToken), proxyBaseUrl, diff --git a/packages/remote/src/__tests__/upload-client.test.ts b/packages/remote/src/__tests__/upload-client.test.ts index 0b57ce1fdb..b8d919e151 100644 --- a/packages/remote/src/__tests__/upload-client.test.ts +++ b/packages/remote/src/__tests__/upload-client.test.ts @@ -382,6 +382,42 @@ test('uploadArtifact falls back to legacy upload when direct upload exceeds redi } }); +test('uploadArtifact never sends a credential-bearing ticket over plain http off loopback', async () => { + const content = 'cleartext-ticket'; + const artifactPath = createTempFile('app.apk', content); + const requests: string[] = []; + const server = await startServer(async (req, res) => { + requests.push(`${req.method} ${req.url}`); + await readRequestBody(req); + if (req.url === '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/upload/preflight') { + sendJson(res, { + ok: true, + cacheHit: false, + uploadId: 'cleartext-ticket', + upload: { + url: 'http://ticket.invalid/upload/direct/cleartext-ticket', + headers: { authorization: `Bearer ${TEST_TOKEN}` }, + }, + }); + return; + } + sendJson(res, { ok: true, uploadId: 'legacy-upload' }); + }); + + try { + const uploadId = await uploadArtifact({ + localPath: artifactPath, + baseUrl: server.baseUrl, + token: TEST_TOKEN, + }); + // 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 server.close(); + } +}); + test('uploadArtifact uses direct upload ticket and finalize flow', async () => { const content = 'direct-upload-apk'; const artifactPath = createTempFile('app.apk', content); diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index b390acbbf4..4138dddd49 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -4,6 +4,7 @@ import { AppError } from '@agent-device/kernel/errors'; import { buildDaemonHttpAuthHeaders, buildDaemonHttpLeaseHeaders, + isSecureCredentialDestination, } from '@agent-device/contracts/daemon-http'; import { prepareUploadArtifact, type PreparedUploadArtifact } from './upload-client-artifact.ts'; import { @@ -371,6 +372,12 @@ function parseUploadPreflightResult(value: unknown): UploadPreflightResult | und if (!isStringRecord(headers)) { return undefined; } + // A ticket that would send a daemon credential over plain http off loopback is not usable; the + // upload takes the legacy route through the base URL the client already admitted. + if (carriesDaemonCredential(headers)) { + const ticketUrl = URL.parse(upload.url); + if (!ticketUrl || !isSecureCredentialDestination(ticketUrl)) return undefined; + } return { kind: 'direct-upload', uploadId: preflight.uploadId, @@ -379,6 +386,16 @@ function parseUploadPreflightResult(value: unknown): UploadPreflightResult | und }; } +const DAEMON_CREDENTIAL_HEADER_NAMES = new Set( + Object.keys(buildDaemonHttpAuthHeaders('credential')), +); + +function carriesDaemonCredential(headers: Record): boolean { + return Object.keys(headers).some((name) => + DAEMON_CREDENTIAL_HEADER_NAMES.has(name.toLowerCase()), + ); +} + function isStringRecord(value: unknown): value is Record { if (!value || typeof value !== 'object' || Array.isArray(value)) { return false; 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..54edde9e7e 100644 --- a/src/cli/cloud-auth-request.ts +++ b/src/cli/cloud-auth-request.ts @@ -1,4 +1,5 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/daemon-http'; import { readCloudJsonResponse } from './cloud-response.ts'; const HTTP_TIMEOUT_MS = 15_000; @@ -31,6 +32,7 @@ export async function postCloudAuthJson(options: { }): Promise { const fetchImpl = options.fetchImpl ?? fetch; const requestUrl = new URL(options.pathName, options.baseUrl); + assertSecureCredentialTransport(requestUrl, 'AGENT_DEVICE_CLOUD_BASE_URL'); const post: RequestInit = { method: 'POST', headers: { 'content-type': 'application/json' }, 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/website/docs/docs/commands.md b/website/docs/docs/commands.md index da38550332..a7beaea6a8 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 https://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`). 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`. - 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..776636c8ce 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -899,6 +899,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | +| `insecure_credential_transport` | A daemon, proxy, host bridge, or cloud auth credential would travel over plain http to a host that is not loopback. `details.origin` names the refused 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..5f1fc00cb1 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -21,6 +21,8 @@ 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. +A client never sends a daemon, proxy, Metro host bridge, or cloud auth credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. The proxy applies the same rule to its upstream daemon URL unless you supply your own `upstreamFetch` transport. + 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 From f566b464ab166a8243cc54b1cd6dd5c22a8366a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 13:27:48 +0100 Subject: [PATCH 02/22] fix(remote): close the remaining cleartext credential paths - proxy: every upstream request carries redirect: 'error'; the upstream URL rule applies to custom transports too, checked on the first exchange; a plain-http upstream goes direct over node:http - direct connection for credential-bearing plain-http requests, so an environment proxy never sees a loopback token (daemon client, remote transfers and diagnostics, proxy transports) - cloud profile discovery checks the URL and follows redirects only on the same origin - metro bridge and the companion worker check each final URL before the bearer is sent; a malformed base is refused - upload tickets must be https or loopback, whatever carries the credential - Limrun API and download URLs and forwarded runner routes are checked at send time - the rule lives in @agent-device/contracts/credential-transport and the matcher in @agent-device/contracts/loopback-host; daemon-http stays free of error imports; revyl uses the shared matcher Co-Authored-By: Claude Opus 5.5 --- .../src/__tests__/runner-transport.test.ts | 20 ++++ packages/apple-runner/src/runner-transport.ts | 12 ++ packages/contracts/package.json | 8 ++ ...t.test.ts => credential-transport.test.ts} | 17 +-- .../contracts/src/credential-transport.ts | 39 ++++++ packages/contracts/src/daemon-http.ts | 52 +------- packages/contracts/src/loopback-host.ts | 18 +++ .../src/daemon-client-lifecycle.ts | 6 +- .../src/daemon-client-transport.ts | 14 ++- .../daemon-contracts/src/daemon-resolution.ts | 2 +- packages/host-kit/package.json | 4 + packages/host-kit/src/direct-http.test.ts | 77 ++++++++++++ packages/host-kit/src/direct-http.ts | 69 +++++++++++ packages/provider-revyl/src/revyl-client.ts | 16 +-- packages/proxy/README.md | 28 +++-- .../src/daemon-proxy-cancellation.test.ts | 8 +- .../daemon-proxy-credential-transport.test.ts | 111 ++++++++++++++++++ .../src/daemon-proxy-transfer-loading.test.ts | 2 +- .../proxy/src/daemon-proxy-transfer.test.ts | 12 +- packages/proxy/src/daemon-proxy.test.ts | 45 ++----- packages/proxy/src/daemon-proxy.ts | 37 ++++-- packages/proxy/src/node-http.test.ts | 4 +- packages/proxy/src/transfer-transport.ts | 11 +- .../client-companion-tunnel-worker.test.ts | 24 +++- .../client-companion-tunnel-worker.ts | 23 +++- packages/react-native/src/index-metro.test.ts | 41 ++++--- .../react-native/src/metro/client-metro.ts | 9 +- .../src/__tests__/upload-client.test.ts | 6 +- packages/remote/src/artifact-download.ts | 4 + .../remote/src/remote-request-diagnostics.ts | 4 + packages/remote/src/upload-client.ts | 35 +++--- packages/remote/src/upload-stream.ts | 4 + .../layering/contracts-exports.snapshot.json | 2 + src/__tests__/cloud-connect-profile.test.ts | 50 ++++++++ src/cli/cloud-auth-request.ts | 53 ++++++--- src/cli/connection/cloud-profile.ts | 13 +- src/core/interactors/limrun-ios-files.test.ts | 17 +++ src/core/interactors/limrun-ios-files.ts | 3 +- .../interactors/limrun-ios-runner-products.ts | 28 +++-- src/core/limrun-download-file.test.ts | 17 +++ src/core/limrun-download-file.ts | 5 + website/docs/docs/commands.md | 2 +- website/docs/docs/error-reasons.md | 2 +- website/docs/docs/security-trust.md | 2 +- 44 files changed, 720 insertions(+), 236 deletions(-) rename packages/contracts/src/{daemon-http-credential-transport.test.ts => credential-transport.test.ts} (73%) create mode 100644 packages/contracts/src/credential-transport.ts create mode 100644 packages/contracts/src/loopback-host.ts create mode 100644 packages/host-kit/src/direct-http.test.ts create mode 100644 packages/host-kit/src/direct-http.ts create mode 100644 packages/proxy/src/daemon-proxy-credential-transport.test.ts diff --git a/packages/apple-runner/src/__tests__/runner-transport.test.ts b/packages/apple-runner/src/__tests__/runner-transport.test.ts index b4231879b1..a2bccdc7ff 100644 --- a/packages/apple-runner/src/__tests__/runner-transport.test.ts +++ b/packages/apple-runner/src/__tests__/runner-transport.test.ts @@ -211,6 +211,26 @@ 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('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-transport.ts b/packages/apple-runner/src/runner-transport.ts index 4fa663a2b7..3a10910070 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', ); } + // A forwarded route is a provider-supplied URL that receives the runner token and the provider's + // own headers, so it gets the credential transport rule. Local routes are loopback, USB, or the + // device's CoreDevice tunnel. + if (endpoint.http) { + const { assertSecureCredentialTransport } = + await import('@agent-device/contracts/credential-transport'); + try { + assertSecureCredentialTransport(route.url, 'Runner forwarding URL'); + } catch (error) { + throw discloseDispatch(error as AppError, 'no'); + } + } 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/daemon-http-credential-transport.test.ts b/packages/contracts/src/credential-transport.test.ts similarity index 73% rename from packages/contracts/src/daemon-http-credential-transport.test.ts rename to packages/contracts/src/credential-transport.test.ts index 874a602ab1..7503682263 100644 --- a/packages/contracts/src/daemon-http-credential-transport.test.ts +++ b/packages/contracts/src/credential-transport.test.ts @@ -1,6 +1,7 @@ import { expect, test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { assertSecureCredentialTransport, isLoopbackHostname } from './daemon-http.ts'; +import { 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); @@ -20,14 +21,19 @@ test.each([ 'http://[::1]:4310', 'http://localhost:4310', ])('a credential may travel to %s', (url) => { - expect(() => assertSecureCredentialTransport(url, 'Remote daemon base URL')).not.toThrow(); + 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', -])('a credential never travels over plain http to %s', (url) => { + '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'); @@ -36,8 +42,5 @@ test.each([ } expect(refusal).toBeInstanceOf(AppError); expect((refusal as AppError).code).toBe('INVALID_ARGS'); - expect((refusal as AppError).details).toMatchObject({ - reason: 'insecure_credential_transport', - origin: new URL(url).origin, - }); + expect((refusal as AppError).details?.reason).toBe('insecure_credential_transport'); }); diff --git a/packages/contracts/src/credential-transport.ts b/packages/contracts/src/credential-transport.ts new file mode 100644 index 0000000000..1ef707699a --- /dev/null +++ b/packages/contracts/src/credential-transport.ts @@ -0,0 +1,39 @@ +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. Callers check the final URL right before each send. + +/** Why a client refuses to send a credential before any request leaves. */ +const CREDENTIAL_TRANSPORT_REASONS = { + // A credential would travel over plain http to a host that is not loopback, or to a URL that does + // not parse. `details.origin` names the refused destination when it parses. + insecureTransport: { reason: 'insecure_credential_transport' }, +} as const satisfies ReasonTable<'remote connection'>; + +/** 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); +} + +/** + * 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 destination in the message. + */ +export function assertSecureCredentialTransport(url: string | URL, subject: string): URL { + const destination = typeof url === 'string' ? URL.parse(url) : url; + if (destination && isSecureCredentialDestination(destination)) return destination; + throw new AppError( + 'INVALID_ARGS', + destination + ? `${subject} must use https to send credentials to ${destination.host}; plain http is allowed only on loopback.` + : `${subject} is not a valid URL, so no credential is sent to it.`, + { + reason: CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason, + ...(destination ? { origin: destination.origin } : {}), + hint: 'Use an https 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.', + }, + ); +} diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index aa82dbc7ed..9c849d8ccf 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -1,6 +1,5 @@ -import net from 'node:net'; import path from 'node:path'; -import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import type { ReasonTable } from '@agent-device/kernel/errors'; // The daemon HTTP wire vocabulary shared by the daemon server, the remote // proxy, and every client that talks to them: the base path, the tenant, lease @@ -95,55 +94,6 @@ export function buildDaemonHttpAuthHeaders(token: string | undefined): Record; - -/** 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); -} - -/** - * Refuses a credential-bearing destination that uses plain http to a host that is not loopback. - * Call it before the first request that carries the credential. A URL that does not parse reaches - * nothing, so it passes; the caller refuses it. `subject` names the destination in the message. - */ -export function assertSecureCredentialTransport(url: string | URL, subject: string): void { - const destination = typeof url === 'string' ? URL.parse(url) : url; - if (!destination || isSecureCredentialDestination(destination)) return; - throw new AppError( - 'INVALID_ARGS', - `${subject} must use https to send credentials to ${destination.host}; plain http is allowed only on loopback.`, - { - reason: CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason, - origin: destination.origin, - hint: 'Use an https 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.', - }, - ); -} - /** The tenant id every daemon route accepts, trimmed, or `undefined` when it breaks the rule. */ export function normalizeTenantId(raw: string | undefined): string | undefined { if (!raw) return undefined; 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/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index 03ebd73d7a..8e2dddc0a6 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -14,10 +14,8 @@ import { stopAndRetireDaemon, type OwnedReplayStateDir, } from '@agent-device/daemon-contracts/daemon-registration-owner'; -import { - assertSecureCredentialTransport, - isLoopbackHostname, -} from '@agent-device/contracts/daemon-http'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; +import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; import { resolveDaemonPaths, resolveDaemonServerMode, diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 21fe9a0d7f..356a85fc9d 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -298,7 +298,11 @@ async function readDaemonHttpHealth( const timeoutSignal = AbortSignal.timeout(Math.ceil(timeoutMs)); const signal = callerSignal ? AbortSignal.any([timeoutSignal, callerSignal]) : timeoutSignal; const transport = await Promise.race([ - loadNodeHttpRequester(url.protocol), + Promise.all([ + loadNodeHttpRequester(url.protocol), + // Plain http carries the token only to loopback, and never through an environment proxy. + import('@agent-device/host-kit/direct-http').then((m) => m.loadDirectHttpAgent(url.protocol)), + ]), new Promise((resolve) => { signal.addEventListener('abort', () => resolve(null), { once: true }); }), @@ -307,7 +311,8 @@ async function readDaemonHttpHealth( if (!transport || healthProbeExpired(signal, deadline)) return unreachable(); return await new Promise((resolve) => { const headers = info.baseUrl ? buildDaemonHttpAuthHeaders(info.token) : {}; - const req = transport.request( + const [requester, agent] = transport; + const req = requester.request( { protocol: url.protocol, host: url.hostname, @@ -317,6 +322,7 @@ async function readDaemonHttpHealth( timeout: timeoutMs, signal, headers, + agent, }, (res) => { let body = ''; @@ -812,6 +818,9 @@ async function sendHttpRequest( if (checked) headers[DAEMON_HTTP_RPC_PROTOCOL_HEADER] = String(DAEMON_RPC_PROTOCOL_VERSION); const checkedRpc = checked ? await import('./daemon-client-checked-rpc.ts') : undefined; const transport = await loadNodeHttpRequester(rpcUrl.protocol); + const agent = await ( + await import('@agent-device/host-kit/direct-http') + ).loadDirectHttpAgent(rpcUrl.protocol); const callerSignal = options.signal; refuseAbortedRequest(callerSignal, req.meta?.requestId); @@ -856,6 +865,7 @@ async function sendHttpRequest( method: 'POST', path: rpcUrl.pathname + rpcUrl.search, headers, + agent, }, (res) => { if (checkedRpc?.isCheckedRpcOutcomeResponse(res.statusCode, res.headers ?? {})) { diff --git a/packages/daemon-contracts/src/daemon-resolution.ts b/packages/daemon-contracts/src/daemon-resolution.ts index c4ee633146..8663fb413b 100644 --- a/packages/daemon-contracts/src/daemon-resolution.ts +++ b/packages/daemon-contracts/src/daemon-resolution.ts @@ -12,7 +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/daemon-http'; +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 }; diff --git a/packages/host-kit/package.json b/packages/host-kit/package.json index e75388b928..afe25d002c 100644 --- a/packages/host-kit/package.json +++ b/packages/host-kit/package.json @@ -44,6 +44,10 @@ "types": "./src/diagnostics.ts", "default": "./src/diagnostics.ts" }, + "./direct-http": { + "types": "./src/direct-http.ts", + "default": "./src/direct-http.ts" + }, "./doctor-lines": { "types": "./src/doctor-lines.ts", "default": "./src/doctor-lines.ts" diff --git a/packages/host-kit/src/direct-http.test.ts b/packages/host-kit/src/direct-http.test.ts new file mode 100644 index 0000000000..ca883749d4 --- /dev/null +++ b/packages/host-kit/src/direct-http.test.ts @@ -0,0 +1,77 @@ +import { afterEach, expect, test } from 'vitest'; +import { execFile } from 'node:child_process'; +import http from 'node:http'; +import path from 'node:path'; +import { promisify } from 'node:util'; +import { closeLoopbackServer, listenOnLoopback } from '@agent-device/test-kit'; + +// A credential sent over plain http goes only to loopback, and an environment proxy on another host +// would read it in cleartext. Node reads `NODE_USE_ENV_PROXY` at startup, so each case runs a child. + +const servers: http.Server[] = []; +afterEach(async () => { + await Promise.all(servers.splice(0).map((server) => closeLoopbackServer(server))); +}); + +async function serve(seen: string[]): Promise { + const server = http.createServer((req, res) => { + seen.push(`${req.method} ${req.url} ${req.headers.authorization ?? ''}`); + res.end('ok'); + }); + servers.push(server); + return await listenOnLoopback(server); +} + +const TRANSPORT = path.join(import.meta.dirname, 'direct-http.ts'); + +async function runChild(script: string, proxyPort: number): Promise { + const { stdout } = await promisify(execFile)( + process.execPath, + ['--experimental-strip-types', '--input-type=module', '-e', script], + { + env: { + ...process.env, + NODE_USE_ENV_PROXY: '1', + HTTP_PROXY: `http://127.0.0.1:${proxyPort}`, + http_proxy: `http://127.0.0.1:${proxyPort}`, + NO_PROXY: '', + no_proxy: '', + }, + }, + ); + return stdout.trim(); +} + +test.each([ + [ + 'node:http with loadDirectHttpAgent', + (target: string) => ` + import http from 'node:http'; + import { loadDirectHttpAgent } from ${JSON.stringify(TRANSPORT)}; + const agent = await loadDirectHttpAgent('http:'); + await new Promise((resolve, reject) => { + const req = http.request(${JSON.stringify(target)}, { agent, headers: { authorization: 'Bearer secret' } }, (res) => { res.resume(); res.on('end', resolve); }); + req.on('error', reject); + req.end(); + }); + console.log('sent');`, + ], + [ + 'fetchOverDirectHttp', + (target: string) => ` + import { fetchOverDirectHttp } from ${JSON.stringify(TRANSPORT)}; + const response = await fetchOverDirectHttp(new Request(${JSON.stringify(target)}, { headers: { authorization: 'Bearer secret' } })); + console.log(await response.text() === 'ok' ? 'sent' : 'bad');`, + ], +])('%s reaches loopback directly, never through an environment proxy', async (_label, script) => { + const proxied: string[] = []; + const direct: string[] = []; + const proxyPort = await serve(proxied); + const targetPort = await serve(direct); + + const output = await runChild(script(`http://127.0.0.1:${targetPort}/rpc`), proxyPort); + + expect(output).toBe('sent'); + expect(proxied).toEqual([]); + expect(direct).toEqual(['GET /rpc Bearer secret']); +}); diff --git a/packages/host-kit/src/direct-http.ts b/packages/host-kit/src/direct-http.ts new file mode 100644 index 0000000000..6cc99fb09d --- /dev/null +++ b/packages/host-kit/src/direct-http.ts @@ -0,0 +1,69 @@ +import type { Agent } from 'node:http'; +import { loadNodeHttpRequester } from './internal/transport.ts'; + +// Loaded at send time by the code that sends a credential over plain http, never at module scope. + +let directHttpAgent: Agent | undefined; + +/** + * The agent for a plain-http request that carries a credential: a direct connection that never + * routes through an environment proxy (`NODE_USE_ENV_PROXY` with `HTTP_PROXY`). Plain http + * carries credentials only to loopback, and a proxy on another host would read them in cleartext. + * Returns `undefined` for https, which keeps the default agent. + */ +export async function loadDirectHttpAgent(protocol: string): Promise { + if (protocol !== 'http:') return undefined; + const http = (await import('node:http')).default; + directHttpAgent ??= new http.Agent({ keepAlive: true, scheduling: 'lifo', timeout: 5_000 }); + return directHttpAgent; +} + +const NULL_BODY_STATUSES = new Set([204, 205, 304]); + +/** + * Sends one Fetch request over `node:http` with `loadDirectHttpAgent`, for a plain-http + * destination that receives a credential. It never follows a redirect: a 3xx is returned as is. + */ +export async function fetchOverDirectHttp(request: Request): Promise { + const url = new URL(request.url); + if (url.protocol !== 'http:') throw new TypeError('fetchOverDirectHttp sends plain http only'); + const [http, agent, { Readable }] = await Promise.all([ + loadNodeHttpRequester('http:'), + loadDirectHttpAgent('http:'), + import('node:stream'), + ]); + const body = request.body ? Buffer.from(await request.arrayBuffer()) : undefined; + request.signal.throwIfAborted(); + return await new Promise((resolve, reject) => { + const req = http.request( + { + host: url.hostname.replace(/^\[(.*)\]$/, '$1'), + port: url.port, + path: `${url.pathname}${url.search}`, + method: request.method, + headers: Object.fromEntries(request.headers), + agent, + signal: request.signal, + }, + (res) => { + const status = res.statusCode ?? 502; + const headers = new Headers(); + for (const [name, value] of Object.entries(res.headers)) { + if (value === undefined) continue; + for (const item of Array.isArray(value) ? value : [value]) headers.append(name, item); + } + const nullBody = request.method === 'HEAD' || NULL_BODY_STATUSES.has(status); + if (nullBody) res.resume(); + resolve( + new Response(nullBody ? null : (Readable.toWeb(res) as ReadableStream), { + status, + statusText: res.statusMessage, + headers, + }), + ); + }, + ); + req.on('error', reject); + req.end(body); + }); +} diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index fb4b720a18..11caa8523a 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -5,8 +5,8 @@ import { type ReasonTable, } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; +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 { @@ -682,20 +682,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 1349a11478..e474f039e5 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -128,14 +128,12 @@ On these routes: Supply `upstreamFetch` if you need those Fetch behaviors or your own routing. -Environment-proxy routing depends on your runtime. In loopback checks, Node 22.12 ignores -`HTTP_PROXY` and `HTTPS_PROXY` for both transports. Node 26.11.1 uses them when -`NODE_USE_ENV_PROXY=1`. Bun 1.4.2 Fetch uses them without that opt-in, while the default transfer -transport requires it. On Node 26.11.1 and Bun 1.4.2, `NO_PROXY=127.0.0.1` bypasses the proxy. -If your Bun deployment needs proxy routing for transfers, set `NODE_USE_ENV_PROXY=1` or supply -`upstreamFetch`. +A plain-http upstream is loopback, and the default transport reaches it directly over `node:http` +on every route. An environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY=1`) never sees the +upstream token. An https upstream follows your runtime's environment-proxy settings: Node 26.11.1 +uses them when `NODE_USE_ENV_PROXY=1`, and Bun 1.4.2 Fetch uses them without that opt-in. -By default, `/rpc`, `/health` and request diagnostics use global `fetch`. +By default, `/rpc`, `/health` and request diagnostics to an https upstream use global `fetch`. ### Reach the daemon over your own transport @@ -144,7 +142,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), @@ -153,9 +151,13 @@ 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. The request carries the -upstream token, so your transport must keep it confidential. Without `upstreamFetch`, -`upstreamBaseUrl` must use https, or plain http to a loopback host; the proxy refuses any other -http URL at construction with `details.reason: "insecure_credential_transport"`. +upstream token and `redirect: 'error'`; never follow a redirect with it. + +`upstreamBaseUrl` must use https, or plain http to a loopback host, with or without +`upstreamFetch`. 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` +(`details.reason: "insecure_credential_transport"` on `/rpc`). 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 @@ -216,11 +218,11 @@ 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`. | -| `upstreamFetch` | none | Sends one request to the daemon. Without it, transfer routes use `node:http(s)` and every other route uses the global `fetch`. | +| `upstreamFetch` | none | Sends one request to the daemon. Without it, transfer routes use `node:http(s)`, a plain-http upstream uses `node:http` on every route, and other routes use the global `fetch`. | | `maxRpcBodyBytes` | 64 MiB, the daemon's own request limit | Larger `/rpc` bodies get a 400 response. | | `upstreamTimeoutMs` | none | Independent cap on one daemon request, including its body. `/health` keeps its separate five-second limit. Without this option, other requests last as long as the client waits, bounded by the client's command timeout and, on transfer routes, the 600-second forwarding aggregate. | 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-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts new file mode 100644 index 0000000000..ffb80ad1e2 --- /dev/null +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -0,0 +1,111 @@ +// 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 { closeLoopbackServer, listenOnLoopback } from '@agent-device/test-kit'; +import { createDaemonProxy, type DaemonProxyUpstreamFetch } from './daemon-proxy.ts'; + +const servers: http.Server[] = []; +afterEach(async () => { + vi.restoreAllMocks(); + await Promise.all(servers.splice(0).map((server) => closeLoopbackServer(server))); +}); + +async function serve(handler: http.RequestListener): Promise { + const server = http.createServer(handler); + servers.push(server); + return `http://127.0.0.1:${await listenOnLoopback(server)}`; +} + +const rpc = () => + new Request('https://gateway.example.test/agent-device/rpc', { + method: 'POST', + headers: { authorization: 'Bearer client-secret', 'content-type': 'application/json' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent-device.command', params: {} }), + }); + +test.each([ + ['the default transport', undefined], + ['a custom transport', 'custom'], +] as const)( + '%s never sends the upstream token to plain http off loopback', + async (_label, 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: 'http://daemon.invalid:4310', + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + ...(upstreamFetch ? { upstreamFetch } : {}), + }); + + for (const request of [ + rpc(), + new Request('https://gateway.example.test/agent-device/health'), + 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(400); + expect(await response.text(), request.url).toContain( + 'plain http is allowed only on loopback', + ); + } + expect(sent).toEqual([]); + }, +); + +test('an upstream redirect is never followed, so its target receives no token', async () => { + const reached: string[] = []; + const target = await serve((req, res) => { + reached.push(`${req.method} ${req.url} ${req.headers['x-agent-device-token'] ?? ''}`); + req.resume(); + res.end('{}'); + }); + const daemon = await serve((req, res) => { + req.resume(); + res.statusCode = 307; + res.setHeader('location', `${target}${req.url}`); + res.end(); + }); + // A logical https URL a transport routes internally: here, global fetch to a loopback daemon, + // with the forwarded request's method, headers, body, and redirect mode. + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'https://daemon.example.test', + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + upstreamFetch: async (request) => + await fetch(`${daemon}${new URL(request.url).pathname}`, { + method: request.method, + headers: request.headers, + redirect: request.redirect, + ...(request.method === 'GET' ? {} : { body: await request.text() }), + }), + }); + + await ( + await proxy.handle(new Request('https://gateway.example.test/agent-device/health')) + ).text(); + expect((await proxy.handle(rpc())).status).toBeGreaterThanOrEqual(400); + + expect(reached).toEqual([]); +}); 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..13429d7e4e 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'); @@ -285,7 +285,9 @@ test('a custom transport receives every route family including transfers', async ).toBe(true); }); -test('admitted transfers use Node while RPC and diagnostics use Fetch', async () => { +// A plain-http upstream is loopback, and it goes direct over Node on every route, so neither a +// patched global fetch nor an environment proxy sees its token. +test('a plain-http upstream takes Node on every admitted route, never the global fetch', async () => { const daemon = await listen( http.createServer((req, res) => { req.resume(); @@ -331,8 +333,8 @@ test('admitted transfers use Node while RPC and diagnostics use Fetch', async () ); expect(response.status, path).toBe(200); await response.text(); - expect(node.mock.calls.length, path).toBe(transfer ? 1 : 0); - expect(fetch.mock.calls.length, path).toBe(transfer ? 0 : 1); + expect(node.mock.calls.length, `${path} transfer=${transfer}`).toBe(1); + expect(fetch.mock.calls.length, path).toBe(0); } for (const [method, path] of [ ['GET', '/upload'], diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index 5b650e942d..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/', @@ -685,27 +685,6 @@ test.each([ ).toThrow(); }); -test('the default transport refuses an upstream token for plain http off loopback at construction', () => { - let refusal: unknown; - try { - createDaemonProxy({ - upstreamBaseUrl: 'http://daemon.internal:4310', - upstreamToken: 'secret', - clientToken: 'client', - }); - } catch (error) { - refusal = error; - } - expect(refusal).toBeInstanceOf(AppError); - expect((refusal as AppError).details?.reason).toBe('insecure_credential_transport'); - - for (const upstreamBaseUrl of ['http://127.0.0.1:4310', 'https://daemon.internal']) { - expect(() => - createDaemonProxy({ upstreamBaseUrl, upstreamToken: 'secret', clientToken: 'client' }), - ).not.toThrow(); - } -}); - test('malformed successful tickets fail without exposing upstream credentials', async () => { const upstream = recordingUpstream(() => Response.json({ upload: { url: 'bad', headers: { authorization: 'secret' } } }), @@ -734,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( @@ -760,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 4c7f49f1d8..b39ed1c0ad 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -12,7 +12,6 @@ import { DAEMON_HTTP_NETWORK_ACCESS_HEADER, DAEMON_HTTP_PUBLIC_NETWORK_ACCESS, DAEMON_HTTP_TENANT_HEADER, - assertSecureCredentialTransport, buildDaemonHttpAuthHeaders, buildDaemonHttpUrl, isTenantOwnedSessionName, @@ -33,8 +32,10 @@ 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. + * `fetch` on `/rpc`, health and diagnostics; plain http goes direct, never through an environment + * proxy. Supply your own to reach the daemon over another transport, such as a WebSocket tunnel. + * Abort the exchange when `request.signal` aborts. Every request carries `redirect: 'error'`: + * never follow a redirect, because the request carries the upstream token. * * 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 @@ -67,8 +68,9 @@ export type DaemonProxyAuthenticate = ( export type DaemonProxyOptions = { /** - * Base URL of the upstream agent-device daemon HTTP server. Without `upstreamFetch` it must use - * https, or http on loopback, because every upstream request carries `upstreamToken`. + * 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`; 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. */ @@ -434,7 +436,7 @@ function keepAliveWith(owner: object, request: Request): Request { /** Builds a request for `owner` to send on, kept reachable for as long as `owner` is. */ 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: 'error' })); } function upstreamSignal(request: Request, options: NormalizedProxyOptions): AbortSignal { @@ -575,14 +577,28 @@ function rewriteUploadDirectUrl( function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOptions { const upstreamBaseUrl = normalizeBaseUrl(options.upstreamBaseUrl, 'upstreamBaseUrl'); const upstreamToken = normalizeToken(options.upstreamToken, 'upstreamToken'); - if (!options.upstreamFetch) { - assertSecureCredentialTransport(upstreamBaseUrl, 'Proxy upstreamBaseUrl'); - } const clientToken = options.authenticate ? undefined : normalizeToken(options.clientToken ?? '', 'clientToken'); - const upstreamFetch = options.upstreamFetch ?? ((request) => fetch(request)); + // Loaded on the first upstream exchange, never at module scope: the proxy entry stays lean. + let upstreamAdmission: Promise | undefined; + const admitUpstream = () => + (upstreamAdmission ??= import('@agent-device/contracts/credential-transport').then( + ({ assertSecureCredentialTransport }) => { + assertSecureCredentialTransport(upstreamBaseUrl, 'Proxy upstreamBaseUrl'); + }, + )); const customUpstreamFetch = options.upstreamFetch; + const sendUpstream: DaemonProxyUpstreamFetch = + customUpstreamFetch ?? + (async (request) => + new URL(request.url).protocol === 'http:' + ? await (await import('@agent-device/host-kit/direct-http')).fetchOverDirectHttp(request) + : await fetch(request)); + const upstreamFetch: DaemonProxyUpstreamFetch = async (request) => { + await admitUpstream(); + return await sendUpstream(request); + }; return { upstreamBaseUrl, publicOrigin: @@ -597,6 +613,7 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti upstreamFetch, upstreamTransport: async (route, request) => { if (!isTransferRoute(route, request.method)) return upstreamFetch(request); + await admitUpstream(); const { createNodeTransferFetch, settleUpstreamFetch } = await import('./transfer-transport.ts'); return customUpstreamFetch diff --git a/packages/proxy/src/node-http.test.ts b/packages/proxy/src/node-http.test.ts index 351ccc955e..5ead80c12a 100644 --- a/packages/proxy/src/node-http.test.ts +++ b/packages/proxy/src/node-http.test.ts @@ -149,7 +149,7 @@ test.each([undefined, 'https://public.example:8443'])( async (publicOrigin) => { 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/transfer-transport.ts b/packages/proxy/src/transfer-transport.ts index cd29348c5f..a956a3018e 100644 --- a/packages/proxy/src/transfer-transport.ts +++ b/packages/proxy/src/transfer-transport.ts @@ -25,7 +25,7 @@ const TRANSFER_FORWARDING_REASONS = { } as const satisfies ReasonTable<'proxy'>; const NULL_BODY_STATUSES = new Set([204, 205, 304]); -/** Forwards one exchange over the runtime's default global Node agent, without redirects or retries. */ +/** Forwards one exchange over `node:http(s)`, without redirects or retries; plain http never takes an environment proxy. */ export function createNodeTransferFetch(): (request: Request) => Promise { return async (request) => { const exchange = openExchange(request.signal); @@ -140,8 +140,12 @@ async function exchangeOverNodeHttp( exchange: TransferExchange, ): Promise { const url = new URL(request.url); - const [transport, { urlToHttpOptions }] = await untilAborted(exchange.signal, () => - Promise.all([loadNodeHttpRequester(url.protocol), import('node:url')]), + const [transport, agent, { urlToHttpOptions }] = await untilAborted(exchange.signal, () => + Promise.all([ + loadNodeHttpRequester(url.protocol), + import('@agent-device/host-kit/direct-http').then((m) => m.loadDirectHttpAgent(url.protocol)), + import('node:url'), + ]), ); exchange.signal.throwIfAborted(); const { auth: _auth, ...target } = urlToHttpOptions(url); @@ -151,6 +155,7 @@ async function exchangeOverNodeHttp( path: `${url.pathname}${url.search}`, headers: Object.fromEntries(request.headers), signal: exchange.signal, + agent, }; exchange.watchdog.arm('connect', TRANSFER_CONNECT_TIMEOUT_MS); return await new Promise((resolve, reject) => { diff --git a/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts b/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts index 76ff42db9f..d03b4520d4 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts @@ -5,7 +5,7 @@ import http from 'node:http'; import path from 'node:path'; import type { Duplex } from 'node:stream'; import { setTimeout as delay } from 'node:timers/promises'; -import { afterEach, test } from 'vitest'; +import { afterEach, test, vi } from 'vitest'; import { buildCompanionPayload, runCompanionTunnelProcessFromEnv, @@ -507,6 +507,28 @@ test('metro companion worker exits after non-retryable registration failure', as assert.equal(registerAttempts, 1); }); +test.for(['http://bridge.invalid', 'http:'])( + 'metro companion worker never sends its bearer token to %s and exits', + async (serverBaseUrl) => { + const sent: unknown[] = []; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { + sent.push(input); + return new Response(null, { status: 500 }); + }); + cleanupTasks.push(async () => fetchSpy.mockRestore()); + + const companion = startMetroCompanionWorker({ + bridgePort: 1, + localPort: 1, + serverBaseUrl, + unregisterPath: '/api/metro/companion/unregister', + }); + await companion.waitForExit('worker exit after the bridge URL was refused'); + + assert.deepEqual(sent, []); + }, +); + test('metro companion worker retries registration failures with retry-after delay', async () => { const bridgeSocketReady = createDeferred(); const registerAttemptTimes: number[] = []; 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..50b2cd9a42 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.ts @@ -23,6 +23,7 @@ import type { MetroTunnelResponseMessage, } from './metro-tunnel-messages.ts'; import { normalizeBaseUrl } from '../metro/base-url.ts'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; const COMPANION_REGISTER_TIMEOUT_MS = 5_000; const COMPANION_REGISTER_MAX_RETRY_DELAY_MS = 60_000; @@ -81,9 +82,12 @@ async function registerCompanion( options: CompanionTunnelWorkerOptions, ): Promise<{ wsUrl: string }> { const registerPath = resolveRegisterPath(options); + const registerUrl = bearerDestination( + `${normalizeBaseUrl(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)), @@ -159,6 +163,18 @@ function clampRetryDelay(delayMs: number): number { return Math.max(0, Math.min(COMPANION_REGISTER_MAX_RETRY_DELAY_MS, Math.ceil(delayMs))); } +/** The final URL a bearer request goes to, or a refusal no retry can fix. */ +function bearerDestination(url: string): URL { + try { + return assertSecureCredentialTransport(url, 'Metro companion bridge URL'); + } catch (error) { + throw new CompanionRegistrationError( + error instanceof Error ? error.message : String(error), + false, + ); + } +} + function nextRetryDelay(currentDelayMs: number): number { return Math.min(currentDelayMs * 2, COMPANION_REGISTER_MAX_RETRY_DELAY_MS); } @@ -167,7 +183,10 @@ async function unregisterCompanion(options: CompanionTunnelWorkerOptions): Promi const unregisterPath = resolveUnregisterPath(options); if (!unregisterPath) return; try { - await fetch(`${normalizeBaseUrl(options.serverBaseUrl)}${unregisterPath}`, { + const unregisterUrl = bearerDestination( + `${normalizeBaseUrl(options.serverBaseUrl)}${unregisterPath}`, + ); + await fetch(unregisterUrl, { method: 'POST', headers: createHeaders(options.serverBaseUrl, options.bearerToken), body: JSON.stringify(buildCompanionPayload(options)), diff --git a/packages/react-native/src/index-metro.test.ts b/packages/react-native/src/index-metro.test.ts index 721069e0cd..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,21 +422,30 @@ test('prepareMetroRuntime rejects incomplete proxy configuration', async () => { ); }); -test('prepareMetroRuntime refuses a bridge bearer token over plain http off loopback', async () => { - await assert.rejects( - () => - prepareMetroRuntime( - { - publicBaseUrl: 'https://sandbox.example.test', - proxyBaseUrl: 'http://proxy.example.test', - env: { AGENT_DEVICE_DAEMON_AUTH_TOKEN: TEST_TOKEN }, - }, - createTestHostEnvironment(), - ), - (error) => - error instanceof AppError && error.details?.reason === 'insecure_credential_transport', - ); -}); +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.ts b/packages/react-native/src/metro/client-metro.ts index c9077a31ac..1ffeef8db0 100644 --- a/packages/react-native/src/metro/client-metro.ts +++ b/packages/react-native/src/metro/client-metro.ts @@ -21,7 +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/daemon-http'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { ensureMetroCompanion } from '../companion/client-metro-companion.ts'; import type { MetroBridgeDescriptor, @@ -454,10 +454,15 @@ function isRetryableBridgeError(error: unknown): boolean { } async function configureMetroBridge(input: ProxyBridgeRequestOptions): Promise { + // Checked on the final URL, right before the bearer token is sent, and outside the retry. + const bridgeUrl = assertSecureCredentialTransport( + `${input.baseUrl}/api/metro/bridge`, + 'Metro bridge URL', + ); let response: Response; try { - response = await fetch(`${input.baseUrl}/api/metro/bridge`, { + response = await fetch(bridgeUrl, { method: 'POST', headers: createProxyHeaders(input.baseUrl, input.bearerToken), body: JSON.stringify({ diff --git a/packages/remote/src/__tests__/upload-client.test.ts b/packages/remote/src/__tests__/upload-client.test.ts index b8d919e151..5bdb8dcb43 100644 --- a/packages/remote/src/__tests__/upload-client.test.ts +++ b/packages/remote/src/__tests__/upload-client.test.ts @@ -382,7 +382,7 @@ test('uploadArtifact falls back to legacy upload when direct upload exceeds redi } }); -test('uploadArtifact never sends a credential-bearing ticket over plain http off loopback', async () => { +test('uploadArtifact never uses a ticket over plain http off loopback, whatever carries its credential', async () => { const content = 'cleartext-ticket'; const artifactPath = createTempFile('app.apk', content); const requests: string[] = []; @@ -395,8 +395,8 @@ test('uploadArtifact never sends a credential-bearing ticket over plain http off cacheHit: false, uploadId: 'cleartext-ticket', upload: { - url: 'http://ticket.invalid/upload/direct/cleartext-ticket', - headers: { authorization: `Bearer ${TEST_TOKEN}` }, + url: 'http://ticket.invalid/upload/direct/cleartext-ticket?signature=secret', + headers: {}, }, }); return; diff --git a/packages/remote/src/artifact-download.ts b/packages/remote/src/artifact-download.ts index 9d33ac57e1..96f9f4ec35 100644 --- a/packages/remote/src/artifact-download.ts +++ b/packages/remote/src/artifact-download.ts @@ -160,6 +160,9 @@ async function requestRemoteArtifact( }, ): Promise { const transport = await loadNodeHttpRequester(params.artifactUrl.protocol); + const agent = await ( + await import('@agent-device/host-kit/direct-http') + ).loadDirectHttpAgent(params.artifactUrl.protocol); await destination.prepare(); return await new Promise((resolve, reject) => { let settled = false; @@ -197,6 +200,7 @@ async function requestRemoteArtifact( port: params.artifactUrl.port, method: 'GET', path: params.artifactUrl.pathname + params.artifactUrl.search, + agent, headers: { ...buildDaemonHttpAuthHeaders(params.token), ...buildDaemonHttpTenantHeaders(params.requestScope?.tenantId), diff --git a/packages/remote/src/remote-request-diagnostics.ts b/packages/remote/src/remote-request-diagnostics.ts index 076c9535ce..bc3d635a15 100644 --- a/packages/remote/src/remote-request-diagnostics.ts +++ b/packages/remote/src/remote-request-diagnostics.ts @@ -147,6 +147,9 @@ async function fetchRemoteRequestDiagnostics(params: { } try { const transport = await loadNodeHttpRequester(url.protocol); + const agent = await ( + await import('@agent-device/host-kit/direct-http') + ).loadDirectHttpAgent(url.protocol); await fs.promises.mkdir(path.dirname(destinationPath), { recursive: true }); return await new Promise((resolve) => { let settled = false; @@ -169,6 +172,7 @@ async function fetchRemoteRequestDiagnostics(params: { port: url.port, method: 'GET', path: url.pathname + url.search, + agent, headers: { ...buildDaemonHttpAuthHeaders(endpoint.token), ...buildDaemonHttpTenantHeaders(endpoint.tenantId), diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index 4138dddd49..764d59724f 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -4,7 +4,6 @@ import { AppError } from '@agent-device/kernel/errors'; import { buildDaemonHttpAuthHeaders, buildDaemonHttpLeaseHeaders, - isSecureCredentialDestination, } from '@agent-device/contracts/daemon-http'; import { prepareUploadArtifact, type PreparedUploadArtifact } from './upload-client-artifact.ts'; import { @@ -318,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( @@ -331,13 +338,17 @@ async function requestUploadControl( watchdog.signal.throwIfAborted(); watchdog.arm(phase, UPLOAD_CONTROL_PLANE_TIMEOUT_MS); try { - // Redirects could forward the daemon token, so these control requests never follow them. - const response = await fetch(url, { + // Redirects could forward the daemon token, so these control requests never follow them. Plain + // http (loopback only) goes direct, never through an environment proxy. + const request = new Request(url, { ...init, method: 'POST', redirect: 'error', signal: watchdog.signal, }); + const response = await (url.protocol === 'http:' + ? (await import('@agent-device/host-kit/direct-http')).fetchOverDirectHttp(request) + : fetch(request)); const body: unknown = response.ok ? await response.json().catch(() => undefined) : undefined; watchdog.signal.throwIfAborted(); return { response, body }; @@ -372,12 +383,6 @@ function parseUploadPreflightResult(value: unknown): UploadPreflightResult | und if (!isStringRecord(headers)) { return undefined; } - // A ticket that would send a daemon credential over plain http off loopback is not usable; the - // upload takes the legacy route through the base URL the client already admitted. - if (carriesDaemonCredential(headers)) { - const ticketUrl = URL.parse(upload.url); - if (!ticketUrl || !isSecureCredentialDestination(ticketUrl)) return undefined; - } return { kind: 'direct-upload', uploadId: preflight.uploadId, @@ -386,16 +391,6 @@ function parseUploadPreflightResult(value: unknown): UploadPreflightResult | und }; } -const DAEMON_CREDENTIAL_HEADER_NAMES = new Set( - Object.keys(buildDaemonHttpAuthHeaders('credential')), -); - -function carriesDaemonCredential(headers: Record): boolean { - return Object.keys(headers).some((name) => - DAEMON_CREDENTIAL_HEADER_NAMES.has(name.toLowerCase()), - ); -} - function isStringRecord(value: unknown): value is Record { if (!value || typeof value !== 'object' || Array.isArray(value)) { return false; diff --git a/packages/remote/src/upload-stream.ts b/packages/remote/src/upload-stream.ts index 6b116d7111..7748b29d96 100644 --- a/packages/remote/src/upload-stream.ts +++ b/packages/remote/src/upload-stream.ts @@ -109,6 +109,9 @@ async function streamFileToHttpRequestAttempt(options: { // upload client, but only a remote daemon ever uploads, so the HTTP stack // loads here rather than at import time. const transport = await loadNodeHttpRequester(options.url.protocol); + const agent = await ( + await import('@agent-device/host-kit/direct-http') + ).loadDirectHttpAgent(options.url.protocol); const payloadSize = fs.statSync(options.payloadPath).size; const headers = buildUploadRequestHeaders(options.headers, options.startOffset, payloadSize); emitUploadAttemptStarted(options.progress, options.startOffset, payloadSize); @@ -134,6 +137,7 @@ async function streamFileToHttpRequestAttempt(options: { method: options.method, path: options.url.pathname + options.url.search, headers, + agent, // Aborting destroys the request mid-stream, which is the only way to stop bytes that are // already piped at a device this client no longer holds the lease on. signal: watchdog.signal, 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/__tests__/cloud-connect-profile.test.ts b/src/__tests__/cloud-connect-profile.test.ts index ef155269ca..9d93167ddb 100644 --- a/src/__tests__/cloud-connect-profile.test.ts +++ b/src/__tests__/cloud-connect-profile.test.ts @@ -400,6 +400,56 @@ for (const [status, code] of [ }); } +test('connect cloud never sends its bearer token to a plain http cloud off loopback', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-cloud-cleartext-'); + mockedResolveCloudAccessForConnect.mockResolvedValue({ + accessToken: 'adc_agent_cloud', + cloudBaseUrl: 'http://cloud.example', + }); + const fetchMock = vi.fn(async () => new Response('{}')); + vi.stubGlobal('fetch', fetchMock); + try { + await assert.rejects( + connectWithGeneratedCloudProfile(path.join(tempRoot, '.state')), + (error) => { + assert.equal(normalizeError(error).details?.reason, 'insecure_credential_transport'); + return true; + }, + ); + assert.equal(fetchMock.mock.calls.length, 0); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('connect cloud refuses a profile redirect to another origin before sending to it', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-cloud-redirect-'); + mockedResolveCloudAccessForConnect.mockResolvedValue({ + accessToken: 'adc_agent_cloud', + cloudBaseUrl: 'https://cloud.example', + }); + const fetchMock = vi.fn( + async () => + new Response(null, { status: 302, headers: { location: 'http://other.example/profile' } }), + ); + vi.stubGlobal('fetch', fetchMock); + try { + await assert.rejects( + connectWithGeneratedCloudProfile(path.join(tempRoot, '.state')), + (error) => { + assert.equal(normalizeError(error).details?.reason, 'cloud_auth_redirect_refused'); + return true; + }, + ); + assert.deepEqual( + fetchMock.mock.calls.map(([url]) => String(url)), + ['https://cloud.example/api/control-plane/connection-profile'], + ); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + test('connect without remote config reports unsupported cloud profile keys', async () => { const tempRoot = mkdtempForTestSync('agent-device-connect-cloud-invalid-'); const stateDir = path.join(tempRoot, '.state'); diff --git a/src/cli/cloud-auth-request.ts b/src/cli/cloud-auth-request.ts index 54edde9e7e..1d6c889066 100644 --- a/src/cli/cloud-auth-request.ts +++ b/src/cli/cloud-auth-request.ts @@ -1,5 +1,5 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; -import { assertSecureCredentialTransport } from '@agent-device/contracts/daemon-http'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { readCloudJsonResponse } from './cloud-response.ts'; const HTTP_TIMEOUT_MS = 15_000; @@ -30,30 +30,47 @@ export async function postCloudAuthJson(options: { // Passed to the response reader, which calls it on a status it would otherwise reject generically. classifyRejectedBody?: (parsed: unknown) => AppError | undefined; }): Promise { - const fetchImpl = options.fetchImpl ?? fetch; - const requestUrl = new URL(options.pathName, options.baseUrl); - assertSecureCredentialTransport(requestUrl, 'AGENT_DEVICE_CLOUD_BASE_URL'); - const post: RequestInit = { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify(options.body), - }; + const response = await fetchCloudOnOneOrigin( + new URL(options.pathName, options.baseUrl), + { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(options.body), + }, + options.fetchImpl, + ); + return await readCloudJsonResponse(response, { + invalidJsonMessage: `Cloud auth endpoint returned invalid JSON (${response.status}).`, + rejectedMessage: 'Cloud auth endpoint rejected the request.', + classifyRejectedBody: options.classifyRejectedBody, + }); +} + +/** + * Sends one credential-bearing cloud request and returns the final answer. The URL must be https, + * or plain http to loopback. A redirect is followed only to the same origin, at most three times, + * and never to a target with a username or password. A 301, 302 or 303 turns a POST into a GET + * without its body or headers; a GET keeps its headers on the same origin. + */ +export async function fetchCloudOnOneOrigin( + requestUrl: URL, + request: RequestInit, + // di-seam-approved: the same fetch-global seam as postCloudAuthJson's fetchImpl. + fetchImpl: typeof fetch = fetch, +): Promise { + assertSecureCredentialTransport(requestUrl, 'Cloud base URL'); // One timeout covers the whole redirect chain. const signal = AbortSignal.timeout(HTTP_TIMEOUT_MS); let url = requestUrl; - let init = post; + let init = request; for (let redirects = 0; ; redirects += 1) { const response = await fetchImpl(url, { ...init, redirect: 'manual', signal }); - if (!REDIRECT_STATUSES.has(response.status)) { - return await readCloudJsonResponse(response, { - invalidJsonMessage: `Cloud auth endpoint returned invalid JSON (${response.status}).`, - rejectedMessage: 'Cloud auth endpoint rejected the request.', - classifyRejectedBody: options.classifyRejectedBody, - }); - } + if (!REDIRECT_STATUSES.has(response.status)) return response; await response.body?.cancel().catch(() => undefined); url = readRedirectTarget(response, url, requestUrl, redirects); - if (GET_REDIRECT_STATUSES.has(response.status)) init = { method: 'GET' }; + if (GET_REDIRECT_STATUSES.has(response.status) && init.method !== 'GET') { + init = { method: 'GET' }; + } } } diff --git a/src/cli/connection/cloud-profile.ts b/src/cli/connection/cloud-profile.ts index fe58324e96..2eda7117ec 100644 --- a/src/cli/connection/cloud-profile.ts +++ b/src/cli/connection/cloud-profile.ts @@ -4,12 +4,12 @@ import type { CliFlags } from '@agent-device/contracts/command'; 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'; +import { fetchCloudOnOneOrigin } from '../cloud-auth-request.ts'; import { readCloudJsonResponse } from '../cloud-response.ts'; import { persistAndResolveGeneratedProfile } from './generated-config.ts'; import { buildConnectClientId } from './client-id.ts'; const CONNECTION_PROFILE_PATH = '/api/control-plane/connection-profile'; -const HTTP_TIMEOUT_MS = 15_000; type CloudConnectionProfileResponse = { connection?: { @@ -71,12 +71,11 @@ async function fetchConnectionProfile(options: { // on the request itself. fetchImpl?: typeof fetch; }): Promise { - const fetchImpl = options.fetchImpl ?? fetch; - const response = await fetchImpl(new URL(CONNECTION_PROFILE_PATH, options.cloudBaseUrl), { - method: 'GET', - headers: { authorization: `Bearer ${options.accessToken}` }, - signal: AbortSignal.timeout(HTTP_TIMEOUT_MS), - }); + const response = await fetchCloudOnOneOrigin( + new URL(CONNECTION_PROFILE_PATH, options.cloudBaseUrl), + { method: 'GET', headers: { authorization: `Bearer ${options.accessToken}` } }, + options.fetchImpl, + ); const parsed = await readCloudJsonResponse(response, { invalidJsonMessage: `Cloud connection profile endpoint returned invalid JSON (${response.status}).`, rejectedMessage: 'Cloud connection profile endpoint rejected the request.', 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..6cd19ac844 100644 --- a/src/core/interactors/limrun-ios-files.ts +++ b/src/core/interactors/limrun-ios-files.ts @@ -9,6 +9,7 @@ import { import type { LimrunRuntimeDependencies } from '@agent-device/provider-limrun'; import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import { downloadLimrunFile } from '../limrun-download-file.ts'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; type Session = Parameters[0]; type Files = AppleToolProvider['simulatorFiles']; @@ -63,7 +64,7 @@ export function createLimrunSimulatorFiles( }; const request = async (method: string, url: URL, signal: AbortSignal, body?: Uint8Array) => { signal.throwIfAborted(); - const response = await fetch(url, { + const response = await fetch(assertSecureCredentialTransport(url, 'Limrun API URL'), { method, headers: { Authorization: `Bearer ${session.token}`, diff --git a/src/core/interactors/limrun-ios-runner-products.ts b/src/core/interactors/limrun-ios-runner-products.ts index 3e947191c6..8eacc58510 100644 --- a/src/core/interactors/limrun-ios-runner-products.ts +++ b/src/core/interactors/limrun-ios-runner-products.ts @@ -13,6 +13,7 @@ import { createGzip } from 'node:zlib'; import { extractArchiveSafely } from '@agent-device/host-kit/archive'; import { escapeXmlTextAndAttribute } from '@agent-device/xml'; import { downloadLimrunFile } from '../limrun-download-file.ts'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; /** Stages the version-matched release runner, or an explicitly supplied development build. */ export async function prepareLimrunRunnerProducts(input: { @@ -249,18 +250,21 @@ export async function uploadLimrunRunnerProducts( const stream = createGzip(); const compression = pipeline(Readable.from(body()), stream, { signal }).catch(() => {}); try { - const response = await fetch(`${apiUrl}/sync`, { - method: 'POST', - headers: { - Authorization: `Bearer ${token}`, - 'Content-Type': 'application/octet-stream', - 'Content-Encoding': 'gzip', - }, - body: Readable.toWeb(stream) as ReadableStream, - duplex: 'half', - signal, - redirect: 'error', - } as RequestInit & { duplex: 'half' }); + const response = await fetch( + assertSecureCredentialTransport(`${apiUrl}/sync`, 'Limrun API URL'), + { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/octet-stream', + 'Content-Encoding': 'gzip', + }, + body: Readable.toWeb(stream) as ReadableStream, + duplex: 'half', + signal, + redirect: 'error', + } as RequestInit & { duplex: 'half' }, + ); if (!response.ok) { await response.body?.cancel(); throw limrunRunnerError( diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index 324128028c..70bb94df22 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -200,3 +200,20 @@ test.each(['default', 'typed', 'deadline'] as const)( expect(fs.existsSync(destinationPath)).toBe(false); }, ); + +test('a provider download URL over plain http off loopback never receives the bearer token', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch'); + try { + await expect( + downloadLimrunFile({ + url: 'http://limrun.invalid/files?name=recording.mp4', + headers: { Authorization: 'Bearer instance-token' }, + destinationPath: path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'), + timeoutMs: 5_000, + }), + ).rejects.toMatchObject({ details: { reason: 'insecure_credential_transport' } }); + expect(fetchSpy).not.toHaveBeenCalled(); + } finally { + fetchSpy.mockRestore(); + } +}); diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index de48670507..7794405751 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -9,6 +9,7 @@ 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; @@ -29,6 +30,10 @@ const LIMRUN_DOWNLOAD_REASONS = { * same URL and never mistakes an earlier attempt's file for this one's. */ export async function downloadLimrunFile(options: LimrunFileDownload): Promise { + // The URL comes from the provider, and the headers carry its bearer token. + if (options.headers && Object.keys(options.headers).length > 0) { + assertSecureCredentialTransport(options.url, 'Limrun download URL'); + } const timeout = AbortSignal.timeout(options.timeoutMs); const signal = options.signal ? AbortSignal.any([timeout, options.signal]) : timeout; try { diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index a7beaea6a8..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 https://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`). 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-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/error-reasons.md b/website/docs/docs/error-reasons.md index 776636c8ce..917b00dafa 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -899,7 +899,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `insecure_credential_transport` | A daemon, proxy, host bridge, or cloud auth credential would travel over plain http to a host that is not loopback. `details.origin` names the refused destination. | +| `insecure_credential_transport` | A credential would travel over plain http to a host that is not loopback, or to a URL that does not parse. `details.origin` names the refused destination when it parses. | | `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/security-trust.md b/website/docs/docs/security-trust.md index 5f1fc00cb1..5424b35c6f 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -21,7 +21,7 @@ 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. -A client never sends a daemon, proxy, Metro host bridge, or cloud auth credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. The proxy applies the same rule to its upstream daemon URL unless you supply your own `upstreamFetch` transport. +A client never sends a daemon, proxy, Metro host bridge, or cloud auth credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, such as Limrun API and download URLs, are checked right before each request. 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. From cdbb0aedc3699bca19ed323086eb98db89d144dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 13:38:19 +0100 Subject: [PATCH 03/22] fix(remote): satisfy the layering, lint, and coverage gates - declare the host-kit direct-http subpath in the pinned export surface - new tests use plain node:http servers where test-kit is not a dependency, and are named for the module they cover (R84) - move the new upload-ticket and connect-cloud cases into focused files under the max-lines cap; type the fetch stub's input - the upload cancellation test replaces the direct-http send, the seam loopback control requests now use - pass string URLs to fetch where callers compare them Co-Authored-By: Claude Opus 5.5 --- ...mon-client-lifecycle-remote-trust.test.ts} | 0 packages/host-kit/src/direct-http.test.ts | 16 +++- .../daemon-proxy-credential-transport.test.ts | 16 +++- .../client-companion-tunnel-worker.ts | 5 +- .../react-native/src/metro/client-metro.ts | 6 +- .../upload-client-cancellation.test.ts | 36 ++++++-- .../upload-client-ticket-transport.test.ts | 58 ++++++++++++ .../src/__tests__/upload-client.test.ts | 36 -------- scripts/layering/package-boundaries.test.ts | 2 + src/__tests__/cloud-connect-profile.test.ts | 50 ----------- .../cloud-profile-transport.test.ts | 88 +++++++++++++++++++ .../interactors/limrun-ios-runner-products.ts | 29 +++--- 12 files changed, 223 insertions(+), 119 deletions(-) rename packages/daemon-client/src/__tests__/{daemon-client-remote-transport-security.test.ts => daemon-client-lifecycle-remote-trust.test.ts} (100%) create mode 100644 packages/remote/src/__tests__/upload-client-ticket-transport.test.ts create mode 100644 src/cli/connection/cloud-profile-transport.test.ts diff --git a/packages/daemon-client/src/__tests__/daemon-client-remote-transport-security.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts similarity index 100% rename from packages/daemon-client/src/__tests__/daemon-client-remote-transport-security.test.ts rename to packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts diff --git a/packages/host-kit/src/direct-http.test.ts b/packages/host-kit/src/direct-http.test.ts index ca883749d4..0a3aaaf886 100644 --- a/packages/host-kit/src/direct-http.test.ts +++ b/packages/host-kit/src/direct-http.test.ts @@ -3,14 +3,24 @@ import { execFile } from 'node:child_process'; import http from 'node:http'; import path from 'node:path'; import { promisify } from 'node:util'; -import { closeLoopbackServer, listenOnLoopback } from '@agent-device/test-kit'; +import type { AddressInfo } from 'node:net'; // A credential sent over plain http goes only to loopback, and an environment proxy on another host // would read it in cleartext. Node reads `NODE_USE_ENV_PROXY` at startup, so each case runs a child. +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 () => { - await Promise.all(servers.splice(0).map((server) => closeLoopbackServer(server))); + await Promise.all(servers.splice(0).map((server) => closeLocal(server))); }); async function serve(seen: string[]): Promise { @@ -19,7 +29,7 @@ async function serve(seen: string[]): Promise { res.end('ok'); }); servers.push(server); - return await listenOnLoopback(server); + return await listenLocal(server); } const TRANSPORT = path.join(import.meta.dirname, 'direct-http.ts'); diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index ffb80ad1e2..bd61fa8cc7 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -4,19 +4,29 @@ import { afterEach, expect, test, vi } from 'vitest'; import http from 'node:http'; import https from 'node:https'; -import { closeLoopbackServer, listenOnLoopback } from '@agent-device/test-kit'; +import type { AddressInfo } from 'node:net'; 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) => closeLoopbackServer(server))); + 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 listenOnLoopback(server)}`; + return `http://127.0.0.1:${await listenLocal(server)}`; } const rpc = () => 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 50b2cd9a42..3e94c7ea10 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.ts @@ -164,9 +164,10 @@ function clampRetryDelay(delayMs: number): number { } /** The final URL a bearer request goes to, or a refusal no retry can fix. */ -function bearerDestination(url: string): URL { +function bearerDestination(url: string): string { try { - return assertSecureCredentialTransport(url, 'Metro companion bridge URL'); + assertSecureCredentialTransport(url, 'Metro companion bridge URL'); + return url; } catch (error) { throw new CompanionRegistrationError( error instanceof Error ? error.message : String(error), diff --git a/packages/react-native/src/metro/client-metro.ts b/packages/react-native/src/metro/client-metro.ts index 1ffeef8db0..fb98adfc24 100644 --- a/packages/react-native/src/metro/client-metro.ts +++ b/packages/react-native/src/metro/client-metro.ts @@ -455,10 +455,8 @@ function isRetryableBridgeError(error: unknown): boolean { async function configureMetroBridge(input: ProxyBridgeRequestOptions): Promise { // Checked on the final URL, right before the bearer token is sent, and outside the retry. - const bridgeUrl = assertSecureCredentialTransport( - `${input.baseUrl}/api/metro/bridge`, - 'Metro bridge URL', - ); + const bridgeUrl = `${input.baseUrl}/api/metro/bridge`; + assertSecureCredentialTransport(bridgeUrl, 'Metro bridge URL'); let response: Response; try { diff --git a/packages/remote/src/__tests__/upload-client-cancellation.test.ts b/packages/remote/src/__tests__/upload-client-cancellation.test.ts index 573e8c2911..22b9950881 100644 --- a/packages/remote/src/__tests__/upload-client-cancellation.test.ts +++ b/packages/remote/src/__tests__/upload-client-cancellation.test.ts @@ -18,10 +18,26 @@ import { uploadArtifact } from '../upload-client.ts'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { observeOutcome } from './support/upload-transfer-fixtures.ts'; +// Control requests to a plain-http (loopback) daemon go direct over `node:http`, never through an +// environment proxy, so that send is the control-plane seam these cases replace. +const directHttp = vi.hoisted(() => ({ + send: undefined as ((request: Request) => Promise) | undefined, +})); +vi.mock('@agent-device/host-kit/direct-http', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + fetchOverDirectHttp: vi.fn(async (request: Request) => + directHttp.send ? await directHttp.send(request) : await actual.fetchOverDirectHttp(request), + ), + }; +}); + const TEST_TOKEN = 'agent-device-upload-cancel-token'; const tempDirs: string[] = []; afterEach(async () => { + directHttp.send = undefined; vi.restoreAllMocks(); vi.useRealTimers(); for (const dir of tempDirs) { @@ -37,6 +53,8 @@ test('cancellation refuses preparation before it reads a missing artifact', asyn const reason = new Error('request owner stopped'); control.abort(reason); const fetch = vi.spyOn(globalThis, 'fetch'); + const direct = vi.fn(async () => new Response(null, { status: 500 })); + directHttp.send = direct; await assert.rejects( uploadArtifact({ env: process.env, @@ -48,6 +66,7 @@ test('cancellation refuses preparation before it reads a missing artifact', asyn (error: unknown) => error === reason, ); assert.equal(fetch.mock.calls.length, 0); + assert.equal(direct.mock.calls.length, 0); }); test('a standalone upload expires its preparation aggregate during hashing without starting a request', async () => { @@ -56,6 +75,8 @@ test('a standalone upload expires its preparation aggregate during hashing witho const hashSource = new PassThrough(); vi.spyOn(fs, 'createReadStream').mockReturnValue(hashSource as unknown as fs.ReadStream); const fetch = vi.spyOn(globalThis, 'fetch'); + const direct = vi.fn(async () => new Response(null, { status: 500 })); + directHttp.send = direct; const outcome = uploadArtifact({ env: process.env, localPath: artifactPath, @@ -73,6 +94,8 @@ test('a standalone upload expires its preparation aggregate during hashing witho }); assert.equal(hashSource.destroyed, true); assert.equal(fetch.mock.calls.length, 0); + assert.equal(direct.mock.calls.length, 0); + assert.equal(direct.mock.calls.length, 0); } finally { hashSource.destroy(); await outcome; @@ -116,12 +139,13 @@ test.each([ let stalledSignal: AbortSignal | undefined; let preflights = 0; let refuseStall: ((error: Error) => void) | undefined; - const fetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { - const route = new URL(String(input)).pathname; + let controlRequests = 0; + directHttp.send = async (request) => { + controlRequests += 1; + const route = new URL(request.url).pathname; if (route.endsWith('/preflight')) preflights += 1; if (route.endsWith('/' + phase) && (!retry || preflights === 2)) { - const signal = init?.signal; - assert.ok(signal); + const signal = request.signal; stalledSignal = signal; entered(); if (prose) throw new Error(`Artifact transfer ${phase} timed out`); @@ -135,7 +159,7 @@ test.each([ uploadId: 'control-upload', upload: { url: `${server.baseUrl}/ticket`, headers: {} }, }); - }); + }; const outcome = observeOutcome( uploadArtifact({ env: process.env, @@ -181,7 +205,7 @@ test.each([ routes, Array.from({ length: expectedTicketLegs }, () => 'PUT /ticket'), ); - assert.equal(fetch.mock.calls.length, 1 + expectedTicketLegs); + assert.equal(controlRequests, 1 + expectedTicketLegs); } finally { caller.abort(new Error('fixture cleanup')); refuseStall?.(new Error('fixture cleanup')); diff --git a/packages/remote/src/__tests__/upload-client-ticket-transport.test.ts b/packages/remote/src/__tests__/upload-client-ticket-transport.test.ts new file mode 100644 index 0000000000..ff7608e30f --- /dev/null +++ b/packages/remote/src/__tests__/upload-client-ticket-transport.test.ts @@ -0,0 +1,58 @@ +// An upload ticket can carry a credential in its headers, a cookie, or its query, so a ticket over +// plain http to a host that is not loopback is never used; the upload takes the legacy route. + +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import http, { type IncomingMessage } from 'node:http'; +import path from 'node:path'; +import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import { uploadArtifact } from '../upload-client.ts'; + +async function readRequestBody(req: IncomingMessage): 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/__tests__/upload-client.test.ts b/packages/remote/src/__tests__/upload-client.test.ts index 5bdb8dcb43..0b57ce1fdb 100644 --- a/packages/remote/src/__tests__/upload-client.test.ts +++ b/packages/remote/src/__tests__/upload-client.test.ts @@ -382,42 +382,6 @@ test('uploadArtifact falls back to legacy upload when direct upload exceeds redi } }); -test('uploadArtifact never uses a ticket over plain http off loopback, whatever carries its credential', async () => { - const content = 'cleartext-ticket'; - const artifactPath = createTempFile('app.apk', content); - const requests: string[] = []; - const server = await startServer(async (req, res) => { - requests.push(`${req.method} ${req.url}`); - await readRequestBody(req); - if (req.url === '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/upload/preflight') { - sendJson(res, { - ok: true, - cacheHit: false, - uploadId: 'cleartext-ticket', - upload: { - url: 'http://ticket.invalid/upload/direct/cleartext-ticket?signature=secret', - headers: {}, - }, - }); - return; - } - sendJson(res, { ok: true, uploadId: 'legacy-upload' }); - }); - - try { - const uploadId = await uploadArtifact({ - localPath: artifactPath, - baseUrl: server.baseUrl, - token: TEST_TOKEN, - }); - // 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 server.close(); - } -}); - test('uploadArtifact uses direct upload ticket and finalize flow', async () => { const content = 'direct-upload-apk'; const artifactPath = createTempFile('app.apk', content); diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index cb6a890b37..72eaf37fdf 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -612,6 +612,8 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/host-kit/code-signature-cache', '@agent-device/host-kit/command', '@agent-device/host-kit/diagnostics', + // Loaded at send time: a direct connection for credential-bearing plain-http requests. + '@agent-device/host-kit/direct-http', '@agent-device/host-kit/doctor-lines', '@agent-device/host-kit/file', '@agent-device/host-kit/gzip-tar', diff --git a/src/__tests__/cloud-connect-profile.test.ts b/src/__tests__/cloud-connect-profile.test.ts index 9d93167ddb..ef155269ca 100644 --- a/src/__tests__/cloud-connect-profile.test.ts +++ b/src/__tests__/cloud-connect-profile.test.ts @@ -400,56 +400,6 @@ for (const [status, code] of [ }); } -test('connect cloud never sends its bearer token to a plain http cloud off loopback', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-cloud-cleartext-'); - mockedResolveCloudAccessForConnect.mockResolvedValue({ - accessToken: 'adc_agent_cloud', - cloudBaseUrl: 'http://cloud.example', - }); - const fetchMock = vi.fn(async () => new Response('{}')); - vi.stubGlobal('fetch', fetchMock); - try { - await assert.rejects( - connectWithGeneratedCloudProfile(path.join(tempRoot, '.state')), - (error) => { - assert.equal(normalizeError(error).details?.reason, 'insecure_credential_transport'); - return true; - }, - ); - assert.equal(fetchMock.mock.calls.length, 0); - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); - -test('connect cloud refuses a profile redirect to another origin before sending to it', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-cloud-redirect-'); - mockedResolveCloudAccessForConnect.mockResolvedValue({ - accessToken: 'adc_agent_cloud', - cloudBaseUrl: 'https://cloud.example', - }); - const fetchMock = vi.fn( - async () => - new Response(null, { status: 302, headers: { location: 'http://other.example/profile' } }), - ); - vi.stubGlobal('fetch', fetchMock); - try { - await assert.rejects( - connectWithGeneratedCloudProfile(path.join(tempRoot, '.state')), - (error) => { - assert.equal(normalizeError(error).details?.reason, 'cloud_auth_redirect_refused'); - return true; - }, - ); - assert.deepEqual( - fetchMock.mock.calls.map(([url]) => String(url)), - ['https://cloud.example/api/control-plane/connection-profile'], - ); - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); - test('connect without remote config reports unsupported cloud profile keys', async () => { const tempRoot = mkdtempForTestSync('agent-device-connect-cloud-invalid-'); const stateDir = path.join(tempRoot, '.state'); 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..f0cc71c749 --- /dev/null +++ b/src/cli/connection/cloud-profile-transport.test.ts @@ -0,0 +1,88 @@ +// `connect cloud` sends its bearer token to the cloud profile endpoint only over https (or plain +// http to loopback), and never follows a redirect to another origin. + +import { afterEach, test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +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, + createTestHostEnvironment, + mkdtempForTestSync, +} from '@agent-device/test-kit'; + +bindTestCommandHost(); + +vi.mock('../auth-session.ts', async (importOriginal) => ({ + ...(await importOriginal()), + resolveCloudAccessForConnect: vi.fn(), +})); + +afterEach(() => { + vi.clearAllMocks(); + vi.unstubAllGlobals(); +}); + +async function connectCloud(stateDir: string): Promise { + const stdoutCapture = beginStdoutCapture(); + try { + await connectCommand({ + host: createTestHostEnvironment(), + positionals: [], + flags: { json: true, help: false, version: false, stateDir }, + client: {} as AgentDeviceClient, + }); + } finally { + stdoutCapture.restore(); + } +} + +async function connectCloudAt( + cloudBaseUrl: string, + answer: () => Response, +): Promise<{ reason: unknown; urls: string[] }> { + const tempRoot = mkdtempForTestSync('agent-device-connect-cloud-transport-'); + vi.mocked(resolveCloudAccessForConnect).mockResolvedValue({ + accessToken: 'adc_agent_cloud', + cloudBaseUrl, + }); + const urls: string[] = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL | Request) => { + urls.push(String(input instanceof Request ? input.url : input)); + return answer(); + }), + ); + try { + const refusal = await connectCloud(path.join(tempRoot, '.state')).then( + () => assert.fail('expected connect cloud to be refused'), + (error: unknown) => error, + ); + return { reason: normalizeError(refusal).details?.reason, urls }; + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +} + +test('connect cloud never sends its bearer token to a plain http cloud off loopback', async () => { + const { reason, urls } = await connectCloudAt('http://cloud.example', () => new Response('{}')); + + assert.equal(reason, 'insecure_credential_transport'); + assert.deepEqual(urls, []); +}); + +test('connect cloud refuses a profile redirect to another origin before sending to it', async () => { + const { reason, urls } = await connectCloudAt( + 'https://cloud.example', + () => new Response(null, { status: 302, headers: { location: 'http://other.example/x' } }), + ); + + assert.equal(reason, 'cloud_auth_redirect_refused'); + assert.deepEqual(urls, ['https://cloud.example/api/control-plane/connection-profile']); +}); diff --git a/src/core/interactors/limrun-ios-runner-products.ts b/src/core/interactors/limrun-ios-runner-products.ts index 8eacc58510..18c552247e 100644 --- a/src/core/interactors/limrun-ios-runner-products.ts +++ b/src/core/interactors/limrun-ios-runner-products.ts @@ -247,24 +247,23 @@ export async function uploadLimrunRunnerProducts( for (const file of payloads) yield* createReadStream(path.join(directory, file.path), { signal }); } + const syncUrl = `${apiUrl}/sync`; + assertSecureCredentialTransport(syncUrl, 'Limrun API URL'); const stream = createGzip(); const compression = pipeline(Readable.from(body()), stream, { signal }).catch(() => {}); try { - const response = await fetch( - assertSecureCredentialTransport(`${apiUrl}/sync`, 'Limrun API URL'), - { - method: 'POST', - headers: { - Authorization: `Bearer ${token}`, - 'Content-Type': 'application/octet-stream', - 'Content-Encoding': 'gzip', - }, - body: Readable.toWeb(stream) as ReadableStream, - duplex: 'half', - signal, - redirect: 'error', - } as RequestInit & { duplex: 'half' }, - ); + const response = await fetch(syncUrl, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/octet-stream', + 'Content-Encoding': 'gzip', + }, + body: Readable.toWeb(stream) as ReadableStream, + duplex: 'half', + signal, + redirect: 'error', + } as RequestInit & { duplex: 'half' }); if (!response.ok) { await response.body?.cancel(); throw limrunRunnerError( From 94582ba0afa60260fb15d0668d388567bccbda52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 13:43:05 +0100 Subject: [PATCH 04/22] chore(wire-compat): acknowledge the direct-connection transport changes Six wire-surface request builders changed only how a request reaches the daemon: plain-http (loopback) destinations take a direct node:http agent that bypasses environment proxies, upload control requests to loopback use node:http instead of fetch, and preflight drops a ticket URL that is plain http off loopback (the legacy route a released daemon already serves). Method, path, headers and bodies are unchanged, so the ledger records the new digests with compatibleChanges entries; the existing acks for five of them carry the new digest and an appended rationale. Co-Authored-By: Claude Opus 5.5 --- test/wire-compat/ledger.json | 37 ++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 72f5ee3432..3a50a1de07 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,7 +71,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealth": "sha256:1ff542dadff6d92233c464b7d09052d809f36186bb60acdb572c48bfc1eb5c1f", "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealthLink": "sha256:96a79a8ff5a078916ee7bffed1d9624d0ba9c0dcbd8e2c55f9abf37fccfef744", "packages/daemon-client/src/daemon-client-transport.ts#isHealthService": "sha256:ffd2c774e0efca5e5d2b01f9d37fe9b76aaf5e7569e07d9208fe667473771c10", - "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth": "sha256:6ce1f9be1e6a977130d0875003ac22da2de5e90b514a3b22b30b9347e63d81c7", + "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth": "sha256:bf1a8cf8a234738d16a9582ded2120a738e1900c03c43e1bef70a7f947f561d8", "packages/daemon-client/src/daemon-client-transport.ts#readHealthLink": "sha256:c4f638b4df43f572e105b6f8df578fe90ebf64cb56002e4d029a109bdbc167d1", "packages/daemon-client/src/daemon-client-transport.ts#readHealthPayload": "sha256:4e85ffc3e35e02379c393e9312344757e003cf1f0ad9eb8d1f77d90c81c861f1", "packages/daemon-client/src/daemon-client-transport.ts#readHealthVersion": "sha256:856bd74aa8b2f205b6b30855755f16391015bffc1b6a323f618b51c26e749bfd", @@ -165,7 +165,7 @@ "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint": "sha256:c1d5fe2fe90c425502cf8b7c87d6606374d6af65b4e9faf942a416f683930bdc", "packages/remote/src/remote-request-diagnostics.ts#buildRemoteRequestDiagnosticsUrl": "sha256:30a1a9bf0df24d3564a616699916a3bb4360c2b4d21c4ad0562fb0c1e738d0a9", - "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics": "sha256:6f68c317e4c0fe5de008ec1fe5e7e030a9d298ad4a7dfd561db933d22e12ae9e", + "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics": "sha256:3d704fc10c2a2132bc064301efcc89fb0df86b657897fbbe1c37ba76e3cb8272", "packages/remote/src/remote-request-diagnostics.ts#localizeRemoteDaemonError": "sha256:35cfa186ad64663ae4dbb4e102d49238532cd7e3b75e8337edcc3d1fd77f92d5", "packages/remote/src/upload-client-artifact.ts#PreparedUploadArtifact": "sha256:5c40027d47feda3c946e836372b9f08ad866ab1612708b0d506551545f931ea4", "packages/remote/src/upload-client.ts#ARTIFACT_HASH_ALGORITHM": "sha256:328c135ea5f9d89fd2c142b440d5402a61d19f9044bf0504dfc2c525e58c1909", @@ -175,8 +175,8 @@ "packages/remote/src/upload-client.ts#finalizeDirectUpload": "sha256:ca3fa667ab2a60fb8af095bddeacb4875dcd2d12db783585a0fb045db35da212", "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#requestUploadControl": "sha256:86e2a092caf2aef3404957eb4abba9dc35ac6e68eea99448085da3c927f24a45", + "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", @@ -190,7 +190,7 @@ "packages/remote/src/upload-stream.ts#parseNonNegativeIntegerHeader": "sha256:5cbe9c6994459d673d988a51407e65556e28175b187ce0a9d27cbb6331962834", "packages/remote/src/upload-stream.ts#parseUploadResumeOffset": "sha256:297184ea22a6dc1cda9aee17034122ae0ea2f43d0355647f6fcf02f3f4b5ca0e", "packages/remote/src/upload-stream.ts#streamFileToHttpRequest": "sha256:c2b5e1369c8b1c9420036e23163d21e43fa2ac8b889c6a8f028cc6095055a16f", - "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt": "sha256:53ea451d23e3c260177368080b8989715f915f85a2c7d907bcc59c72248c8db8", + "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt": "sha256:0e93634d9e22fa6f3017aa98f880170ee5e57423acd8883373bf96de9c62b3d6", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_INSTANCE_HEADER": "sha256:d2bb3f4846470188a0fc1724271da0f0bcbdf2337bd6bf331508142cadcb65d8", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER": "sha256:4564c2ce437d30d7a823e3326f4375c0750ba8d42bec22b4d02e8eb7f7db2973", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_INSTANCE_MISMATCH_HEADER": "sha256:a197edaf7f9fa94a6aab269856aa852da3204cc586f5fd23198689eb11908b61", @@ -256,7 +256,7 @@ "packages/remote/src/artifact-download.ts#RemoteArtifactRequest": "sha256:6cce66499f34bb18139917df592e554395936964025089024d6c6f67e4fa4b98", "packages/remote/src/artifact-download.ts#RemoteArtifactFetch": "sha256:e83939ec48a66917df9ec84becf53b6ca3c8115cfdada10731046381ac9e32c1", "packages/remote/src/artifact-download.ts#fetchRemoteArtifactFromUrl": "sha256:de6e71abdc758f760beffba0dc260473f88a8c60b13540b9c14d39f1a3d5e3a1", - "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:cafb5fd5838819719b2fac62c5e108276dd800a58b4614462d138cf1ed2f7d6e", + "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:9777ec47aa972b81181a6ba3c2325c816c2a7a443c095c635f48d7451369453a", "packages/daemon-client/src/daemon-client-checked-rpc.ts#isCheckedRpcOutcomeResponse": "sha256:75fb9f3444a3f8f4a762811ba7cbe02d92a39ed4e55483ea0cf7f029e5720a3e", "packages/daemon-client/src/daemon-client-checked-rpc.ts#CheckedRpcOutcome": "sha256:8aa7e58307417460bb54938f6bbbd340254e14ffbbaf2093272996909592f7be", "packages/daemon-client/src/daemon-client-checked-rpc.ts#ReadHealthLink": "sha256:86a9e6f1ebdaecca3ddaa16081c221321c01c684b70197961ecd71a3f54a464f", @@ -464,8 +464,8 @@ }, { "declaration": "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth", - "digest": "sha256:6ce1f9be1e6a977130d0875003ac22da2de5e90b514a3b22b30b9347e63d81c7", - "rationale": "The health-probe budget includes requester loading and response completion. The caller AbortSignal joins the probe timer only in-process; caller cancellation remains distinct from probe expiry. No signal, timedOut flag, request route, auth header or accepted health payload field changes on the wire, so released daemons and proxies parse and respond as before (ADR 0006)." + "digest": "sha256:bf1a8cf8a234738d16a9582ded2120a738e1900c03c43e1bef70a7f947f561d8", + "rationale": "The health-probe budget includes requester loading and response completion. The caller AbortSignal joins the probe timer only in-process; caller cancellation remains distinct from probe expiry. No signal, timedOut flag, request route, auth header or accepted health payload field changes on the wire, so released daemons and proxies parse and respond as before (ADR 0006). #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." }, { "declaration": "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint", @@ -474,8 +474,8 @@ }, { "declaration": "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics", - "digest": "sha256:6f68c317e4c0fe5de008ec1fe5e7e030a9d298ad4a7dfd561db933d22e12ae9e", - "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006)." + "digest": "sha256:3d704fc10c2a2132bc064301efcc89fb0df86b657897fbbe1c37ba76e3cb8272", + "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." }, { "declaration": "packages/remote/src/upload-client.ts#uploadDirectArtifact", @@ -534,8 +534,8 @@ }, { "declaration": "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt", - "digest": "sha256:53ea451d23e3c260177368080b8989715f915f85a2c7d907bcc59c72248c8db8", - "rationale": "#4441 keeps each attempt under its sequential phase watchdog and corrects its transport lifecycle: the connect ceiling now ends at actual socket or TLS-handshake establishment, body progress counts only transport writes, and an early response reads the accepted answer to its end, then destroys and joins the owned file/request pipeline and retires this attempt's phase watchdog before resolving or starting the redirect/resume attempt, so a completed hop's timers never reach the next hop. The outgoing-request phase observation now comes from @agent-device/host-kit/transport's observeClientRequestPhases, which listens to the same socket, TLS-handshake and finish events and is removed when the attempt settles. Bytes on the wire are unchanged: same route, method, headers, body framing, resume-offset handling and redirect limit. Only this client's own sequencing and deadlines moved, so a protocol-2 peer parses exactly what it parsed before. Request-body progress is now each non-empty request write that completes without an error, which Node reports once the bytes reach the local kernel, instead of drain, which fires only after a write returned false. The write wrapper passes every argument and the backpressure result through, so the bytes and framing on the wire do not change. That completed-write observer is host-kit's transport owner, which also stops reporting after the response starts, the signal aborts or the request is destroyed; no request changes. The attempt composes that write owner with the phase observer once per request and disposes both when it settles. Duplicate success disposal and abort-reason mapping are consolidated without changing precedence. The sole response-path pipeline join remains before outcome or next hop; URL, method, authentication, payloads and framing remain unchanged. Its two refusal errors now read details.reason from UPLOAD_TRANSFER_REASONS instead of literals in this declaration, so only the identifier expressions moved; the values published are the identical strings and nothing a peer sends or parses moves." + "digest": "sha256:0e93634d9e22fa6f3017aa98f880170ee5e57423acd8883373bf96de9c62b3d6", + "rationale": "#4441 keeps each attempt under its sequential phase watchdog and corrects its transport lifecycle: the connect ceiling now ends at actual socket or TLS-handshake establishment, body progress counts only transport writes, and an early response reads the accepted answer to its end, then destroys and joins the owned file/request pipeline and retires this attempt's phase watchdog before resolving or starting the redirect/resume attempt, so a completed hop's timers never reach the next hop. The outgoing-request phase observation now comes from @agent-device/host-kit/transport's observeClientRequestPhases, which listens to the same socket, TLS-handshake and finish events and is removed when the attempt settles. Bytes on the wire are unchanged: same route, method, headers, body framing, resume-offset handling and redirect limit. Only this client's own sequencing and deadlines moved, so a protocol-2 peer parses exactly what it parsed before. Request-body progress is now each non-empty request write that completes without an error, which Node reports once the bytes reach the local kernel, instead of drain, which fires only after a write returned false. The write wrapper passes every argument and the backpressure result through, so the bytes and framing on the wire do not change. That completed-write observer is host-kit's transport owner, which also stops reporting after the response starts, the signal aborts or the request is destroyed; no request changes. The attempt composes that write owner with the phase observer once per request and disposes both when it settles. Duplicate success disposal and abort-reason mapping are consolidated without changing precedence. The sole response-path pipeline join remains before outcome or next hop; URL, method, authentication, payloads and framing remain unchanged. Its two refusal errors now read details.reason from UPLOAD_TRANSFER_REASONS instead of literals in this declaration, so only the identifier expressions moved; the values published are the identical strings and nothing a peer sends or parses moves. #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." }, { "declaration": "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath", @@ -549,13 +549,13 @@ }, { "declaration": "packages/remote/src/upload-client.ts#requestUploadControl", - "digest": "sha256:5689da0c0cd18d0293e5bb05ddc0d8a07d1bca9ab1d94f8ca185b03bc5b8d758", - "rationale": "Lists the shared control Fetch/JSON owner so changes to method, headers, body or redirect forwarding remain wire-gated. Existing preflight/finalize routes and protocol-2 payloads are preserved; the original 30-second ceiling now retains typed local phase expiry and stops later legs. Non-success status handling is unchanged." + "digest": "sha256:86e2a092caf2aef3404957eb4abba9dc35ac6e68eea99448085da3c927f24a45", + "rationale": "Lists the shared control Fetch/JSON owner so changes to method, headers, body or redirect forwarding remain wire-gated. Existing preflight/finalize routes and protocol-2 payloads are preserved; the original 30-second ceiling now retains typed local phase expiry and stops later legs. Non-success status handling is unchanged. #5150 sends a plain-http (loopback) control request over node:http with a direct agent instead of global fetch. It still follows no redirect, and method, headers, and JSON body are unchanged." }, { "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", @@ -701,6 +701,11 @@ "declaration": "packages/remote/src/session-script-destination.ts#RemoteEndpoint", "digest": "sha256:2fbcaa03bc0675fef8d19fd0a163d5d01a2162031745a41ff5c1db8a982cc2b6", "rationale": "Adds the client-local checkedRpc flag, set when the open goes on the checked RPC route. Nothing on the wire reads it; the open request and its response fields are unchanged." + }, + { + "declaration": "packages/remote/src/artifact-download.ts#requestRemoteArtifact", + "digest": "sha256:9777ec47aa972b81181a6ba3c2325c816c2a7a443c095c635f48d7451369453a", + "rationale": "#5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." } ] } From 358e2b47a2dd76bd6fd34cf25559662b8ee38386 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 13:47:49 +0100 Subject: [PATCH 05/22] test(remote): pin the direct agent on the request diagnostics fetch The direct request-diagnostics read sends the daemon token over plain http to loopback, so it takes the direct agent that bypasses environment proxies. The integration test now asserts that agent in the request options instead of a shape without one. Co-Authored-By: Claude Opus 5.5 --- .../remote-proxy-request-diagnostics.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts b/test/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts index 51eb05e329..a4bf1c9ab9 100644 --- a/test/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts +++ b/test/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts @@ -4,6 +4,7 @@ import http from 'node:http'; import path from 'node:path'; import { test, vi } from 'vitest'; import { localizeRemoteDaemonError } from '@agent-device/remote/remote-request-diagnostics'; +import { loadDirectHttpAgent } from '@agent-device/host-kit/direct-http'; import type { DaemonError } from '@agent-device/kernel/errors'; import { mkdtempForTestSync, skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; import { createProviderScenarioHarness } from './harness.ts'; @@ -102,9 +103,13 @@ test('Provider-backed integration local proxy serves the daemon diagnostics reco method?: string; path?: string; headers?: Record; + agent?: http.Agent; }; assert.equal(directRequestSpy.mock.calls.length, 1); + // The token travels over plain http to loopback, so the request takes the direct agent that + // never routes through an environment proxy. assert.deepEqual(directOptions, { + agent: await loadDirectHttpAgent('http:'), protocol: 'http:', host: '127.0.0.1', port: String(daemon.httpPort), From 18a45e151c2c9e3ac2ba0ed0e8b39a94b15c3883 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 13:54:56 +0100 Subject: [PATCH 06/22] fix(proxy): relay upstream redirects instead of refusing them redirect: 'error' turned every upstream 3xx into a network error, so the daemon's 308 resume response on a direct upload chunk reached the client as a 500. Upstream requests now carry redirect: 'manual': the proxy never follows a redirect while it holds the upstream token, and it relays the 3xx to its client as before. Client requests follow at most a same-origin redirect (uploads) or none (RPC, health, diagnostics, artifact download, upload control), so a relayed Location cannot pull the daemon token over plain http. Co-Authored-By: Claude Opus 5.5 --- packages/proxy/README.md | 3 ++- .../proxy/src/daemon-proxy-credential-transport.test.ts | 4 ++-- packages/proxy/src/daemon-proxy.ts | 7 ++++--- website/docs/docs/security-trust.md | 2 +- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/proxy/README.md b/packages/proxy/README.md index e474f039e5..351ce120d9 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -151,7 +151,8 @@ 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. The request carries the -upstream token and `redirect: 'error'`; never follow a redirect with it. +upstream token and `redirect: 'manual'`: return a 3xx response as it is and never follow it. The +proxy relays a 3xx, such as the daemon's `308` resume response, to its client unchanged. `upstreamBaseUrl` must use https, or plain http to a loopback host, with or without `upstreamFetch`. With your own transport, give it a logical URL that meets this rule, such as diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index bd61fa8cc7..fef1f49e04 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -84,7 +84,7 @@ test.each([ }, ); -test('an upstream redirect is never followed, so its target receives no token', async () => { +test('an upstream redirect is relayed, never followed, so its target receives no token', async () => { const reached: string[] = []; const target = await serve((req, res) => { reached.push(`${req.method} ${req.url} ${req.headers['x-agent-device-token'] ?? ''}`); @@ -115,7 +115,7 @@ test('an upstream redirect is never followed, so its target receives no token', await ( await proxy.handle(new Request('https://gateway.example.test/agent-device/health')) ).text(); - expect((await proxy.handle(rpc())).status).toBeGreaterThanOrEqual(400); + expect((await proxy.handle(rpc())).status).toBe(307); expect(reached).toEqual([]); }); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index b39ed1c0ad..5892155ba1 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -34,8 +34,9 @@ import { * the proxy reaches the daemon over `node:http(s)` on artifact transfer routes and over the global * `fetch` on `/rpc`, health and diagnostics; plain http goes direct, never through an environment * proxy. Supply your own to reach the daemon over another transport, such as a WebSocket tunnel. - * Abort the exchange when `request.signal` aborts. Every request carries `redirect: 'error'`: - * never follow a redirect, because the request carries the upstream token. + * Abort the exchange when `request.signal` aborts. Every request carries `redirect: 'manual'`: + * return a 3xx as the response and never follow it, because the request carries the upstream + * token. The proxy relays the 3xx to its client, which applies its own redirect rules. * * 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 @@ -436,7 +437,7 @@ function keepAliveWith(owner: object, request: Request): Request { /** Builds a request for `owner` to send on, kept reachable for as long as `owner` is. */ function forwardedRequest(owner: Request, url: string | URL, init: RequestInit): Request { - return keepAliveWith(owner, new Request(url, { ...init, redirect: 'error' })); + return keepAliveWith(owner, new Request(url, { ...init, redirect: 'manual' })); } function upstreamSignal(request: Request, options: NormalizedProxyOptions): AbortSignal { diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 5424b35c6f..5857d161a9 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -21,7 +21,7 @@ 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. -A client never sends a daemon, proxy, Metro host bridge, or cloud auth credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, such as Limrun API and download URLs, are checked right before each request. +A client never sends a daemon, proxy, Metro host bridge, or cloud auth credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect; it relays the redirect response to its client, whose requests follow at most a same-origin redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, such as Limrun API and download URLs, are checked right before each request. 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. From 05f08d9bc167af030b1d87250ad55a13b307fe0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 14:14:06 +0100 Subject: [PATCH 07/22] fix(proxy): one redirect rule across routes, with a safe relayed Location - the checked RPC route uses the same redirect: 'manual' as every other upstream request; it still refuses a 3xx answer before relaying - a relayed 3xx carries its Location only when the target is the upstream daemon itself, moved onto the client-facing origin and base path; a foreign target, userinfo, or the upstream token drops it - response relaying lives in upstream-response-relay.ts, loaded with the first forwarded response, so every route and transport shares one header allowlist - loadNodeHttpRequester takes credential: 'direct', which every credential-bearing node:http send now uses; wire ledger re-recorded - the insecure-transport refusal names the setting, never the destination, so checked paths keep naming no endpoint - checked RPC tests use https or loopback endpoints; zero-send tests cover the checked command, the connect probe, and the proxy route Co-Authored-By: Claude Opus 5.5 --- .../contracts/src/credential-transport.ts | 8 +- ...lient-checked-rpc-connect-recovery.test.ts | 14 ++-- ...emon-client-lifecycle-remote-trust.test.ts | 64 +++++++++++---- .../src/daemon-client-transport.ts | 16 +--- packages/host-kit/src/internal/transport.ts | 22 +++-- packages/proxy/README.md | 12 +-- .../src/daemon-proxy-checked-rpc.test.ts | 6 +- .../daemon-proxy-credential-transport.test.ts | 81 ++++++++++++++++++- packages/proxy/src/daemon-proxy.ts | 59 +++++--------- packages/proxy/src/transfer-transport.ts | 11 +-- packages/proxy/src/upstream-response-relay.ts | 77 ++++++++++++++++++ packages/remote/src/artifact-download.ts | 6 +- .../remote/src/remote-request-diagnostics.ts | 6 +- packages/remote/src/upload-stream.ts | 6 +- test/wire-compat/ledger.json | 16 ++-- website/docs/docs/error-reasons.md | 2 +- 16 files changed, 279 insertions(+), 127 deletions(-) create mode 100644 packages/proxy/src/upstream-response-relay.ts diff --git a/packages/contracts/src/credential-transport.ts b/packages/contracts/src/credential-transport.ts index 1ef707699a..06bc4c25f7 100644 --- a/packages/contracts/src/credential-transport.ts +++ b/packages/contracts/src/credential-transport.ts @@ -8,7 +8,7 @@ import { isLoopbackHostname } from './loopback-host.ts'; /** Why a client refuses to send a credential before any request leaves. */ const CREDENTIAL_TRANSPORT_REASONS = { // A credential would travel over plain http to a host that is not loopback, or to a URL that does - // not parse. `details.origin` names the refused destination when it parses. + // not parse. The refusal names the setting, never the destination. insecureTransport: { reason: 'insecure_credential_transport' }, } as const satisfies ReasonTable<'remote connection'>; @@ -20,7 +20,8 @@ export function isSecureCredentialDestination(url: URL): boolean { /** * 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 destination in the message. + * 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): URL { const destination = typeof url === 'string' ? URL.parse(url) : url; @@ -28,11 +29,10 @@ export function assertSecureCredentialTransport(url: string | URL, subject: stri throw new AppError( 'INVALID_ARGS', destination - ? `${subject} must use https to send credentials to ${destination.host}; plain http is allowed only on loopback.` + ? `${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.`, { reason: CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason, - ...(destination ? { origin: destination.origin } : {}), hint: 'Use an https 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.', }, ); 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 index 96c9cf0599..997a90f487 100644 --- 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 @@ -8,7 +8,7 @@ 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 { createDaemonTransport } from '../index.ts'; +import { assertRemoteServesCheckedRpc, createDaemonTransport } from '../index.ts'; import { resolveClientSettings } from '../daemon-client-lifecycle.ts'; const REQUEST = { session: 'default', command: 'devices', positionals: [], flags: {} }; @@ -17,32 +17,66 @@ afterEach(() => { vi.restoreAllMocks(); }); -test('a token for a plain http daemon off loopback is refused before any request leaves', async () => { - const opened = [ +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'), ]; - const send = createDaemonTransport( - createTestHostEnvironment({ - env: { - AGENT_DEVICE_DAEMON_BASE_URL: 'http://remote-mac.example.test:7777/agent-device', - AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'remote-secret', - }, - }), - ); +} - const refusal = await send(REQUEST).then( +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)); - assert.equal(refusal.code, 'INVALID_ARGS'); + 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.equal(refusal.details?.origin, 'http://remote-mac.example.test:7777'); + 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/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 356a85fc9d..8104d0c981 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -298,11 +298,7 @@ async function readDaemonHttpHealth( const timeoutSignal = AbortSignal.timeout(Math.ceil(timeoutMs)); const signal = callerSignal ? AbortSignal.any([timeoutSignal, callerSignal]) : timeoutSignal; const transport = await Promise.race([ - Promise.all([ - loadNodeHttpRequester(url.protocol), - // Plain http carries the token only to loopback, and never through an environment proxy. - import('@agent-device/host-kit/direct-http').then((m) => m.loadDirectHttpAgent(url.protocol)), - ]), + loadNodeHttpRequester(url.protocol, 'direct'), new Promise((resolve) => { signal.addEventListener('abort', () => resolve(null), { once: true }); }), @@ -311,8 +307,7 @@ async function readDaemonHttpHealth( if (!transport || healthProbeExpired(signal, deadline)) return unreachable(); return await new Promise((resolve) => { const headers = info.baseUrl ? buildDaemonHttpAuthHeaders(info.token) : {}; - const [requester, agent] = transport; - const req = requester.request( + const req = transport.request( { protocol: url.protocol, host: url.hostname, @@ -322,7 +317,6 @@ async function readDaemonHttpHealth( timeout: timeoutMs, signal, headers, - agent, }, (res) => { let body = ''; @@ -817,10 +811,7 @@ async function sendHttpRequest( } if (checked) headers[DAEMON_HTTP_RPC_PROTOCOL_HEADER] = String(DAEMON_RPC_PROTOCOL_VERSION); const checkedRpc = checked ? await import('./daemon-client-checked-rpc.ts') : undefined; - const transport = await loadNodeHttpRequester(rpcUrl.protocol); - const agent = await ( - await import('@agent-device/host-kit/direct-http') - ).loadDirectHttpAgent(rpcUrl.protocol); + const transport = await loadNodeHttpRequester(rpcUrl.protocol, 'direct'); const callerSignal = options.signal; refuseAbortedRequest(callerSignal, req.meta?.requestId); @@ -865,7 +856,6 @@ async function sendHttpRequest( method: 'POST', path: rpcUrl.pathname + rpcUrl.search, headers, - agent, }, (res) => { if (checkedRpc?.isCheckedRpcOutcomeResponse(res.statusCode, res.headers ?? {})) { diff --git a/packages/host-kit/src/internal/transport.ts b/packages/host-kit/src/internal/transport.ts index 99ba9455d2..463b8d56ff 100644 --- a/packages/host-kit/src/internal/transport.ts +++ b/packages/host-kit/src/internal/transport.ts @@ -1,6 +1,6 @@ import crypto from 'node:crypto'; import { types } from 'node:util'; -import type { ClientRequest, IncomingMessage } from 'node:http'; +import type { ClientRequest, IncomingMessage, RequestOptions } from 'node:http'; import type { Socket } from 'node:net'; import { AppError } from '@agent-device/kernel/errors'; @@ -37,11 +37,23 @@ export type NodeHttpRequester = Pick; * Resolves `.default`, not the namespace, so callers get the very same module * object a static `import http from 'node:http'` yields -- its `request` * property is mutable, which the transport tests rely on to stub requests. + * + * `credential: 'direct'` is for a request that carries a credential: over plain http (loopback + * only) it connects directly and never through an environment proxy, unless the caller names its + * own `agent`. The requester still calls the module's `request` at send time. */ -export async function loadNodeHttpRequester(protocol: string): Promise { - return protocol === 'https:' - ? (await import('node:https')).default - : (await import('node:http')).default; +export async function loadNodeHttpRequester( + protocol: string, + credential?: 'direct', +): Promise { + if (protocol === 'https:') return (await import('node:https')).default; + const http = (await import('node:http')).default; + if (credential !== 'direct') return http; + const agent = await (await import('../direct-http.ts')).loadDirectHttpAgent(protocol); + return { + request: ((options: RequestOptions, callback?: (res: IncomingMessage) => void) => + http.request({ agent, ...options }, callback)) as NodeHttpRequester['request'], + }; } export function readNodeHttpResponseBody( diff --git a/packages/proxy/README.md b/packages/proxy/README.md index 351ce120d9..c7b53ff5f7 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -152,7 +152,12 @@ 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. 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, such as the daemon's `308` resume response, to its client unchanged. +proxy relays a 3xx, such as the daemon's `308` resume response, to its client. It relays a +`Location` only when it targets the daemon itself, moved onto the proxy's client-facing origin, and +drops one that points elsewhere, has userinfo, or carries the upstream token. 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. `upstreamBaseUrl` must use https, or plain http to a loopback host, with or without `upstreamFetch`. With your own transport, give it a logical URL that meets this rule, such as @@ -160,11 +165,6 @@ proxy relays a 3xx, such as the daemon's `308` resume response, to its client un proxy sends nothing upstream and answers every request with `INVALID_ARGS` (`details.reason: "insecure_credential_transport"` on `/rpc`). -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. - 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 inactivity limit. Work your transport starts can keep running if it ignores `request.signal`. The 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 index fef1f49e04..309075fbf1 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -5,6 +5,10 @@ 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 { @@ -29,12 +33,18 @@ async function serve(handler: http.RequestListener): Promise { return `http://127.0.0.1:${await listenLocal(server)}`; } -const rpc = () => - new Request('https://gateway.example.test/agent-device/rpc', { +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' }, - body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent-device.command', params: {} }), + 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', undefined], @@ -69,6 +79,7 @@ test.each([ 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' }, @@ -119,3 +130,65 @@ test('an upstream redirect is relayed, never followed, so its target receives no expect(reached).toEqual([]); }); + +test.each([ + ['a foreign origin', 'http://attacker.example/x?signature=secret', null], + ['userinfo', 'https://user:pass@daemon.example.test/artifacts/x', null], + ['the upstream token', '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/artifacts/other?token=daemon-secret', null], + [ + 'the upstream daemon', + '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/artifacts/other?part=2', + 'https://gateway.example.test/agent-device/artifacts/other?part=2', + ], +] as const)( + 'a relayed Location that names %s is relayed only on the daemon itself', + async (_label, location, relayed) => { + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'https://daemon.example.test', + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + upstreamFetch: async () => 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(relayed); + } + }, +); + +test('the default transports relay a daemon redirect with its target on every route', async () => { + const daemon = await serve((req, res) => { + req.resume(); + res.statusCode = 307; + res.setHeader('location', `${req.url}-moved`); + res.end(); + }); + const proxy = createDaemonProxy({ + upstreamBaseUrl: daemon, + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + }); + + const transfer = await proxy.handle( + new Request('https://gateway.example.test/agent-device/artifacts/build', { + headers: { authorization: 'Bearer client-secret' }, + }), + ); + const command = await proxy.handle(rpc()); + + expect(transfer.status).toBe(307); + expect(transfer.headers.get('location')).toBe( + 'https://gateway.example.test/agent-device/artifacts/build-moved', + ); + expect(command.status).toBe(307); + expect(command.headers.get('location')).toBe( + 'https://gateway.example.test/agent-device/rpc-moved', + ); +}); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 5892155ba1..ebef28ad16 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -35,13 +35,12 @@ import { * `fetch` on `/rpc`, health and diagnostics; plain http goes direct, never through an environment * proxy. Supply your own to reach the daemon over another transport, such as a WebSocket tunnel. * Abort the exchange when `request.signal` aborts. Every request carries `redirect: 'manual'`: - * return a 3xx as the response and never follow it, because the request carries the upstream - * token. The proxy relays the 3xx to its client, which applies its own redirect rules. + * 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 to its client, which applies its own redirect rules; + * on the checked RPC route 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. */ @@ -147,14 +146,6 @@ const FORWARDED_REQUEST_HEADERS = [ 'x-artifact-hash-algorithm', DAEMON_HTTP_TENANT_HEADER, ]; -const FORWARDED_RESPONSE_HEADERS = [ - 'content-type', - 'content-disposition', - 'x-request-id', - DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, -]; -const FORWARDED_UPLOAD_CHUNK_RESPONSE_HEADERS = ['range', 'x-upload-offset']; -const FORWARDED_ARTIFACT_DOWNLOAD_RESPONSE_HEADERS = ['content-length']; export function createDaemonProxy(options: DaemonProxyOptions): DaemonProxy { const normalized = normalizeProxyOptions(options); @@ -390,14 +381,13 @@ async function forwardProxyRequest(params: { const { request, route, options, rpcBody, caller } = params; const body = resolveUpstreamBody(request, route, rpcBody, options.upstreamToken, caller.tenantId); const checked = route === DAEMON_HTTP_CHECKED_RPC_ROUTE; + const upstreamUrl = buildUpstreamUrl(options.upstreamBaseUrl, route, request.url); const upstreamResponse = await options.upstreamTransport( route, - forwardedRequest(request, buildUpstreamUrl(options.upstreamBaseUrl, route, request.url), { + forwardedRequest(request, upstreamUrl, { 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 } : {}), }), ); @@ -407,7 +397,17 @@ async function forwardProxyRequest(params: { if (refusal) return refusal; } - const headers = copyProxyResponseHeaders(upstreamResponse, request, route); + const { relayedResponseHeaders } = await import('./upstream-response-relay.ts'); + const headers = relayedResponseHeaders({ + upstreamResponse, + upstreamUrl, + requestUrl: request.url, + requestId: resolveRequestId(request), + route, + upstreamBaseUrl: options.upstreamBaseUrl, + upstreamToken: options.upstreamToken, + publicOrigin: options.publicOrigin, + }); if (isUploadPreflightRoute(route)) { return await rewrittenUploadPreflightResponse({ request, @@ -436,6 +436,10 @@ function keepAliveWith(owner: object, request: Request): 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, redirect: 'manual' })); } @@ -445,27 +449,6 @@ function upstreamSignal(request: Request, options: NormalizedProxyOptions): Abor return AbortSignal.any([request.signal, AbortSignal.timeout(options.upstreamTimeoutMs)]); } -function copyProxyResponseHeaders( - upstreamResponse: Response, - request: Request, - route: string, -): Headers { - const headers = new Headers(); - for (const name of [...FORWARDED_RESPONSE_HEADERS, ...routeResponseHeaders(route)]) { - const value = upstreamResponse.headers.get(name); - if (value) headers.set(name, value); - } - if (!headers.has('x-request-id')) headers.set('x-request-id', resolveRequestId(request)); - return headers; -} - -/** `content-length` stays off the preflight route because the proxy rewrites that body. */ -function routeResponseHeaders(route: string): readonly string[] { - if (route.startsWith('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/upload/direct/')) return FORWARDED_UPLOAD_CHUNK_RESPONSE_HEADERS; - if (route.startsWith('/artifacts/')) return FORWARDED_ARTIFACT_DOWNLOAD_RESPONSE_HEADERS; - return []; -} - async function rewrittenUploadPreflightResponse(params: { request: Request; upstreamResponse: Response; diff --git a/packages/proxy/src/transfer-transport.ts b/packages/proxy/src/transfer-transport.ts index a956a3018e..d5804f8744 100644 --- a/packages/proxy/src/transfer-transport.ts +++ b/packages/proxy/src/transfer-transport.ts @@ -25,7 +25,7 @@ const TRANSFER_FORWARDING_REASONS = { } as const satisfies ReasonTable<'proxy'>; const NULL_BODY_STATUSES = new Set([204, 205, 304]); -/** Forwards one exchange over `node:http(s)`, without redirects or retries; plain http never takes an environment proxy. */ +/** Forwards one exchange over `node:http(s)`, without redirects or retries; plain http goes direct. */ export function createNodeTransferFetch(): (request: Request) => Promise { return async (request) => { const exchange = openExchange(request.signal); @@ -140,12 +140,8 @@ async function exchangeOverNodeHttp( exchange: TransferExchange, ): Promise { const url = new URL(request.url); - const [transport, agent, { urlToHttpOptions }] = await untilAborted(exchange.signal, () => - Promise.all([ - loadNodeHttpRequester(url.protocol), - import('@agent-device/host-kit/direct-http').then((m) => m.loadDirectHttpAgent(url.protocol)), - import('node:url'), - ]), + const [transport, { urlToHttpOptions }] = await untilAborted(exchange.signal, () => + Promise.all([loadNodeHttpRequester(url.protocol, 'direct'), import('node:url')]), ); exchange.signal.throwIfAborted(); const { auth: _auth, ...target } = urlToHttpOptions(url); @@ -155,7 +151,6 @@ async function exchangeOverNodeHttp( path: `${url.pathname}${url.search}`, headers: Object.fromEntries(request.headers), signal: exchange.signal, - agent, }; exchange.watchdog.arm('connect', TRANSFER_CONNECT_TIMEOUT_MS); return await new Promise((resolve, reject) => { diff --git a/packages/proxy/src/upstream-response-relay.ts b/packages/proxy/src/upstream-response-relay.ts new file mode 100644 index 0000000000..7000d2f400 --- /dev/null +++ b/packages/proxy/src/upstream-response-relay.ts @@ -0,0 +1,77 @@ +import { + DAEMON_HTTP_BASE_PATH, + DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, +} from '@agent-device/contracts/daemon-http'; + +// Which upstream response headers a proxied response carries, the same on every route and +// transport. Loaded with the first forwarded response, never at module scope. + +const FORWARDED_RESPONSE_HEADERS = [ + 'content-type', + 'content-disposition', + 'x-request-id', + DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, +]; +const FORWARDED_UPLOAD_CHUNK_RESPONSE_HEADERS = ['range', 'x-upload-offset']; +const FORWARDED_ARTIFACT_DOWNLOAD_RESPONSE_HEADERS = ['content-length']; + +export type RelayedResponse = { + upstreamResponse: Response; + /** The URL the upstream request went to; a relative `Location` resolves against it. */ + upstreamUrl: URL; + /** The client request's URL: its origin and base path are where a relayed target points. */ + requestUrl: string; + requestId: string; + route: string; + upstreamBaseUrl: string; + upstreamToken: string; + publicOrigin: string | undefined; +}; + +/** The headers a proxied response carries: the allowlist, the request id, and a safe `Location`. */ +export function relayedResponseHeaders(relay: RelayedResponse): Headers { + const headers = new Headers(); + for (const name of [...FORWARDED_RESPONSE_HEADERS, ...routeResponseHeaders(relay.route)]) { + const value = relay.upstreamResponse.headers.get(name); + if (value) headers.set(name, value); + } + if (!headers.has('x-request-id')) headers.set('x-request-id', relay.requestId); + const location = relayedLocation(relay); + if (location) headers.set('location', location); + return headers; +} + +/** `content-length` stays off the preflight route because the proxy rewrites that body. */ +function routeResponseHeaders(route: string): readonly string[] { + if (route.startsWith('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/upload/direct/')) return FORWARDED_UPLOAD_CHUNK_RESPONSE_HEADERS; + if (route.startsWith('/artifacts/')) return FORWARDED_ARTIFACT_DOWNLOAD_RESPONSE_HEADERS; + return []; +} + +/** + * The `Location` of a relayed upstream 3xx, as the client must see it. Only a target on the + * upstream daemon itself is relayed, moved onto the client-facing origin and base path the request + * came in on. A target elsewhere, with userinfo, or carrying the upstream token is dropped: the + * proxy never hands a client a credential or a foreign destination. + */ +function relayedLocation(relay: RelayedResponse): string | undefined { + const raw = relay.upstreamResponse.headers.get('location'); + if (!raw || raw.includes(relay.upstreamToken)) return undefined; + const target = URL.parse(raw, relay.upstreamUrl); + const upstreamBase = new URL(relay.upstreamBaseUrl); + if (!target || target.origin !== upstreamBase.origin || target.username || target.password) { + return undefined; + } + const basePath = upstreamBase.pathname.replace(/\/+$/, ''); + if (basePath && target.pathname !== basePath && !target.pathname.startsWith(`${basePath}/`)) { + return undefined; + } + const requestUrl = new URL(relay.requestUrl); + const prefix = requestUrl.pathname.startsWith(`${DAEMON_HTTP_BASE_PATH}/`) + ? DAEMON_HTTP_BASE_PATH + : ''; + const relayed = new URL(relay.publicOrigin ?? requestUrl.origin); + relayed.pathname = `${prefix}${target.pathname.slice(basePath.length) || '/'}`; + relayed.search = target.search; + return relayed.toString(); +} diff --git a/packages/remote/src/artifact-download.ts b/packages/remote/src/artifact-download.ts index 96f9f4ec35..864c9b2d83 100644 --- a/packages/remote/src/artifact-download.ts +++ b/packages/remote/src/artifact-download.ts @@ -159,10 +159,7 @@ async function requestRemoteArtifact( materialize(res: http.IncomingMessage, signal: AbortSignal): Promise; }, ): Promise { - const transport = await loadNodeHttpRequester(params.artifactUrl.protocol); - const agent = await ( - await import('@agent-device/host-kit/direct-http') - ).loadDirectHttpAgent(params.artifactUrl.protocol); + const transport = await loadNodeHttpRequester(params.artifactUrl.protocol, 'direct'); await destination.prepare(); return await new Promise((resolve, reject) => { let settled = false; @@ -200,7 +197,6 @@ async function requestRemoteArtifact( port: params.artifactUrl.port, method: 'GET', path: params.artifactUrl.pathname + params.artifactUrl.search, - agent, headers: { ...buildDaemonHttpAuthHeaders(params.token), ...buildDaemonHttpTenantHeaders(params.requestScope?.tenantId), diff --git a/packages/remote/src/remote-request-diagnostics.ts b/packages/remote/src/remote-request-diagnostics.ts index bc3d635a15..8bd6434bce 100644 --- a/packages/remote/src/remote-request-diagnostics.ts +++ b/packages/remote/src/remote-request-diagnostics.ts @@ -146,10 +146,7 @@ async function fetchRemoteRequestDiagnostics(params: { return 'daemon base URL is not a valid URL'; } try { - const transport = await loadNodeHttpRequester(url.protocol); - const agent = await ( - await import('@agent-device/host-kit/direct-http') - ).loadDirectHttpAgent(url.protocol); + const transport = await loadNodeHttpRequester(url.protocol, 'direct'); await fs.promises.mkdir(path.dirname(destinationPath), { recursive: true }); return await new Promise((resolve) => { let settled = false; @@ -172,7 +169,6 @@ async function fetchRemoteRequestDiagnostics(params: { port: url.port, method: 'GET', path: url.pathname + url.search, - agent, headers: { ...buildDaemonHttpAuthHeaders(endpoint.token), ...buildDaemonHttpTenantHeaders(endpoint.tenantId), diff --git a/packages/remote/src/upload-stream.ts b/packages/remote/src/upload-stream.ts index 7748b29d96..27baa30408 100644 --- a/packages/remote/src/upload-stream.ts +++ b/packages/remote/src/upload-stream.ts @@ -108,10 +108,7 @@ async function streamFileToHttpRequestAttempt(options: { // This module sits in the CLI's eager import closure via the remote-artifact // upload client, but only a remote daemon ever uploads, so the HTTP stack // loads here rather than at import time. - const transport = await loadNodeHttpRequester(options.url.protocol); - const agent = await ( - await import('@agent-device/host-kit/direct-http') - ).loadDirectHttpAgent(options.url.protocol); + const transport = await loadNodeHttpRequester(options.url.protocol, 'direct'); const payloadSize = fs.statSync(options.payloadPath).size; const headers = buildUploadRequestHeaders(options.headers, options.startOffset, payloadSize); emitUploadAttemptStarted(options.progress, options.startOffset, payloadSize); @@ -137,7 +134,6 @@ async function streamFileToHttpRequestAttempt(options: { method: options.method, path: options.url.pathname + options.url.search, headers, - agent, // Aborting destroys the request mid-stream, which is the only way to stop bytes that are // already piped at a device this client no longer holds the lease on. signal: watchdog.signal, diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 3a50a1de07..4b1164084d 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,7 +71,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealth": "sha256:1ff542dadff6d92233c464b7d09052d809f36186bb60acdb572c48bfc1eb5c1f", "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealthLink": "sha256:96a79a8ff5a078916ee7bffed1d9624d0ba9c0dcbd8e2c55f9abf37fccfef744", "packages/daemon-client/src/daemon-client-transport.ts#isHealthService": "sha256:ffd2c774e0efca5e5d2b01f9d37fe9b76aaf5e7569e07d9208fe667473771c10", - "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth": "sha256:bf1a8cf8a234738d16a9582ded2120a738e1900c03c43e1bef70a7f947f561d8", + "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth": "sha256:f5c01ec3975732318ac1e682b84d75fb9398d109b85302bf5ba189d98dfbf8ab", "packages/daemon-client/src/daemon-client-transport.ts#readHealthLink": "sha256:c4f638b4df43f572e105b6f8df578fe90ebf64cb56002e4d029a109bdbc167d1", "packages/daemon-client/src/daemon-client-transport.ts#readHealthPayload": "sha256:4e85ffc3e35e02379c393e9312344757e003cf1f0ad9eb8d1f77d90c81c861f1", "packages/daemon-client/src/daemon-client-transport.ts#readHealthVersion": "sha256:856bd74aa8b2f205b6b30855755f16391015bffc1b6a323f618b51c26e749bfd", @@ -165,7 +165,7 @@ "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint": "sha256:c1d5fe2fe90c425502cf8b7c87d6606374d6af65b4e9faf942a416f683930bdc", "packages/remote/src/remote-request-diagnostics.ts#buildRemoteRequestDiagnosticsUrl": "sha256:30a1a9bf0df24d3564a616699916a3bb4360c2b4d21c4ad0562fb0c1e738d0a9", - "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics": "sha256:3d704fc10c2a2132bc064301efcc89fb0df86b657897fbbe1c37ba76e3cb8272", + "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics": "sha256:75a4e0305576be8ff3be797c6cc7215f1a2df389c208f8b911ae036fe826583d", "packages/remote/src/remote-request-diagnostics.ts#localizeRemoteDaemonError": "sha256:35cfa186ad64663ae4dbb4e102d49238532cd7e3b75e8337edcc3d1fd77f92d5", "packages/remote/src/upload-client-artifact.ts#PreparedUploadArtifact": "sha256:5c40027d47feda3c946e836372b9f08ad866ab1612708b0d506551545f931ea4", "packages/remote/src/upload-client.ts#ARTIFACT_HASH_ALGORITHM": "sha256:328c135ea5f9d89fd2c142b440d5402a61d19f9044bf0504dfc2c525e58c1909", @@ -190,7 +190,7 @@ "packages/remote/src/upload-stream.ts#parseNonNegativeIntegerHeader": "sha256:5cbe9c6994459d673d988a51407e65556e28175b187ce0a9d27cbb6331962834", "packages/remote/src/upload-stream.ts#parseUploadResumeOffset": "sha256:297184ea22a6dc1cda9aee17034122ae0ea2f43d0355647f6fcf02f3f4b5ca0e", "packages/remote/src/upload-stream.ts#streamFileToHttpRequest": "sha256:c2b5e1369c8b1c9420036e23163d21e43fa2ac8b889c6a8f028cc6095055a16f", - "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt": "sha256:0e93634d9e22fa6f3017aa98f880170ee5e57423acd8883373bf96de9c62b3d6", + "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt": "sha256:84beddf7c503a75f8d2f1e124ae94f198233f12e3d4a44518f0ae6c55bb6f69e", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_INSTANCE_HEADER": "sha256:d2bb3f4846470188a0fc1724271da0f0bcbdf2337bd6bf331508142cadcb65d8", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER": "sha256:4564c2ce437d30d7a823e3326f4375c0750ba8d42bec22b4d02e8eb7f7db2973", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_INSTANCE_MISMATCH_HEADER": "sha256:a197edaf7f9fa94a6aab269856aa852da3204cc586f5fd23198689eb11908b61", @@ -256,7 +256,7 @@ "packages/remote/src/artifact-download.ts#RemoteArtifactRequest": "sha256:6cce66499f34bb18139917df592e554395936964025089024d6c6f67e4fa4b98", "packages/remote/src/artifact-download.ts#RemoteArtifactFetch": "sha256:e83939ec48a66917df9ec84becf53b6ca3c8115cfdada10731046381ac9e32c1", "packages/remote/src/artifact-download.ts#fetchRemoteArtifactFromUrl": "sha256:de6e71abdc758f760beffba0dc260473f88a8c60b13540b9c14d39f1a3d5e3a1", - "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:9777ec47aa972b81181a6ba3c2325c816c2a7a443c095c635f48d7451369453a", + "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:bcd2a587fc699de6575feb95576e03e40f969852f77d9ed492ae02d49ea72ffc", "packages/daemon-client/src/daemon-client-checked-rpc.ts#isCheckedRpcOutcomeResponse": "sha256:75fb9f3444a3f8f4a762811ba7cbe02d92a39ed4e55483ea0cf7f029e5720a3e", "packages/daemon-client/src/daemon-client-checked-rpc.ts#CheckedRpcOutcome": "sha256:8aa7e58307417460bb54938f6bbbd340254e14ffbbaf2093272996909592f7be", "packages/daemon-client/src/daemon-client-checked-rpc.ts#ReadHealthLink": "sha256:86a9e6f1ebdaecca3ddaa16081c221321c01c684b70197961ecd71a3f54a464f", @@ -464,7 +464,7 @@ }, { "declaration": "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth", - "digest": "sha256:bf1a8cf8a234738d16a9582ded2120a738e1900c03c43e1bef70a7f947f561d8", + "digest": "sha256:f5c01ec3975732318ac1e682b84d75fb9398d109b85302bf5ba189d98dfbf8ab", "rationale": "The health-probe budget includes requester loading and response completion. The caller AbortSignal joins the probe timer only in-process; caller cancellation remains distinct from probe expiry. No signal, timedOut flag, request route, auth header or accepted health payload field changes on the wire, so released daemons and proxies parse and respond as before (ADR 0006). #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." }, { @@ -474,7 +474,7 @@ }, { "declaration": "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics", - "digest": "sha256:3d704fc10c2a2132bc064301efcc89fb0df86b657897fbbe1c37ba76e3cb8272", + "digest": "sha256:75a4e0305576be8ff3be797c6cc7215f1a2df389c208f8b911ae036fe826583d", "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." }, { @@ -534,7 +534,7 @@ }, { "declaration": "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt", - "digest": "sha256:0e93634d9e22fa6f3017aa98f880170ee5e57423acd8883373bf96de9c62b3d6", + "digest": "sha256:84beddf7c503a75f8d2f1e124ae94f198233f12e3d4a44518f0ae6c55bb6f69e", "rationale": "#4441 keeps each attempt under its sequential phase watchdog and corrects its transport lifecycle: the connect ceiling now ends at actual socket or TLS-handshake establishment, body progress counts only transport writes, and an early response reads the accepted answer to its end, then destroys and joins the owned file/request pipeline and retires this attempt's phase watchdog before resolving or starting the redirect/resume attempt, so a completed hop's timers never reach the next hop. The outgoing-request phase observation now comes from @agent-device/host-kit/transport's observeClientRequestPhases, which listens to the same socket, TLS-handshake and finish events and is removed when the attempt settles. Bytes on the wire are unchanged: same route, method, headers, body framing, resume-offset handling and redirect limit. Only this client's own sequencing and deadlines moved, so a protocol-2 peer parses exactly what it parsed before. Request-body progress is now each non-empty request write that completes without an error, which Node reports once the bytes reach the local kernel, instead of drain, which fires only after a write returned false. The write wrapper passes every argument and the backpressure result through, so the bytes and framing on the wire do not change. That completed-write observer is host-kit's transport owner, which also stops reporting after the response starts, the signal aborts or the request is destroyed; no request changes. The attempt composes that write owner with the phase observer once per request and disposes both when it settles. Duplicate success disposal and abort-reason mapping are consolidated without changing precedence. The sole response-path pipeline join remains before outcome or next hop; URL, method, authentication, payloads and framing remain unchanged. Its two refusal errors now read details.reason from UPLOAD_TRANSFER_REASONS instead of literals in this declaration, so only the identifier expressions moved; the values published are the identical strings and nothing a peer sends or parses moves. #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." }, { @@ -704,7 +704,7 @@ }, { "declaration": "packages/remote/src/artifact-download.ts#requestRemoteArtifact", - "digest": "sha256:9777ec47aa972b81181a6ba3c2325c816c2a7a443c095c635f48d7451369453a", + "digest": "sha256:bcd2a587fc699de6575feb95576e03e40f969852f77d9ed492ae02d49ea72ffc", "rationale": "#5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." } ] diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 917b00dafa..60d9bca798 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -899,7 +899,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `insecure_credential_transport` | A credential would travel over plain http to a host that is not loopback, or to a URL that does not parse. `details.origin` names the refused destination when it parses. | +| `insecure_credential_transport` | A credential would travel over plain http to a host that is not loopback, 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. | From 3c6adad58ca1b2f794b862719ecf083dc4137bf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 14:19:20 +0100 Subject: [PATCH 08/22] fix(host-kit): break the direct-http import cycle and share the header copy Fallow audit flagged a cycle (direct-http.ts -> internal/transport.ts -> direct-http.ts) and a duplicated response-header copy in direct-http.ts and the proxy transfer transport. direct-http now loads node:http itself, so only internal/transport reaches into it, and both senders use its responseHeadersOf. Co-Authored-By: Claude Opus 5.5 --- packages/host-kit/src/direct-http.ts | 24 +++++++++++++++--------- packages/proxy/src/transfer-transport.ts | 7 ++----- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/packages/host-kit/src/direct-http.ts b/packages/host-kit/src/direct-http.ts index 6cc99fb09d..15713e49f3 100644 --- a/packages/host-kit/src/direct-http.ts +++ b/packages/host-kit/src/direct-http.ts @@ -1,5 +1,4 @@ -import type { Agent } from 'node:http'; -import { loadNodeHttpRequester } from './internal/transport.ts'; +import type { Agent, IncomingMessage } from 'node:http'; // Loaded at send time by the code that sends a credential over plain http, never at module scope. @@ -20,6 +19,16 @@ export async function loadDirectHttpAgent(protocol: string): Promise { const url = new URL(request.url); if (url.protocol !== 'http:') throw new TypeError('fetchOverDirectHttp sends plain http only'); - const [http, agent, { Readable }] = await Promise.all([ - loadNodeHttpRequester('http:'), + // The module object itself, so a stubbed `request` is the one called. + const [{ default: http }, agent, { Readable }] = await Promise.all([ + import('node:http'), loadDirectHttpAgent('http:'), import('node:stream'), ]); @@ -47,11 +57,7 @@ export async function fetchOverDirectHttp(request: Request): Promise { }, (res) => { const status = res.statusCode ?? 502; - const headers = new Headers(); - for (const [name, value] of Object.entries(res.headers)) { - if (value === undefined) continue; - for (const item of Array.isArray(value) ? value : [value]) headers.append(name, item); - } + const headers = responseHeadersOf(res); const nullBody = request.method === 'HEAD' || NULL_BODY_STATUSES.has(status); if (nullBody) res.resume(); resolve( diff --git a/packages/proxy/src/transfer-transport.ts b/packages/proxy/src/transfer-transport.ts index d5804f8744..7b2d551e1f 100644 --- a/packages/proxy/src/transfer-transport.ts +++ b/packages/proxy/src/transfer-transport.ts @@ -11,6 +11,7 @@ import { TRANSFER_RESPONSE_HEADER_TIMEOUT_MS, type TransferPhaseWatchdog, } from '@agent-device/host-kit/transport'; +import { responseHeadersOf } from '@agent-device/host-kit/direct-http'; const PROXY_TRANSFER_AGGREGATE_MS = 600_000; @@ -205,11 +206,7 @@ async function exchangeOverNodeHttp( answered = true; outgoingStopped.abort(); exchange.watchdog.suspend(); - const headers = new Headers(); - for (const [name, value] of Object.entries(res.headers)) { - if (value === undefined) continue; - for (const item of Array.isArray(value) ? value : [value]) headers.append(name, item); - } + const headers = responseHeadersOf(res); if (request.method === 'HEAD' || NULL_BODY_STATUSES.has(status)) { res.resume(); void responseClosed.then(finish); From 6d139261718cc21df4c085c479ec8175e46dc152 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 14:38:37 +0100 Subject: [PATCH 09/22] fix(remote): close the remaining credential transport gaps - proxy: compare a relayed Location by decoded path and drop its query and fragment; answer /health with an error on an upstream redirect; refuse a malformed upstream base per request instead of throwing - companion worker: require a base URL with a host before appending the register or unregister path - cloud auth, Metro, Limrun and the Apple runner send plain http through the direct requester, so an environment proxy never sees a credential - Limrun downloads follow redirects only https to https or on the same origin, and check every hop - direct requester: behave as fetch does on errors, aborts and redirect: 'error', bound silence to five minutes, and always keep the direct agent Co-Authored-By: Claude Sonnet 5.5 --- .../src/__tests__/runner-transport.test.ts | 36 ++++ .../src/__tests__/test-host-defaults.ts | 3 + packages/apple-runner/src/host.ts | 3 + packages/apple-runner/src/runner-transport.ts | 7 +- packages/host-kit/src/direct-http.test.ts | 161 +++++++++++++++++- packages/host-kit/src/direct-http.ts | 82 ++++++++- packages/host-kit/src/internal/transport.ts | 8 +- .../platform-apple/src/core/runner-host.ts | 2 + packages/proxy/README.md | 17 +- packages/proxy/src/checked-rpc-admission.ts | 6 +- .../daemon-proxy-credential-transport.test.ts | 71 ++++++-- packages/proxy/src/daemon-proxy.ts | 47 ++--- packages/proxy/src/upstream-response-relay.ts | 27 ++- .../client-companion-tunnel-worker.test.ts | 54 +++++- .../client-companion-tunnel-worker.ts | 24 +-- packages/react-native/src/index-metro.test.ts | 5 +- .../metro/client-metro-auto-companion.test.ts | 47 +++++ .../react-native/src/metro/client-metro.ts | 3 +- .../test-kit/src/host-kit-capabilities.ts | 33 ++-- src/cli/__tests__/cloud-auth-request.test.ts | 17 +- src/cli/cloud-auth-request.ts | 12 +- .../cloud-profile-transport.test.ts | 6 + src/core/interactors/limrun-ios-files.test.ts | 29 ++++ src/core/interactors/limrun-ios-files.ts | 22 ++- .../interactors/limrun-ios-runner-products.ts | 3 +- .../interactors/limrun-ios-runner.test.ts | 16 ++ src/core/interactors/limrun-ios-runner.ts | 3 +- src/core/limrun-download-file.test.ts | 111 +++++++++++- src/core/limrun-download-file.ts | 52 +++++- test/wire-compat/ledger.json | 2 +- website/docs/docs/error-reasons.md | 2 + website/docs/docs/security-trust.md | 2 +- 32 files changed, 781 insertions(+), 132 deletions(-) diff --git a/packages/apple-runner/src/__tests__/runner-transport.test.ts b/packages/apple-runner/src/__tests__/runner-transport.test.ts index a2bccdc7ff..58691082be 100644 --- a/packages/apple-runner/src/__tests__/runner-transport.test.ts +++ b/packages/apple-runner/src/__tests__/runner-transport.test.ts @@ -1,6 +1,8 @@ import { afterEach, beforeEach, test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; import path from 'node:path'; import { AppError, @@ -41,6 +43,7 @@ vi.mock('../runner-usbmux.ts', async (importOriginal) => { import { clearDeviceTunnelIpCache } from '../runner-command-route.ts'; import { fetchWithTimeout, sendRunnerCommandOnce } from '../runner-transport.ts'; import { mkdtempForTestSync } from './tmp-dir.ts'; +import { loadRealHostKitCapabilities } from '@agent-device/test-kit'; // The real `resolveIosPhysicalDeviceControl` resolves the CoreDevice tunnel IP // through root-level tooling this package cannot reach; a fake control backed @@ -336,3 +339,36 @@ test('a cancellation during route resolution discloses that the command was neve ); assert.equal(vi.mocked(fetch).mock.calls.length, 0); }); + +test('the real transport sends a loopback runner command around global fetch', async () => { + const hostKit = await loadRealHostKitCapabilities(); + appleRunnerTestHost.update({ fetchWithCredential: hostKit.fetchWithCredential }); + const received: string[] = []; + const runner = http.createServer((req, res) => { + let body = ''; + req.on('data', (chunk) => (body += String(chunk))); + req.on('end', () => { + received.push(`${req.url} ${req.headers['content-length']} ${body.length}`); + if (req.url === '/moved') res.writeHead(307, { location: '/target' }).end(); + else res.end('{}'); + }); + }); + await new Promise((resolve) => runner.listen(0, '127.0.0.1', resolve)); + const origin = `http://127.0.0.1:${(runner.address() as AddressInfo).port}`; + const proxied = vi.fn().mockRejectedValue(new Error('proxied')); + vi.stubGlobal('fetch', proxied); + + try { + const post = { method: 'POST', body: 'command' }; + assert.equal((await fetchWithTimeout(`${origin}/command`, post, 5_000)).status, 200); + // The runner token travels in a header, so the redirect target gets nothing. + await assert.rejects(() => fetchWithTimeout(`${origin}/moved`, post, 5_000), TypeError); + + assert.deepEqual(received, ['/command 7 7', '/moved 7 7']); + assert.equal(proxied.mock.calls.length, 0); + } finally { + vi.unstubAllGlobals(); + runner.closeAllConnections(); + await new Promise((resolve) => runner.close(() => resolve())); + } +}); diff --git a/packages/apple-runner/src/__tests__/test-host-defaults.ts b/packages/apple-runner/src/__tests__/test-host-defaults.ts index ef49d09d95..a09249b7ec 100644 --- a/packages/apple-runner/src/__tests__/test-host-defaults.ts +++ b/packages/apple-runner/src/__tests__/test-host-defaults.ts @@ -104,6 +104,9 @@ export async function createAppleRunnerTestHostDefaults(): Promise await fetch(input, init), leaseOwnerStateDir: () => undefined, hasDeviceClaimAuthority: () => false, }; diff --git a/packages/apple-runner/src/host.ts b/packages/apple-runner/src/host.ts index 8ce159ac86..16686cdb25 100644 --- a/packages/apple-runner/src/host.ts +++ b/packages/apple-runner/src/host.ts @@ -1,5 +1,6 @@ import type * as HostCommand from '@agent-device/host-kit/command'; import type * as HostDiagnostics from '@agent-device/host-kit/diagnostics'; +import type * as HostDirectHttp from '@agent-device/host-kit/direct-http'; import type * as HostFile from '@agent-device/host-kit/file'; import type * as HostProcess from '@agent-device/host-kit/process'; import type * as HostRequest from '@agent-device/host-kit/request'; @@ -98,6 +99,7 @@ export type AppleRunnerHost = Pick< | 'commandDeveloperDir' > & Pick & + Pick & Pick & Pick< typeof HostProcess, @@ -198,6 +200,7 @@ export const hostEnvironment = delegate('hostEnvironment'); export const shellQuote = delegate('shellQuote'); export const emitDiagnostic = delegate('emitDiagnostic'); export const withDiagnosticTimer = delegate('withDiagnosticTimer'); +export const fetchWithCredential = delegate('fetchWithCredential'); export const retryWithPolicy = delegate('retryWithPolicy'); export const isEnvTruthy = delegate('isEnvTruthy'); export const isProcessAlive = delegate('isProcessAlive'); diff --git a/packages/apple-runner/src/runner-transport.ts b/packages/apple-runner/src/runner-transport.ts index 3a10910070..27e198b171 100644 --- a/packages/apple-runner/src/runner-transport.ts +++ b/packages/apple-runner/src/runner-transport.ts @@ -3,7 +3,7 @@ import { discloseDispatch, AppError, } from '@agent-device/kernel/errors'; -import { Deadline, resolveIosPhysicalDeviceControl } from './host.ts'; +import { Deadline, fetchWithCredential, resolveIosPhysicalDeviceControl } from './host.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { createRunnerCommandRouteResolver, @@ -161,8 +161,9 @@ export async function fetchWithTimeout( const timeoutSignal = AbortSignal.timeout(timeoutMs); const signal = requestSignal ? AbortSignal.any([requestSignal, timeoutSignal]) : timeoutSignal; try { - // The token travels in a header, so a redirect must never carry it elsewhere. - return await fetch(url, { ...init, redirect: 'error', signal }); + // The token travels in a header, so a redirect must never carry it elsewhere, and a + // plain-http send never goes through an environment proxy. + return await fetchWithCredential(url, { ...init, redirect: 'error', signal }); } catch (error) { // `AbortSignal.timeout` rejects with a bare DOMException that no recovery rule can // read. Only a rejection carrying that signal's own reason is our deadline: a diff --git a/packages/host-kit/src/direct-http.test.ts b/packages/host-kit/src/direct-http.test.ts index 0a3aaaf886..e54f09a9be 100644 --- a/packages/host-kit/src/direct-http.test.ts +++ b/packages/host-kit/src/direct-http.test.ts @@ -1,9 +1,11 @@ -import { afterEach, expect, test } from 'vitest'; +import { afterEach, expect, test, vi } from 'vitest'; import { execFile } from 'node:child_process'; import http from 'node:http'; import path from 'node:path'; import { promisify } from 'node:util'; import type { AddressInfo } from 'node:net'; +import { fetchOverDirectHttp, fetchWithCredential, loadDirectHttpAgent } from './direct-http.ts'; +import { loadNodeHttpRequester } from './transport.ts'; // A credential sent over plain http goes only to loopback, and an environment proxy on another host // would read it in cleartext. Node reads `NODE_USE_ENV_PROXY` at startup, so each case runs a child. @@ -20,6 +22,7 @@ async function closeLocal(server: http.Server): Promise { const servers: http.Server[] = []; afterEach(async () => { + vi.restoreAllMocks(); await Promise.all(servers.splice(0).map((server) => closeLocal(server))); }); @@ -66,6 +69,13 @@ test.each([ }); console.log('sent');`, ], + [ + 'fetchWithCredential', + (target: string) => ` + import { fetchWithCredential } from ${JSON.stringify(TRANSPORT)}; + const response = await fetchWithCredential(${JSON.stringify(target)}, { headers: { authorization: 'Bearer secret' } }); + console.log(await response.text() === 'ok' ? 'sent' : 'bad');`, + ], [ 'fetchOverDirectHttp', (target: string) => ` @@ -85,3 +95,152 @@ test.each([ expect(proxied).toEqual([]); expect(direct).toEqual(['GET /rpc Bearer secret']); }); + +function deferred() { + let resolve!: () => void; + const promise = new Promise((done) => (resolve = done)); + return { promise, resolve }; +} + +/** A loopback server that answers as `respond` does and records what its connections saw. */ +async function serveWith(respond: http.RequestListener) { + const closed = deferred(); + const server = http.createServer((req, res) => { + res.on('close', () => closed.resolve()); + respond(req, res); + }); + servers.push(server); + const origin = `http://127.0.0.1:${await listenLocal(server)}`; + return { origin, closed: closed.promise }; +} + +const stayQuiet: http.RequestListener = () => {}; +const sendHalf: http.RequestListener = (_req, res) => void res.write('half'); + +test('a post declares its length and returns a redirect without following it', async () => { + const seen: string[] = []; + const target = await serveWith((req, res) => { + seen.push(req.url ?? ''); + res.end(); + }); + const { origin } = await serveWith((req, res) => { + let body = ''; + req.on('data', (chunk) => (body += String(chunk))); + req.on('end', () => { + seen.push(`${req.headers['content-length']} ${body}`); + res.writeHead(307, { location: `${target.origin}/moved` }).end(); + }); + }); + + const response = await fetchWithCredential(origin, { + method: 'POST', + body: 'payload', + redirect: 'manual', + }); + + expect(response.status).toBe(307); + await expect( + fetchWithCredential(origin, { method: 'POST', body: 'payload', redirect: 'error' }), + ).rejects.toThrow(TypeError); + expect(seen).toEqual(['7 payload', '7 payload']); +}); + +test('a refused connection rejects as fetch does, with the socket error as the cause', async () => { + const server = http.createServer(); + const port = await listenLocal(server); + await closeLocal(server); + + await expect(fetchWithCredential(`http://127.0.0.1:${port}/`)).rejects.toMatchObject({ + name: 'TypeError', + message: 'fetch failed', + cause: { code: 'ECONNREFUSED' }, + }); +}); + +test('an abort before the response rejects with its reason and closes the connection', async () => { + const received = deferred(); + const { origin, closed } = await serveWith(() => received.resolve()); + const controller = new AbortController(); + const reason = new Error('caller gave up'); + + const pending = fetchWithCredential(origin, { signal: controller.signal }); + await received.promise; + controller.abort(reason); + + await expect(pending).rejects.toBe(reason); + await closed; +}); + +test('an abort during the response body fails the read and closes the connection', async () => { + const { origin, closed } = await serveWith(sendHalf); + const controller = new AbortController(); + const reason = new Error('caller gave up'); + const response = await fetchWithCredential(origin, { signal: controller.signal }); + const reader = response.body!.getReader(); + await reader.read(); + + const pending = reader.read(); + controller.abort(reason); + + await expect(pending).rejects.toBe(reason); + await closed; +}); + +/** Runs the real socket timeout at 20 ms, and records the bound the request asked for. */ +function shortenIdleTimeout(): unknown[] { + const asked: unknown[] = []; + const request = http.request; + vi.spyOn(http, 'request').mockImplementation((( + options: http.RequestOptions, + callback: (res: http.IncomingMessage) => void, + ) => { + asked.push(options.timeout); + return request({ ...options, timeout: 20 }, callback); + }) as typeof http.request); + return asked; +} + +const idleTimeout = { details: { reason: 'direct_http_idle_timeout' } }; + +test('a peer that never answers ends the request with the idle timeout', async () => { + const { origin, closed } = await serveWith(stayQuiet); + const asked = shortenIdleTimeout(); + + await expect(fetchOverDirectHttp(new Request(origin))).rejects.toMatchObject(idleTimeout); + + await closed; + expect(asked).toEqual([300_000]); +}); + +test('a body that goes silent fails the read with the idle timeout', async () => { + const { origin, closed } = await serveWith(sendHalf); + shortenIdleTimeout(); + const response = await fetchWithCredential(origin); + + await expect(response.text()).rejects.toMatchObject(idleTimeout); + await closed; +}); + +test('the credential requester keeps its direct agent whatever the options name', async () => { + const { origin } = await serveWith((_req, res) => void res.end()); + const direct = await loadDirectHttpAgent('http:'); + const request = vi.spyOn(http, 'request'); + const requester = await loadNodeHttpRequester('http:', 'direct'); + + for (const agent of [undefined, new http.Agent()]) { + const options: http.RequestOptions = { host: '127.0.0.1', port: new URL(origin).port, agent }; + await new Promise((resolve, reject) => { + const sent = requester.request(options, (res) => { + res.resume(); + res.on('end', resolve); + }); + sent.on('error', reject); + sent.end(); + }); + } + + expect(request.mock.calls.map(([options]) => (options as http.RequestOptions).agent)).toEqual([ + direct, + direct, + ]); +}); diff --git a/packages/host-kit/src/direct-http.ts b/packages/host-kit/src/direct-http.ts index 15713e49f3..0a36fede1c 100644 --- a/packages/host-kit/src/direct-http.ts +++ b/packages/host-kit/src/direct-http.ts @@ -1,4 +1,5 @@ import type { Agent, IncomingMessage } from 'node:http'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; // Loaded at send time by the code that sends a credential over plain http, never at module scope. @@ -29,9 +30,23 @@ export function responseHeadersOf(res: IncomingMessage): Headers { return headers; } +const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); +// The silence `fetch` allows while it waits for response headers or the next body bytes. It +// replaces the agent's 5 s timeout, which is for pooled sockets and would end a long command. +const IDLE_TIMEOUT_MS = 300_000; + +const DIRECT_HTTP_REASONS = { + // A plain-http exchange with a loopback peer stayed silent for `details.timeoutMs`. + idleTimeout: { reason: 'direct_http_idle_timeout' }, +} as const satisfies ReasonTable<'remote connection'>; + /** * Sends one Fetch request over `node:http` with `loadDirectHttpAgent`, for a plain-http - * destination that receives a credential. It never follows a redirect: a 3xx is returned as is. + * destination that receives a credential. It never follows a redirect: a 3xx is returned as is, or + * fails the request that asks for `redirect: 'error'`. As with `fetch`, a failed exchange rejects + * with `TypeError('fetch failed')` carrying the cause. An abort ends the exchange with the signal's + * reason, and five silent minutes end it with a `direct_http_idle_timeout` error: the call rejects + * with it, or after the response, the body read does. */ export async function fetchOverDirectHttp(request: Request): Promise { const url = new URL(request.url); @@ -42,9 +57,15 @@ export async function fetchOverDirectHttp(request: Request): Promise { loadDirectHttpAgent('http:'), import('node:stream'), ]); - const body = request.body ? Buffer.from(await request.arrayBuffer()) : undefined; request.signal.throwIfAborted(); return await new Promise((resolve, reject) => { + let response: IncomingMessage | undefined; + const fail = (cause: unknown) => reject(new TypeError('fetch failed', { cause })); + const end = (reason: Error) => { + reject(reason); + response?.destroy(reason); + req.destroy(); + }; const req = http.request( { host: url.hostname.replace(/^\[(.*)\]$/, '$1'), @@ -53,23 +74,70 @@ export async function fetchOverDirectHttp(request: Request): Promise { method: request.method, headers: Object.fromEntries(request.headers), agent, - signal: request.signal, + timeout: IDLE_TIMEOUT_MS, }, (res) => { + response = res; + // The body stream reports an error to its reader; an unread body has no other listener. + res.on('error', () => undefined); const status = res.statusCode ?? 502; - const headers = responseHeadersOf(res); + if (request.redirect === 'error' && REDIRECT_STATUSES.has(status)) { + res.destroy(); + fail(new Error('unexpected redirect')); + return; + } const nullBody = request.method === 'HEAD' || NULL_BODY_STATUSES.has(status); if (nullBody) res.resume(); resolve( new Response(nullBody ? null : (Readable.toWeb(res) as ReadableStream), { status, statusText: res.statusMessage, - headers, + headers: responseHeadersOf(res), }), ); }, ); - req.on('error', reject); - req.end(body); + req.on('timeout', () => { + end( + new AppError('COMMAND_FAILED', 'Plain-http request timed out waiting for the peer', { + reason: DIRECT_HTTP_REASONS.idleTimeout.reason, + timeoutMs: IDLE_TIMEOUT_MS, + }), + ); + }); + const abort = () => end(request.signal.reason as Error); + request.signal.addEventListener('abort', abort, { once: true }); + // This listener also keeps `request` reachable while the exchange lives: its signal follows + // the caller's only that long. + req.once('close', () => request.signal.removeEventListener('abort', abort)); + req.on('error', fail); + if (!request.body) { + req.end(); + return; + } + // Read whole, so the request declares its length. + request.arrayBuffer().then( + (body) => req.end(Buffer.from(body)), + (error: unknown) => { + fail(error); + req.destroy(); + }, + ); }); } + +/** + * Sends one credential-bearing Fetch request. Plain http goes direct through + * `fetchOverDirectHttp`, so an environment proxy never reads the credential in cleartext; anything + * else goes through global `fetch`. The caller has already applied the credential transport rule. + * An injected `send` is the caller's own transport and carries every request. + */ +export async function fetchWithCredential( + input: string | URL, + init: RequestInit = {}, + send?: typeof fetch, +): Promise { + if (send) return await send(input, init); + if (new URL(input).protocol !== 'http:') return await fetch(input, init); + return await fetchOverDirectHttp(new Request(input, init)); +} diff --git a/packages/host-kit/src/internal/transport.ts b/packages/host-kit/src/internal/transport.ts index 463b8d56ff..89cab8438a 100644 --- a/packages/host-kit/src/internal/transport.ts +++ b/packages/host-kit/src/internal/transport.ts @@ -39,8 +39,10 @@ export type NodeHttpRequester = Pick; * property is mutable, which the transport tests rely on to stub requests. * * `credential: 'direct'` is for a request that carries a credential: over plain http (loopback - * only) it connects directly and never through an environment proxy, unless the caller names its - * own `agent`. The requester still calls the module's `request` at send time. + * only) it connects directly and never through an environment proxy. Call that requester as + * `request(options, callback)`, its only form. Its direct agent always replaces an `agent` among + * the options, because any other agent could route the credential through a proxy. It still calls + * the module's `request` at send time. */ export async function loadNodeHttpRequester( protocol: string, @@ -52,7 +54,7 @@ export async function loadNodeHttpRequester( const agent = await (await import('../direct-http.ts')).loadDirectHttpAgent(protocol); return { request: ((options: RequestOptions, callback?: (res: IncomingMessage) => void) => - http.request({ agent, ...options }, callback)) as NodeHttpRequester['request'], + http.request({ ...options, agent }, callback)) as NodeHttpRequester['request'], }; } diff --git a/packages/platform-apple/src/core/runner-host.ts b/packages/platform-apple/src/core/runner-host.ts index 72efa662ff..1bd046939f 100644 --- a/packages/platform-apple/src/core/runner-host.ts +++ b/packages/platform-apple/src/core/runner-host.ts @@ -89,6 +89,8 @@ export const appleRunnerHost: AppleRunnerHost = { shellQuote, emitDiagnostic, withDiagnosticTimer, + fetchWithCredential: async (...args) => + await (await import('@agent-device/host-kit/direct-http')).fetchWithCredential(...args), retryWithPolicy, isEnvTruthy, deadlineFromTimeoutMs: (timeoutMs, nowMs) => Deadline.fromTimeoutMs(timeoutMs, nowMs), diff --git a/packages/proxy/README.md b/packages/proxy/README.md index c7b53ff5f7..9ffd89c3e0 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -130,8 +130,10 @@ Supply `upstreamFetch` if you need those Fetch behaviors or your own routing. A plain-http upstream is loopback, and the default transport reaches it directly over `node:http` on every route. An environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY=1`) never sees the -upstream token. An https upstream follows your runtime's environment-proxy settings: Node 26.11.1 -uses them when `NODE_USE_ENV_PROXY=1`, and Bun 1.4.2 Fetch uses them without that opt-in. +upstream token. As with `fetch`, such a request ends after five minutes of silence from the daemon +(transfer routes keep their own limits above). An https upstream follows your runtime's +environment-proxy settings: Node 26.11.1 uses them when `NODE_USE_ENV_PROXY=1`, and Bun 1.4.2 Fetch +uses them without that opt-in. By default, `/rpc`, `/health` and request diagnostics to an https upstream use global `fetch`. @@ -153,11 +155,12 @@ const proxy = createDaemonProxy({ 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, such as the daemon's `308` resume response, to its client. It relays a -`Location` only when it targets the daemon itself, moved onto the proxy's client-facing origin, and -drops one that points elsewhere, has userinfo, or carries the upstream token. 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. +`Location` only when it targets the daemon itself, as a path on the proxy's client-facing origin +without its query or fragment. It drops one that points elsewhere, has userinfo, or has the +upstream token in its path. 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`. With your own transport, give it a logical URL that meets this rule, such as diff --git a/packages/proxy/src/checked-rpc-admission.ts b/packages/proxy/src/checked-rpc-admission.ts index 4e2b9f7028..ad738b9694 100644 --- a/packages/proxy/src/checked-rpc-admission.ts +++ b/packages/proxy/src/checked-rpc-admission.ts @@ -13,6 +13,7 @@ import { DAEMON_HTTP_RPC_PROTOCOL_HEADER, DAEMON_RPC_PROTOCOL_VERSION, } from '@agent-device/contracts/daemon-http'; +import { isRedirectAnswer } from './upstream-response-relay.ts'; /** The most of an upstream refusal body the proxy reads for its bounded diagnostic values. */ const UPSTREAM_REFUSAL_MAX_BYTES = 64 * 1024; @@ -51,10 +52,7 @@ export async function localCheckedRpcRefusal( request: Request, rpcId: unknown, ): Promise { - if ( - upstreamResponse.redirected || - (upstreamResponse.status >= 300 && upstreamResponse.status < 400) - ) { + if (isRedirectAnswer(upstreamResponse)) { await upstreamResponse.body?.cancel(); throw new AppError('COMMAND_FAILED', 'The daemon answered a checked call with a redirect', { hint: 'The proxy never follows a redirect on the checked route. Point upstreamBaseUrl at the daemon itself.', diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index 309075fbf1..bcf0f4f2b6 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -47,11 +47,13 @@ const checkedRpc = () => rpc('rpc/checked', { [DAEMON_HTTP_RPC_PROTOCOL_HEADER]: String(DAEMON_RPC_PROTOCOL_VERSION) }); test.each([ - ['the default transport', undefined], - ['a custom transport', 'custom'], + ['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'], ] as const)( - '%s never sends the upstream token to plain http off loopback', - async (_label, transport) => { + '%s never sends the upstream token to %s', + async (_label, _destination, upstreamBaseUrl, transport) => { const sent: unknown[] = []; for (const spy of [ vi.spyOn(globalThis, 'fetch'), @@ -71,7 +73,7 @@ test.each([ } : undefined; const proxy = createDaemonProxy({ - upstreamBaseUrl: 'http://daemon.invalid:4310', + upstreamBaseUrl, upstreamToken: 'daemon-secret', clientToken: 'client-secret', ...(upstreamFetch ? { upstreamFetch } : {}), @@ -87,9 +89,7 @@ test.each([ ]) { const response = await proxy.handle(request); expect(response.status, request.url).toBe(400); - expect(await response.text(), request.url).toContain( - 'plain http is allowed only on loopback', - ); + expect(await response.text(), request.url).toContain('Proxy upstreamBaseUrl'); } expect(sent).toEqual([]); }, @@ -105,7 +105,7 @@ test('an upstream redirect is relayed, never followed, so its target receives no const daemon = await serve((req, res) => { req.resume(); res.statusCode = 307; - res.setHeader('location', `${target}${req.url}`); + res.setHeader('location', `${target}/redirected`); res.end(); }); // A logical https URL a transport routes internally: here, global fetch to a loopback daemon, @@ -123,9 +123,10 @@ test('an upstream redirect is relayed, never followed, so its target receives no }), }); - await ( - await proxy.handle(new Request('https://gateway.example.test/agent-device/health')) - ).text(); + const health = await proxy.handle( + new Request('https://gateway.example.test/agent-device/health'), + ); + expect(health.status).toBe(500); expect((await proxy.handle(rpc())).status).toBe(307); expect(reached).toEqual([]); @@ -134,11 +135,23 @@ test('an upstream redirect is relayed, never followed, so its target receives no test.each([ ['a foreign origin', 'http://attacker.example/x?signature=secret', null], ['userinfo', 'https://user:pass@daemon.example.test/artifacts/x', null], - ['the upstream token', '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/artifacts/other?token=daemon-secret', null], + ['the upstream token in its path', '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/artifacts/daemon-secret', null], + ['the percent-encoded upstream token in its path', '/artifacts/daemon%2Dsecret', null], + ['a malformed path escape', '/artifacts/%E0%A4%A', null], + [ + 'the percent-encoded upstream token in its query', + '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/artifacts/other?token=daemon%2Dsecret', + 'https://gateway.example.test/agent-device/artifacts/other', + ], + [ + 'the upstream token in its fragment', + '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/artifacts/other#daemon%2Dsecret', + 'https://gateway.example.test/agent-device/artifacts/other', + ], [ 'the upstream daemon', - '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/artifacts/other?part=2', - 'https://gateway.example.test/agent-device/artifacts/other?part=2', + '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/artifacts/other', + 'https://gateway.example.test/agent-device/artifacts/other', ], ] as const)( 'a relayed Location that names %s is relayed only on the daemon itself', @@ -167,7 +180,7 @@ test('the default transports relay a daemon redirect with its target on every ro const daemon = await serve((req, res) => { req.resume(); res.statusCode = 307; - res.setHeader('location', `${req.url}-moved`); + res.setHeader('location', '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/artifacts/moved'); res.end(); }); const proxy = createDaemonProxy({ @@ -185,10 +198,32 @@ test('the default transports relay a daemon redirect with its target on every ro expect(transfer.status).toBe(307); expect(transfer.headers.get('location')).toBe( - 'https://gateway.example.test/agent-device/artifacts/build-moved', + 'https://gateway.example.test/agent-device/artifacts/moved', ); expect(command.status).toBe(307); expect(command.headers.get('location')).toBe( - 'https://gateway.example.test/agent-device/rpc-moved', + 'https://gateway.example.test/agent-device/artifacts/moved', + ); +}); + +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.ts b/packages/proxy/src/daemon-proxy.ts index ebef28ad16..e69dab91a0 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -36,9 +36,9 @@ import { * proxy. Supply your own to reach the daemon over another 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 to its client, which applies its own redirect rules; - * on the checked RPC route it refuses a 3xx or `redirected` answer instead, but it cannot undo a - * resend the transport already made. + * the upstream token. The proxy relays a 3xx to its client, which applies its own redirect rules. + * 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. * On transfer routes, the proxy bounds its own response and body waits, even if the transport @@ -123,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; }; @@ -356,13 +358,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, }), ); + const { isRedirectAnswer } = await import('./upstream-response-relay.ts'); + if (isRedirectAnswer(response)) { + 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 }; @@ -379,6 +391,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 upstreamUrl = buildUpstreamUrl(options.upstreamBaseUrl, route, request.url); @@ -559,7 +572,7 @@ 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 @@ -573,16 +586,12 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti }, )); const customUpstreamFetch = options.upstreamFetch; - const sendUpstream: DaemonProxyUpstreamFetch = + const upstreamFetch: DaemonProxyUpstreamFetch = customUpstreamFetch ?? (async (request) => new URL(request.url).protocol === 'http:' ? await (await import('@agent-device/host-kit/direct-http')).fetchOverDirectHttp(request) : await fetch(request)); - const upstreamFetch: DaemonProxyUpstreamFetch = async (request) => { - await admitUpstream(); - return await sendUpstream(request); - }; return { upstreamBaseUrl, publicOrigin: @@ -594,10 +603,10 @@ 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); - await admitUpstream(); const { createNodeTransferFetch, settleUpstreamFetch } = await import('./transfer-transport.ts'); return customUpstreamFetch @@ -610,16 +619,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 { diff --git a/packages/proxy/src/upstream-response-relay.ts b/packages/proxy/src/upstream-response-relay.ts index 7000d2f400..ab6e4bc9de 100644 --- a/packages/proxy/src/upstream-response-relay.ts +++ b/packages/proxy/src/upstream-response-relay.ts @@ -28,6 +28,11 @@ export type RelayedResponse = { publicOrigin: string | undefined; }; +/** Whether the upstream answered with a redirect, or its transport reports that it followed one. */ +export function isRedirectAnswer(response: Response): boolean { + return response.redirected || (response.status >= 300 && response.status < 400); +} + /** The headers a proxied response carries: the allowlist, the request id, and a safe `Location`. */ export function relayedResponseHeaders(relay: RelayedResponse): Headers { const headers = new Headers(); @@ -50,18 +55,22 @@ function routeResponseHeaders(route: string): readonly string[] { /** * The `Location` of a relayed upstream 3xx, as the client must see it. Only a target on the - * upstream daemon itself is relayed, moved onto the client-facing origin and base path the request - * came in on. A target elsewhere, with userinfo, or carrying the upstream token is dropped: the - * proxy never hands a client a credential or a foreign destination. + * upstream daemon itself is relayed, as a path moved onto the client-facing origin and base path + * the request came in on. Its query and fragment are dropped: the daemon redirects with neither, + * and both can carry a credential. A target elsewhere, with userinfo, or whose decoded path holds + * the upstream token is dropped whole: the proxy never hands a client a credential or a foreign + * destination. */ function relayedLocation(relay: RelayedResponse): string | undefined { const raw = relay.upstreamResponse.headers.get('location'); - if (!raw || raw.includes(relay.upstreamToken)) return undefined; + if (!raw) return undefined; const target = URL.parse(raw, relay.upstreamUrl); const upstreamBase = new URL(relay.upstreamBaseUrl); if (!target || target.origin !== upstreamBase.origin || target.username || target.password) { return undefined; } + const path = decodedPath(target); + if (path === undefined || path.includes(relay.upstreamToken)) return undefined; const basePath = upstreamBase.pathname.replace(/\/+$/, ''); if (basePath && target.pathname !== basePath && !target.pathname.startsWith(`${basePath}/`)) { return undefined; @@ -72,6 +81,14 @@ function relayedLocation(relay: RelayedResponse): string | undefined { : ''; const relayed = new URL(relay.publicOrigin ?? requestUrl.origin); relayed.pathname = `${prefix}${target.pathname.slice(basePath.length) || '/'}`; - relayed.search = target.search; return relayed.toString(); } + +/** The path as the daemon would read it, or `undefined` for one with a malformed escape. */ +function decodedPath(url: URL): string | undefined { + try { + return decodeURIComponent(url.pathname); + } catch { + return undefined; + } +} diff --git a/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts b/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts index d03b4520d4..845da80e74 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts @@ -507,15 +507,23 @@ test('metro companion worker exits after non-retryable registration failure', as assert.equal(registerAttempts, 1); }); -test.for(['http://bridge.invalid', 'http:'])( +// A base without a host gains one from the appended path: `https://` would reach `https://api/...`. +test.for(['http://bridge.invalid', 'http:', 'https://', 'https:'])( 'metro companion worker never sends its bearer token to %s and exits', async (serverBaseUrl) => { const sent: unknown[] = []; const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { sent.push(input); - return new Response(null, { status: 500 }); + return new Response(null, { status: 401 }); + }); + const requestSpy = vi.spyOn(http, 'request').mockImplementation(((target: unknown) => { + sent.push(target); + throw new Error('nothing may be sent'); + }) as typeof http.request); + cleanupTasks.push(async () => { + fetchSpy.mockRestore(); + requestSpy.mockRestore(); }); - cleanupTasks.push(async () => fetchSpy.mockRestore()); const companion = startMetroCompanionWorker({ bridgePort: 1, @@ -529,6 +537,46 @@ test.for(['http://bridge.invalid', 'http:'])( }, ); +test('metro companion worker reaches a loopback bridge directly, never through global fetch', async () => { + const received: string[] = []; + const registered = createDeferred(); + let bridgePort = 0; + let bridgeSocketRef: Duplex | null = null; + const bridgeServer = http.createServer((req, res) => { + received.push(`${req.url} ${req.headers.authorization}`); + req.resume(); + if (req.url === '/api/metro/companion/register') { + writeSuccessfulRegistration(res, bridgePort); + return; + } + res.end('{}'); + }); + bridgeServer.on('upgrade', (req, socket) => { + bridgeSocketRef = socket; + if (acceptWebSocketUpgrade(req, socket)) registered.resolve(); + }); + cleanupTasks.push(() => closeLoopbackServer(bridgeServer)); + cleanupTasks.push(async () => { + bridgeSocketRef?.destroy(); + }); + bridgePort = await listenOnLoopback(bridgeServer); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); + cleanupTasks.push(async () => fetchSpy.mockRestore()); + + const companion = startMetroCompanionWorker({ + bridgePort, + localPort: 1, + unregisterPath: '/api/metro/companion/unregister', + }); + await Promise.race([waitFor(registered.promise, 5_000, 'bridge socket'), companion.earlyExit]); + bridgeSocketRef!.destroy(); + await companion.stop(); + + assert.equal(received[0], '/api/metro/companion/register Bearer test-token'); + assert.ok(received.includes('/api/metro/companion/unregister Bearer test-token'), `${received}`); + assert.equal(fetchSpy.mock.calls.length, 0); +}); + test('metro companion worker retries registration failures with retry-after delay', async () => { const bridgeSocketReady = createDeferred(); const registerAttemptTimes: number[] = []; 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 3e94c7ea10..07fc8ed71b 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.ts @@ -82,12 +82,11 @@ async function registerCompanion( options: CompanionTunnelWorkerOptions, ): Promise<{ wsUrl: string }> { const registerPath = resolveRegisterPath(options); - const registerUrl = bearerDestination( - `${normalizeBaseUrl(options.serverBaseUrl)}${registerPath}`, - ); + const registerUrl = bearerDestination(options.serverBaseUrl, registerPath); + const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); let response: Response; try { - response = await fetch(registerUrl, { + response = await fetchWithCredential(registerUrl, { method: 'POST', headers: createHeaders(options.serverBaseUrl, options.bearerToken), body: JSON.stringify(buildCompanionPayload(options)), @@ -163,9 +162,15 @@ function clampRetryDelay(delayMs: number): number { return Math.max(0, Math.min(COMPANION_REGISTER_MAX_RETRY_DELAY_MS, Math.ceil(delayMs))); } -/** The final URL a bearer request goes to, or a refusal no retry can fix. */ -function bearerDestination(url: string): string { +/** + * The final URL a bearer request goes to, or a refusal no retry can fix. The base must be a URL + * with a host on its own: appending a path can give one to a base without it (`https://` becomes + * `https://api/...`). + */ +function bearerDestination(serverBaseUrl: string, path: string): string { try { + assertSecureCredentialTransport(serverBaseUrl, 'Metro companion bridge URL'); + const url = `${normalizeBaseUrl(serverBaseUrl)}${path}`; assertSecureCredentialTransport(url, 'Metro companion bridge URL'); return url; } catch (error) { @@ -184,10 +189,9 @@ async function unregisterCompanion(options: CompanionTunnelWorkerOptions): Promi const unregisterPath = resolveUnregisterPath(options); if (!unregisterPath) return; try { - const unregisterUrl = bearerDestination( - `${normalizeBaseUrl(options.serverBaseUrl)}${unregisterPath}`, - ); - await fetch(unregisterUrl, { + const unregisterUrl = bearerDestination(options.serverBaseUrl, unregisterPath); + const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); + await fetchWithCredential(unregisterUrl, { method: 'POST', headers: createHeaders(options.serverBaseUrl, options.bearerToken), body: JSON.stringify(buildCompanionPayload(options)), diff --git a/packages/react-native/src/index-metro.test.ts b/packages/react-native/src/index-metro.test.ts index fa64379eeb..717ec756f1 100644 --- a/packages/react-native/src/index-metro.test.ts +++ b/packages/react-native/src/index-metro.test.ts @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { once } from 'node:events'; import { createHash } from 'node:crypto'; import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { createServer } from 'node:http'; +import http, { createServer } from 'node:http'; import path from 'node:path'; import { prepareMetroRuntime, reloadMetro } from './index.ts'; import { AppError } from '@agent-device/kernel/errors'; @@ -426,6 +426,7 @@ test.for(['http://proxy.example.test', 'http:'])( 'prepareMetroRuntime never sends a bridge bearer token to %s', async (proxyBaseUrl) => { const fetchSpy = vi.spyOn(globalThis, 'fetch'); + const requestSpy = vi.spyOn(http, 'request'); try { await assert.rejects( () => @@ -441,8 +442,10 @@ test.for(['http://proxy.example.test', 'http:'])( error instanceof AppError && error.details?.reason === 'insecure_credential_transport', ); assert.equal(fetchSpy.mock.calls.length, 0); + assert.equal(requestSpy.mock.calls.length, 0); } finally { fetchSpy.mockRestore(); + requestSpy.mockRestore(); } }, ); 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..15591ed40f 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,6 +1,8 @@ import { afterEach, test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; import path from 'node:path'; import { mkdtempForTestSync, createTestHostEnvironment } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; @@ -550,3 +552,48 @@ test('prepareMetroRuntime retries malformed retryable bridge responses after com fs.rmSync(tempRoot, { recursive: true, force: true }); } }); + +test('a loopback bridge gets the bearer token directly, never through global fetch', async () => { + const projectRoot = mkdtempForTestSync('agent-device-metro-direct-bridge-'); + fs.mkdirSync(path.join(projectRoot, 'node_modules')); + fs.writeFileSync( + path.join(projectRoot, 'package.json'), + JSON.stringify({ name: 'direct-bridge', dependencies: { 'react-native': '0.0.0-test' } }), + ); + const received: string[] = []; + const bridge = http.createServer((req, res) => { + received.push(`${req.method} ${req.url} ${req.headers.authorization}`); + req.resume(); + res.writeHead(401).end('{"ok":false}'); + }); + await new Promise((resolve) => bridge.listen(0, '127.0.0.1', resolve)); + // The dev server probe carries no credential and stays on global fetch. + const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => { + return new Response('packager-status:running'); + }); + vi.stubGlobal('fetch', fetchMock); + + try { + await assert.rejects(() => + prepareMetroRuntime( + { + projectRoot, + proxyBaseUrl: `http://127.0.0.1:${(bridge.address() as AddressInfo).port}`, + proxyBearerToken: 'shared-token', + bridgeScope: TEST_BRIDGE_SCOPE, + metroPort: 8081, + reuseExisting: true, + installDependenciesIfNeeded: false, + }, + createTestHostEnvironment(), + ), + ); + + assert.deepEqual(received, ['POST /api/metro/bridge Bearer shared-token']); + assert.equal(JSON.stringify(fetchMock.mock.calls).includes('shared-token'), false); + } finally { + vi.unstubAllGlobals(); + bridge.closeAllConnections(); + await new Promise((resolve) => bridge.close(() => resolve())); + } +}); diff --git a/packages/react-native/src/metro/client-metro.ts b/packages/react-native/src/metro/client-metro.ts index fb98adfc24..92c6db153f 100644 --- a/packages/react-native/src/metro/client-metro.ts +++ b/packages/react-native/src/metro/client-metro.ts @@ -457,10 +457,11 @@ async function configureMetroBridge(input: ProxyBridgeRequestOptions): Promise diff --git a/src/cli/__tests__/cloud-auth-request.test.ts b/src/cli/__tests__/cloud-auth-request.test.ts index 54dcc02f8d..b211e0604c 100644 --- a/src/cli/__tests__/cloud-auth-request.test.ts +++ b/src/cli/__tests__/cloud-auth-request.test.ts @@ -1,11 +1,11 @@ -import { afterEach, expect, test } from 'vitest'; +import { afterEach, expect, test, vi } from 'vitest'; import http from 'node:http'; import type { AddressInfo } from 'node:net'; import { normalizeError } from '@agent-device/kernel/errors'; import { postCloudAuthJson } from '../cloud-auth-request.ts'; -// These tests use Node's own fetch against loopback servers, so they prove that no redirect is -// followed by fetch itself and that a refused target never receives a request. +// These tests send over the real transport to loopback servers, so they prove that the transport +// follows no redirect itself and that a refused target never receives a request. type Received = { method?: string; path?: string; body: string; contentType?: string }; /** A canned response. Routes are data, so no handler is ever chosen by the request path. */ @@ -14,6 +14,7 @@ type Route = { status: number; headers: Record; body: string }; const servers: http.Server[] = []; afterEach(async () => { + vi.restoreAllMocks(); await Promise.all( servers.splice(0).map( (server) => @@ -179,3 +180,13 @@ test('a cloud base URL over plain http off loopback is refused before anything i expect(refusal).toMatchObject({ details: { reason: 'insecure_credential_transport' } }); expect(sent).toBe(0); }); + +test('a loopback cloud is reached directly, never through global fetch and its proxy', async () => { + const cloud = await listen(); + cloud.routes.set('/start', answer); + const proxied = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); + + expect(await post(cloud.origin)).toEqual({ accessToken: 'adc_agent' }); + expect(cloud.received).toEqual([posted('/start')]); + expect(proxied).not.toHaveBeenCalled(); +}); diff --git a/src/cli/cloud-auth-request.ts b/src/cli/cloud-auth-request.ts index 1d6c889066..0173f7968a 100644 --- a/src/cli/cloud-auth-request.ts +++ b/src/cli/cloud-auth-request.ts @@ -55,16 +55,22 @@ export async function postCloudAuthJson(options: { export async function fetchCloudOnOneOrigin( requestUrl: URL, request: RequestInit, - // di-seam-approved: the same fetch-global seam as postCloudAuthJson's fetchImpl. - fetchImpl: typeof fetch = fetch, + // di-seam-approved: the same fetch-global seam as postCloudAuthJson's fetchImpl. Without it, + // plain http (loopback only) goes direct, never through an environment proxy. + fetchImpl?: typeof fetch, ): Promise { assertSecureCredentialTransport(requestUrl, 'Cloud base URL'); + const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); // One timeout covers the whole redirect chain. const signal = AbortSignal.timeout(HTTP_TIMEOUT_MS); let url = requestUrl; let init = request; for (let redirects = 0; ; redirects += 1) { - const response = await fetchImpl(url, { ...init, redirect: 'manual', signal }); + const response = await fetchWithCredential( + url, + { ...init, redirect: 'manual', signal }, + fetchImpl, + ); if (!REDIRECT_STATUSES.has(response.status)) return response; await response.body?.cancel().catch(() => undefined); url = readRedirectTarget(response, url, requestUrl, redirects); diff --git a/src/cli/connection/cloud-profile-transport.test.ts b/src/cli/connection/cloud-profile-transport.test.ts index f0cc71c749..3bb67e4211 100644 --- a/src/cli/connection/cloud-profile-transport.test.ts +++ b/src/cli/connection/cloud-profile-transport.test.ts @@ -4,6 +4,7 @@ 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 { connectCommand } from '../commands/connection.ts'; import { resolveCloudAccessForConnect } from '../auth-session.ts'; @@ -24,6 +25,7 @@ vi.mock('../auth-session.ts', async (importOriginal) => ({ })); afterEach(() => { + vi.restoreAllMocks(); vi.clearAllMocks(); vi.unstubAllGlobals(); }); @@ -59,6 +61,10 @@ async function connectCloudAt( return answer(); }), ); + vi.spyOn(http, 'request').mockImplementation(((target: unknown) => { + urls.push(JSON.stringify(target)); + throw new Error('nothing may be sent over plain http'); + }) as typeof http.request); try { const refusal = await connectCloud(path.join(tempRoot, '.state')).then( () => assert.fail('expected connect cloud to be refused'), diff --git a/src/core/interactors/limrun-ios-files.test.ts b/src/core/interactors/limrun-ios-files.test.ts index d3015aef8a..2228ca5e3e 100644 --- a/src/core/interactors/limrun-ios-files.test.ts +++ b/src/core/interactors/limrun-ios-files.test.ts @@ -4,6 +4,7 @@ import { createLimrunAppleToolProvider } from './limrun-ios-tools.ts'; import { withAppleToolProvider } from '@agent-device/platform-apple/tool-provider'; import { resolveIosSimulatorDeepLinkBundleId } from '@agent-device/platform-apple/app-resolution'; import { promises as fs } from 'node:fs'; +import http from 'node:http'; import path from 'node:path'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; @@ -380,6 +381,7 @@ test('a provider API URL over plain http off loopback never receives the instanc const local = path.join(f.directory, 'push.apns'); await fs.writeFile(local, '{}'); const fetchSpy = vi.spyOn(globalThis, 'fetch'); + const requestSpy = vi.spyOn(http, 'request'); try { const session = { ...f.session, apiUrl: 'http://limrun.invalid/v1/ios_test/api' }; const tools = createLimrunAppleToolProvider(session, new AbortController().signal); @@ -387,6 +389,33 @@ test('a provider API URL over plain http off loopback never receives the instanc details: { reason: 'insecure_credential_transport' }, }); expect(fetchSpy).not.toHaveBeenCalled(); + expect(requestSpy).not.toHaveBeenCalled(); + } finally { + fetchSpy.mockRestore(); + requestSpy.mockRestore(); + } +}); + +test('loopback file requests and downloads never go through global fetch', async () => { + const f = await fixture({ + containers: { 'com.example.app': { app: { 'Info.plist': plist('exp+example') } } }, + }); + const local = path.join(f.directory, 'push.apns'); + await fs.writeFile(local, '{}'); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); + try { + const tools = createLimrunAppleToolProvider(f.session, new AbortController().signal); + await (await tools.simulatorFiles.stageFile(local))[Symbol.asyncDispose](); + await expect( + tools.simulatorApps.readInfoPlist({ + device: f.device, + bundleId: 'com.example.app', + timeoutMs: 5_000, + }), + ).resolves.toMatchObject({ CFBundleExecutable: 'Example' }); + + expect(f.storage.calls.map((call) => call.method)).toEqual(['PUT', 'DELETE', 'GET']); + 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 6cd19ac844..146635a23f 100644 --- a/src/core/interactors/limrun-ios-files.ts +++ b/src/core/interactors/limrun-ios-files.ts @@ -64,16 +64,20 @@ export function createLimrunSimulatorFiles( }; const request = async (method: string, url: URL, signal: AbortSignal, body?: Uint8Array) => { signal.throwIfAborted(); - const response = await fetch(assertSecureCredentialTransport(url, 'Limrun API URL'), { - method, - headers: { - Authorization: `Bearer ${session.token}`, - ...(body ? { 'Content-Type': 'application/octet-stream' } : {}), + const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); + const response = await fetchWithCredential( + assertSecureCredentialTransport(url, 'Limrun API URL'), + { + method, + headers: { + Authorization: `Bearer ${session.token}`, + ...(body ? { 'Content-Type': 'application/octet-stream' } : {}), + }, + body: body as BodyInit | undefined, + signal, + redirect: 'error', }, - body: body as BodyInit | undefined, - signal, - redirect: 'error', - }); + ); if (!response.ok) { await response.body?.cancel(); throw new AppError('COMMAND_FAILED', `Limrun file ${method} failed (${response.status})`, { diff --git a/src/core/interactors/limrun-ios-runner-products.ts b/src/core/interactors/limrun-ios-runner-products.ts index 18c552247e..20e5917b7e 100644 --- a/src/core/interactors/limrun-ios-runner-products.ts +++ b/src/core/interactors/limrun-ios-runner-products.ts @@ -249,10 +249,11 @@ export async function uploadLimrunRunnerProducts( } const syncUrl = `${apiUrl}/sync`; assertSecureCredentialTransport(syncUrl, 'Limrun API URL'); + const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); const stream = createGzip(); const compression = pipeline(Readable.from(body()), stream, { signal }).catch(() => {}); try { - const response = await fetch(syncUrl, { + const response = await fetchWithCredential(syncUrl, { method: 'POST', headers: { Authorization: `Bearer ${token}`, diff --git a/src/core/interactors/limrun-ios-runner.test.ts b/src/core/interactors/limrun-ios-runner.test.ts index d39348077a..336d2f50d0 100644 --- a/src/core/interactors/limrun-ios-runner.test.ts +++ b/src/core/interactors/limrun-ios-runner.test.ts @@ -48,6 +48,22 @@ test('stages a token-authenticated runner once and presents forwarded XCTest sna ).rejects.toThrow(); }); +test('a loopback instance gets sync, launch and runner calls without global fetch', async () => { + const f = await fixture(); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); + try { + await f.runner.createInteractor().snapshot({ appBundleId: 'com.apple.Preferences' }); + + expect(f.uploads.length).toBeGreaterThan(0); + expect(f.requests.filter((url) => url.endsWith('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/xctest/run'))).toHaveLength(1); + expect(f.command).toMatchObject({ command: 'snapshot' }); + expect(fetchSpy).not.toHaveBeenCalled(); + await f.runner.dispose(); + } 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..ffaff9f175 100644 --- a/src/core/interactors/limrun-ios-runner.ts +++ b/src/core/interactors/limrun-ios-runner.ts @@ -163,11 +163,12 @@ 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)]); + const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); response = await retryWithPolicy( async () => { runRequested = true; const result = await awaitWithSignal( - fetch(`${apiUrl}/xctest/run`, { + fetchWithCredential(`${apiUrl}/xctest/run`, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index 70bb94df22..8199af8381 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -10,6 +10,7 @@ import { downloadLimrunFile } from './limrun-download-file.ts'; const servers: http.Server[] = []; afterEach(async () => { + vi.restoreAllMocks(); await Promise.all( servers.splice(0).map( (server) => @@ -201,19 +202,111 @@ test.each(['default', 'typed', 'deadline'] as const)( }, ); -test('a provider download URL over plain http off loopback never receives the bearer token', async () => { - const fetchSpy = vi.spyOn(globalThis, 'fetch'); - try { +async function download(url: string): Promise { + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + await downloadLimrunFile({ + url, + headers: { Authorization: 'Bearer instance-token' }, + destinationPath, + timeoutMs: 5_000, + }); + return destinationPath; +} + +const insecure = { details: { reason: 'insecure_credential_transport' } }; +const refusedRedirect = { details: { reason: 'limrun_download_redirect_refused' } }; +const redirectTo = (location: string) => new Response(null, { status: 302, headers: { location } }); + +const downloadHeaders: Array> = [ + { Authorization: 'Bearer instance-token' }, + {}, +]; + +test.each(downloadHeaders)( + 'a provider download URL over plain http off loopback is never requested, with headers %j', + async (headers) => { + const fetchSpy = vi.spyOn(globalThis, 'fetch'); + const requestSpy = vi.spyOn(http, 'request'); + await expect( downloadLimrunFile({ - url: 'http://limrun.invalid/files?name=recording.mp4', - headers: { Authorization: 'Bearer instance-token' }, + url: 'http://limrun.invalid/files?signature=signed', + headers, destinationPath: path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'), timeoutMs: 5_000, }), - ).rejects.toMatchObject({ details: { reason: 'insecure_credential_transport' } }); + ).rejects.toMatchObject(insecure); + expect(fetchSpy).not.toHaveBeenCalled(); - } finally { - fetchSpy.mockRestore(); - } + expect(requestSpy).not.toHaveBeenCalled(); + }, +); + +test('an https download redirected to plain http off loopback sends nothing there', async () => { + const sent: string[] = []; + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + sent.push(`${String(input)} ${init?.redirect}`); + return redirectTo('http://limrun.invalid/files?signature=signed'); + }); + const requestSpy = vi.spyOn(http, 'request'); + + await expect(download('https://limrun.example/files')).rejects.toMatchObject(refusedRedirect); + + expect(sent).toEqual(['https://limrun.example/files manual']); + expect(requestSpy).not.toHaveBeenCalled(); +}); + +test('a redirect off https to another origin is refused before its target is contacted', async () => { + const reached: string[] = []; + const target = new URL( + await serve((request, response) => { + reached.push(request.url ?? ''); + response.end('payload'); + }), + ); + const origin = await serve((_request, response) => { + response.writeHead(307, { location: target.href }).end(); + }); + + await expect(download(origin)).rejects.toMatchObject(refusedRedirect); + + expect(reached).toEqual([]); +}); + +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')]); + return sent.length === 1 + ? redirectTo('https://storage.example/clip?signature=signed') + : new Response('payload'); + }); + + const destinationPath = await download('https://limrun.example/files'); + + expect(fs.readFileSync(destinationPath, 'utf8')).toBe('payload'); + expect(sent).toEqual([ + ['https://limrun.example/files', 'Bearer instance-token'], + ['https://storage.example/clip?signature=signed', null], + ]); +}); + +test('a same-origin redirect is followed with the headers, at most five times', async () => { + const seen: string[] = []; + const url = await serve((request, response) => { + seen.push(`${request.url} ${request.headers.authorization}`); + if (seen.length === 1) response.writeHead(302, { location: '/clip' }).end(); + else response.end('payload'); + }); + + expect(fs.readFileSync(await download(url), 'utf8')).toBe('payload'); + expect(seen.at(-1)).toBe('/clip Bearer instance-token'); + + let hops = 0; + const loop = await serve((_request, response) => { + hops += 1; + response.writeHead(302, { location: '/again' }).end(); + }); + await expect(download(loop)).rejects.toMatchObject(refusedRedirect); + expect(hops).toBe(6); }); diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index 7794405751..73f5d1c2a0 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -12,6 +12,8 @@ import type { LimrunFileDownload } from '@agent-device/provider-limrun'; import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; const RESPONSE_BODY_PREVIEW_BYTES = 500; +const MAX_DOWNLOAD_REDIRECTS = 5; +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. @@ -22,6 +24,9 @@ const LIMRUN_DOWNLOAD_REASONS = { timeout: { reason: 'limrun_download_timeout' }, // The transfer broke for a reason the service never answered with, kept in `details.cause`. failed: { reason: 'limrun_download_failed' }, + // The download got a redirect it does not follow: off https to another origin, to a URL with a + // username or password or one that does not parse, or past the fifth hop. Nothing was sent there. + redirectRefused: { reason: 'limrun_download_redirect_refused' }, } as const satisfies ReasonTable<'limrun'>; /** @@ -30,19 +35,11 @@ const LIMRUN_DOWNLOAD_REASONS = { * same URL and never mistakes an earlier attempt's file for this one's. */ export async function downloadLimrunFile(options: LimrunFileDownload): Promise { - // The URL comes from the provider, and the headers carry its bearer token. - if (options.headers && Object.keys(options.headers).length > 0) { - 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, - }); + const response = await fetchDownload(options, signal); if (!response.ok) throw await httpFailure(response, options); if (!response.body) { throw new AppError('COMMAND_FAILED', 'Limrun download returned no body', { @@ -60,6 +57,43 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise { + const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); + let url = assertSecureCredentialTransport(options.url, 'Limrun download URL'); + let headers = options.headers; + for (let redirects = 0; ; redirects += 1) { + const response = await fetchWithCredential(url.href, { + method: 'GET', + headers, + redirect: 'manual', + signal, + }); + const location = response.headers.get('location'); + if (!REDIRECT_STATUSES.has(response.status) || location === null) return response; + await response.body?.cancel().catch(() => undefined); + const target = URL.parse(location, url); + if (!target || !isFollowedRedirect(url, target) || redirects >= MAX_DOWNLOAD_REDIRECTS) { + throw new AppError('COMMAND_FAILED', 'Limrun download answered with a refused redirect', { + reason: LIMRUN_DOWNLOAD_REASONS.redirectRefused.reason, + statusCode: response.status, + }); + } + if (target.origin !== url.origin) headers = {}; + url = assertSecureCredentialTransport(target, 'Limrun download URL'); + } +} + +function isFollowedRedirect(from: URL, to: URL): boolean { + if (to.username || to.password) return false; + return (from.protocol === 'https:' && to.protocol === 'https:') || to.origin === from.origin; +} + 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 4b1164084d..b6a248e55d 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -208,7 +208,7 @@ "packages/daemon/src/server/http/http-checked-rpc.ts#refuseCheckedRpcCredential": "sha256:5594a47e90079eaf31eeb335c709451f8e60616511a4ec84d7248722a37b93ea", "packages/daemon/src/server/http/http-checked-rpc.ts#withUnregisteredTrackingId": "sha256:fffc54ad047879605f532801118868fd0aed1db38b74d671b65325551cc8fe0a", "packages/daemon/src/server/http/http-checked-rpc.ts#readFrameParams": "sha256:8ccdb4a3b91a585be7c1518d198f34f608905c62b8eba9aad12b62a4107f5f31", - "packages/proxy/src/checked-rpc-admission.ts#localCheckedRpcRefusal": "sha256:017a05ac5b415d33030a30c99529a9dd58bb19aeae5649d15a6e00740fe84d95", + "packages/proxy/src/checked-rpc-admission.ts#localCheckedRpcRefusal": "sha256:05188deadff5a2a1e09faaeb2a500af5499dafc8183d18e4290d88f23a24d408", "packages/proxy/src/checked-rpc-admission.ts#refusalResponse": "sha256:10872cc1096a6c3262de9a2dccfb1fa447b67107322894a7289116575de9b4b7", "packages/proxy/src/checked-rpc-admission.ts#localRequestId": "sha256:1bd486b7d70c727c2cab6330fc78f65e1922126be2e38d615f39c1b36acf9eb4", "packages/proxy/src/checked-rpc-admission.ts#readUpstreamRefusalDetails": "sha256:4789d8cffbee31ce2c3c33184751bd11498365aa72e7b37e3b46c432e941920c", diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 60d9bca798..6bf209f626 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -818,6 +818,7 @@ These reasons can come from more than one command. | `limrun_download_http_error` | The service answered the download with an error status; `details.statusCode` and `details.body` carry its reply. | | `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`. | +| `limrun_download_redirect_refused` | The download got a redirect it does not follow: off https to another origin, to a URL with a username or password or one that does not parse, or past the fifth hop. Nothing was sent there. | ### Limrun provider @@ -904,6 +905,7 @@ These reasons can come from more than one command. | `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. | | `remote_checked_rpc_unsupported` | The connection sets `daemonRpc: checked`, but the remote does not serve checked RPC: `connect` found no `checked-rpc` capability in its `/health`, or a command got the route answered as unknown. A command is never resent, because an ingress may have answered for one that ran. Update the remote daemon or proxy, or remove `daemonRpc` from the connection. | +| `direct_http_idle_timeout` | A plain-http exchange with a loopback peer stayed silent for `details.timeoutMs`. | | `REMOTE_SESSION_REQUIRED` | A command on a leased remote connection, or one that would lease one, named no session. | | `CONNECTION_DEVICE_CONFLICT` | The connection is bound to another device, or its lease was allocated by another device spec; `details.keys` names the disagreeing keys, and is present only for a device-spec mismatch. | | `CONNECTION_PLATFORM_CONFLICT` | The connection is bound to another platform, or the request names one its lease backend does not rent. | diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 5857d161a9..6629d3554d 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -21,7 +21,7 @@ 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. -A client never sends a daemon, proxy, Metro host bridge, or cloud auth credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect; it relays the redirect response to its client, whose requests follow at most a same-origin redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, such as Limrun API and download URLs, are checked right before each request. +A client never sends a daemon, proxy, Metro host bridge, or cloud auth credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect; it relays the redirect response to its client, whose requests follow at most a same-origin redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, such as Limrun API and download URLs, are checked right before each request. A Limrun download follows a redirect only from https to https or on the same origin, and drops its headers when it leaves the origin. 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. From 7f7168a241614c3fdac3996e7031a062bf56ccab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 14:49:03 +0100 Subject: [PATCH 10/22] fix(remote): cover the Revyl client and the Metro bridge socket - Revyl sends loopback http through the direct requester, so an environment proxy never sees the API key, and refuses a presigned upload URL that is neither https nor loopback http - the Metro companion opens the registered bridge socket only over wss, or ws to loopback, and refuses it before the socket opens - a loopback bridge socket connects directly through undici, because the global WebSocket sends its URL to an environment proxy Co-Authored-By: Claude Sonnet 5.5 --- .../src/credential-transport.test.ts | 29 ++- .../contracts/src/credential-transport.ts | 11 + .../provider-revyl/src/revyl-client.test.ts | 69 ++++++- packages/provider-revyl/src/revyl-client.ts | 21 +- packages/react-native/package.json | 3 +- ...tunnel-worker-credential-transport.test.ts | 189 ++++++++++++++++++ .../client-companion-tunnel-worker.test.ts | 72 +------ .../client-companion-tunnel-worker.ts | 31 ++- pnpm-lock.yaml | 3 + website/docs/docs/security-trust.md | 2 +- 10 files changed, 347 insertions(+), 83 deletions(-) create mode 100644 packages/react-native/src/companion/client-companion-tunnel-worker-credential-transport.test.ts diff --git a/packages/contracts/src/credential-transport.test.ts b/packages/contracts/src/credential-transport.test.ts index 7503682263..f288034812 100644 --- a/packages/contracts/src/credential-transport.test.ts +++ b/packages/contracts/src/credential-transport.test.ts @@ -1,6 +1,9 @@ import { expect, test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { assertSecureCredentialTransport } from './credential-transport.ts'; +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', () => { @@ -44,3 +47,27 @@ test.each([ 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', 'https:'], + ['https://bridge.example.test/bridge', 'https:'], + ['ws://127.0.0.1:4310/bridge?ticket=t', 'http:'], + ['WS://[::1]:4310/bridge', 'http:'], + ['http://localhost:4310/bridge', 'http:'], +])('a credential socket may open to %s', (url, protocol) => { + expect(assertSecureCredentialSocket(url, 'Bridge socket URL').protocol).toBe(protocol); +}); + +test.each([ + 'ws://bridge.example.test/bridge?ticket=t', + 'ws://10.0.0.7:4310/bridge', + 'http://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' }), + }), + ); +}); diff --git a/packages/contracts/src/credential-transport.ts b/packages/contracts/src/credential-transport.ts index 06bc4c25f7..0691829304 100644 --- a/packages/contracts/src/credential-transport.ts +++ b/packages/contracts/src/credential-transport.ts @@ -37,3 +37,14 @@ export function assertSecureCredentialTransport(url: string | URL, subject: stri }, ); } + +/** + * The same rule for a WebSocket that carries a credential: `wss` counts as https, and `ws` as plain + * http, so loopback only. Returns the destination in that http(s) form. + */ +export function assertSecureCredentialSocket(url: string, subject: string): URL { + const destination = URL.parse(url); + if (destination?.protocol === 'wss:') destination.protocol = 'https:'; + if (destination?.protocol === 'ws:') destination.protocol = 'http:'; + return assertSecureCredentialTransport(destination ?? url, subject); +} diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index 098e6076e4..f98a4cdce5 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -1,5 +1,8 @@ import assert from 'node:assert/strict'; -import { test } from 'vitest'; +import fs from 'node:fs/promises'; +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { test, vi } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; import { createRevylClient, @@ -22,6 +25,70 @@ test('uses the public Revyl backend when no URL is configured', () => { assert.equal(client.backendUrl, REVYL_DEFAULT_BACKEND_URL); }); +test('a loopback backend and upload URL are reached directly, never through global fetch', async () => { + const received: string[] = []; + const server = http.createServer((req, res) => { + received.push(`${req.method} ${req.url} ${req.headers.authorization ?? ''}`.trim()); + req.resume(); + req.on('end', () => res.end('{}')); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + const proxied = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); + try { + const client = createRevylClient({ + apiKey: 'test-key', + backendUrl: origin, + clientVersion: '0.0.0-test', + }); + await client.verifyCredentials(); + await client.uploadSessionArtifact( + `${origin}/upload?signature=signed`, + { filePath: import.meta.filename, size: (await fs.stat(import.meta.filename)).size }, + 'application/zip', + ); + + assert.deepEqual(received, [ + 'GET /api/v1/entity/users/get_user_uuid Bearer test-key', + 'PUT /upload?signature=signed', + ]); + assert.equal(proxied.mock.calls.length, 0); + } finally { + proxied.mockRestore(); + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +test('a presigned upload URL over plain http off loopback receives nothing', async () => { + const sent: unknown[] = []; + const requestSpy = vi.spyOn(http, 'request'); + const client = createRevylClient({ + apiKey: 'test-key', + clientVersion: '0.0.0-test', + fetch: stubFetch((request) => { + sent.push(request.url); + return jsonResponse({}); + }), + }); + try { + 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, []); + assert.equal(requestSpy.mock.calls.length, 0); + } finally { + requestSpy.mockRestore(); + } +}); + 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 11caa8523a..99491eca9c 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -5,6 +5,7 @@ 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 { Readable } from 'node:stream'; @@ -95,6 +96,9 @@ type RevylProviderReason = */ type RevylRoute = 'session' | 'general'; +/** Sends one request that carries the API key or a presigned URL. */ +type RevylTransmit = (url: string | URL, init: RequestInit) => Promise; + type RevylRequest = Readonly<{ method: 'GET' | 'POST'; path: string; @@ -175,7 +179,12 @@ export type RevylClient = Readonly<{ export function createRevylClient(options: RevylClientOptions): RevylClient { const backendUrl = resolveRevylBackendUrl(options.backendUrl ?? REVYL_DEFAULT_BACKEND_URL); - const fetchImpl = options.fetch ?? fetch; + // Without an injected `fetch`, plain http (loopback only) goes direct, never through an + // environment proxy. + const transmit: RevylTransmit = async (url, init) => { + const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); + return await fetchWithCredential(url, init, options.fetch); + }; const baseHeaders = { Authorization: `Bearer ${options.apiKey}`, Accept: 'application/json', @@ -187,7 +196,7 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { const retry = request.retry ?? request.method === 'GET'; const attempts = retry ? RETRY_DELAYS_MS.length + 1 : 1; for (let attempt = 1; ; attempt += 1) { - const outcome = await sendOnce(backendUrl, fetchImpl, baseHeaders, request); + const outcome = await sendOnce(backendUrl, transmit, baseHeaders, request); if (!isRetryable(request, outcome) || attempt >= attempts || request.signal?.aborted) { if (outcome instanceof Error) throw outcome; return outcome; @@ -300,6 +309,8 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { }); }, async uploadSessionArtifact(uploadUrl, file, contentType, signal) { + // Revyl chooses this URL, and its signature is the credential. + 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', @@ -312,7 +323,7 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { }; let response: Response; try { - response = await fetchImpl(uploadUrl, init); + response = await transmit(uploadUrl, init); } catch (error) { throw new AppError( 'COMMAND_FAILED', @@ -359,7 +370,7 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { async function sendOnce( backendUrl: string, - fetchImpl: typeof fetch, + transmit: RevylTransmit, baseHeaders: Record, request: RevylRequest, ): Promise { @@ -369,7 +380,7 @@ async function sendOnce( if (request.workerAction) headers['X-Revyl-Agent'] = REVYL_ATTRIBUTION; if (request.body !== undefined) headers['Content-Type'] = 'application/json'; try { - const response = await fetchImpl(new URL(request.path, backendUrl), { + const response = await transmit(new URL(request.path, backendUrl), { method: request.method, headers, body: request.body === undefined ? undefined : JSON.stringify(request.body), diff --git a/packages/react-native/package.json b/packages/react-native/package.json index e2a2bae199..127fa39687 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -17,6 +17,7 @@ } }, "devDependencies": { - "@agent-device/test-kit": "workspace:*" + "@agent-device/test-kit": "workspace:*", + "undici": "7.30.1" } } 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..692e99ce95 --- /dev/null +++ b/packages/react-native/src/companion/client-companion-tunnel-worker-credential-transport.test.ts @@ -0,0 +1,189 @@ +// The companion's bearer token and its bridge socket URL never leave this machine in cleartext: not +// to a plain destination off loopback, and not through an environment proxy. + +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 path from 'node:path'; +import type { Duplex } from 'node:stream'; +import { afterEach, test, vi } from 'vitest'; +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 } 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` resolves when it exits, and `stop` ends its lease first. */ +function startWorker(serverBaseUrl: string) { + const statePath = path.join(mkdtempForTestSync('metro-companion-transport-'), 'state.json'); + fs.writeFileSync(statePath, '{}'); + const done = runCompanionTunnelWorker( + { + serverBaseUrl, + bearerToken: 'test-token', + localBaseUrl: 'http://127.0.0.1:1', + 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; + }; + cleanupTasks.push(stop); + return { done, stop }; +} + +/** A loopback bridge whose registration answers `wsUrl(port)`, recording what reaches it. */ +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 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) => { + received.push(`UPGRADE ${req.url}`); + socketRef = socket; + if (acceptWebSocketUpgrade(req, socket)) upgrade(socket); + }); + cleanupTasks.push(() => closeLoopbackServer(server)); + cleanupTasks.push(async () => socketRef?.destroy()); + port = await listenOnLoopback(server); + return { origin: `http://127.0.0.1:${port}`, received, upgraded }; +} + +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', 'http:', 'https://', 'https:'])( + 'the worker never sends its bearer token to %s and exits', + async (serverBaseUrl) => { + const sent: unknown[] = []; + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { + sent.push(input); + return new Response(null, { status: 401 }); + }); + vi.spyOn(http, 'request').mockImplementation(((target: unknown) => { + sent.push(target); + throw new Error('nothing may be sent'); + }) as typeof http.request); + + await startWorker(serverBaseUrl).done; + + assert.deepEqual(sent, []); + }, +); + +test('the worker reaches a loopback bridge directly, never through global fetch', async () => { + const bridge = await listenBridge((port) => `ws://127.0.0.1:${port}/bridge`); + const proxied = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); + const worker = startWorker(bridge.origin); + + (await bridge.upgraded).destroy(); + await worker.stop(); + + assert.equal(bridge.received[0], registered); + assert.ok(bridge.received.includes(unregistered), `${bridge.received}`); + assert.equal(proxied.mock.calls.length, 0); +}); + +// `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 bridge. +test.for([ + (port: number) => `ws://0.0.0.0:${port}/bridge?ticket=secret`, + (port: number) => `ws://0.0.0.0:${port}/bridge`, + (port: number) => `http://0.0.0.0:${port}/bridge?ticket=secret`, +])('the worker refuses a plain socket off loopback before it opens', async (wsUrl) => { + const bridge = await listenBridge(wsUrl); + + await startWorker(bridge.origin).done; + + assert.deepEqual(bridge.received, [registered, unregistered]); +}); + +test('the worker opens a loopback socket around an environment proxy', async () => { + const proxied: string[] = []; + const proxy = http.createServer((req, res) => { + proxied.push(`${req.method} ${req.url}`); + res.writeHead(502).end(); + }); + for (const event of ['upgrade', 'connect'] as const) { + proxy.on(event, (req: http.IncomingMessage, socket: Duplex) => { + proxied.push(`${event} ${req.url}`); + socket.destroy(); + }); + } + cleanupTasks.push(() => closeLoopbackServer(proxy)); + const proxyUrl = `http://127.0.0.1:${await listenOnLoopback(proxy)}`; + const bridge = await listenBridge((port) => `ws://127.0.0.1:${port}/bridge?ticket=secret`); + + // Node reads `NODE_USE_ENV_PROXY` at startup, so this worker runs as its own process. + const child = 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', + NODE_USE_ENV_PROXY: '1', + HTTP_PROXY: proxyUrl, + http_proxy: proxyUrl, + NO_PROXY: '', + no_proxy: '', + }, + stdio: 'ignore', + }, + ); + const exited = once(child, 'exit'); + cleanupTasks.push(async () => { + child.kill('SIGKILL'); + await exited; + }); + + await Promise.race([ + bridge.upgraded, + exited.then(() => assert.fail('the worker exited before it opened the bridge socket')), + ]); + + assert.deepEqual(bridge.received, [registered, 'UPGRADE /bridge?ticket=secret']); + assert.deepEqual(proxied, []); +}); diff --git a/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts b/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts index 845da80e74..76ff42db9f 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.test.ts @@ -5,7 +5,7 @@ import http from 'node:http'; import path from 'node:path'; import type { Duplex } from 'node:stream'; import { setTimeout as delay } from 'node:timers/promises'; -import { afterEach, test, vi } from 'vitest'; +import { afterEach, test } from 'vitest'; import { buildCompanionPayload, runCompanionTunnelProcessFromEnv, @@ -507,76 +507,6 @@ test('metro companion worker exits after non-retryable registration failure', as assert.equal(registerAttempts, 1); }); -// A base without a host gains one from the appended path: `https://` would reach `https://api/...`. -test.for(['http://bridge.invalid', 'http:', 'https://', 'https:'])( - 'metro companion worker never sends its bearer token to %s and exits', - async (serverBaseUrl) => { - const sent: unknown[] = []; - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { - sent.push(input); - return new Response(null, { status: 401 }); - }); - const requestSpy = vi.spyOn(http, 'request').mockImplementation(((target: unknown) => { - sent.push(target); - throw new Error('nothing may be sent'); - }) as typeof http.request); - cleanupTasks.push(async () => { - fetchSpy.mockRestore(); - requestSpy.mockRestore(); - }); - - const companion = startMetroCompanionWorker({ - bridgePort: 1, - localPort: 1, - serverBaseUrl, - unregisterPath: '/api/metro/companion/unregister', - }); - await companion.waitForExit('worker exit after the bridge URL was refused'); - - assert.deepEqual(sent, []); - }, -); - -test('metro companion worker reaches a loopback bridge directly, never through global fetch', async () => { - const received: string[] = []; - const registered = createDeferred(); - let bridgePort = 0; - let bridgeSocketRef: Duplex | null = null; - const bridgeServer = http.createServer((req, res) => { - received.push(`${req.url} ${req.headers.authorization}`); - req.resume(); - if (req.url === '/api/metro/companion/register') { - writeSuccessfulRegistration(res, bridgePort); - return; - } - res.end('{}'); - }); - bridgeServer.on('upgrade', (req, socket) => { - bridgeSocketRef = socket; - if (acceptWebSocketUpgrade(req, socket)) registered.resolve(); - }); - cleanupTasks.push(() => closeLoopbackServer(bridgeServer)); - cleanupTasks.push(async () => { - bridgeSocketRef?.destroy(); - }); - bridgePort = await listenOnLoopback(bridgeServer); - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); - cleanupTasks.push(async () => fetchSpy.mockRestore()); - - const companion = startMetroCompanionWorker({ - bridgePort, - localPort: 1, - unregisterPath: '/api/metro/companion/unregister', - }); - await Promise.race([waitFor(registered.promise, 5_000, 'bridge socket'), companion.earlyExit]); - bridgeSocketRef!.destroy(); - await companion.stop(); - - assert.equal(received[0], '/api/metro/companion/register Bearer test-token'); - assert.ok(received.includes('/api/metro/companion/unregister Bearer test-token'), `${received}`); - assert.equal(fetchSpy.mock.calls.length, 0); -}); - test('metro companion worker retries registration failures with retry-after delay', async () => { const bridgeSocketReady = createDeferred(); const registerAttemptTimes: number[] = []; 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 07fc8ed71b..aff63647bf 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.ts @@ -23,7 +23,10 @@ import type { MetroTunnelResponseMessage, } from './metro-tunnel-messages.ts'; import { normalizeBaseUrl } from '../metro/base-url.ts'; -import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; +import { + assertSecureCredentialSocket, + assertSecureCredentialTransport, +} from '@agent-device/contracts/credential-transport'; const COMPANION_REGISTER_TIMEOUT_MS = 5_000; const COMPANION_REGISTER_MAX_RETRY_DELAY_MS = 60_000; @@ -168,11 +171,32 @@ function clampRetryDelay(delayMs: number): number { * `https://api/...`). */ function bearerDestination(serverBaseUrl: string, path: string): string { - try { + return refuseWithoutRetry(() => { assertSecureCredentialTransport(serverBaseUrl, 'Metro companion bridge URL'); const url = `${normalizeBaseUrl(serverBaseUrl)}${path}`; assertSecureCredentialTransport(url, 'Metro companion bridge URL'); return url; + }); +} + +/** + * Prepares the bridge socket. The registered URL is what admits this companion to the bridge, so it + * follows the credential transport rule: `wss`, or `ws` to loopback. A `ws` socket connects + * directly, because the global `WebSocket` hands its URL to an environment proxy. + */ +async function prepareBridgeSocket(wsUrl: string): Promise<() => WebSocket> { + const destination = refuseWithoutRetry(() => + assertSecureCredentialSocket(wsUrl, 'Metro companion bridge socket URL'), + ); + if (destination.protocol === 'https:') return () => new WebSocket(wsUrl); + const { Agent, WebSocket: DirectWebSocket } = await import('undici'); + return () => new DirectWebSocket(wsUrl, { dispatcher: new Agent() }) as unknown as WebSocket; +} + +/** Runs a transport check as part of registration: its refusal is one no retry can fix. */ +function refuseWithoutRetry(check: () => T): T { + try { + return check(); } catch (error) { throw new CompanionRegistrationError( error instanceof Error ? error.message : String(error), @@ -510,12 +534,13 @@ export async function runCompanionTunnelWorker( registerRetryDelayMs = runtime.reconnectDelayMs ?? COMPANION_TUNNEL_RECONNECT_DELAY_MS; registered = true; activeRegistrationComplete = true; + const connectBridge = await prepareBridgeSocket(registration.wsUrl); if (shutdownRequested || !shouldKeepWorkerRunning(options)) { await unregisterActiveRegistration(); registered = false; break; } - const bridgeSocket = new WebSocket(registration.wsUrl); + const bridgeSocket = connectBridge(); activeBridgeSocket = bridgeSocket; bridgeSocket.binaryType = 'arraybuffer'; try { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 311e223d79..be7f3994ad 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1087,6 +1087,9 @@ importers: '@agent-device/test-kit': specifier: workspace:* version: link:../test-kit + undici: + specifier: 7.30.1 + version: 7.30.1 packages/remote: dependencies: diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 6629d3554d..8a995c9590 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -21,7 +21,7 @@ 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. -A client never sends a daemon, proxy, Metro host bridge, or cloud auth credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect; it relays the redirect response to its client, whose requests follow at most a same-origin redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, such as Limrun API and download URLs, are checked right before each request. A Limrun download follows a redirect only from https to https or on the same origin, and drops its headers when it leaves the origin. +A client never sends a daemon, proxy, Metro host bridge, cloud auth, or provider credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect; it relays the redirect response to its client, whose requests follow at most a same-origin redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, or that are signed, such as Limrun API and download URLs and Revyl upload URLs, are checked right before each request. A Limrun download follows a redirect only from https to https or on the same origin, and drops its headers when it leaves the origin. The Metro companion opens the host bridge's socket only over `wss`, or `ws` to loopback. 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. From 96d8f4fe3211ce328c2859c1d350c7d9bb9ed69e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 14:58:34 +0100 Subject: [PATCH 11/22] test(react-native): handle a peer reset on the companion test bridge The sockets the test servers take on upgrade and connect had no error listener. Killing the spawned worker with its bridge socket open can reset it, which Linux CI reported as an unhandled ECONNRESET. Co-Authored-By: Claude Sonnet 5.5 --- ...ompanion-tunnel-worker-credential-transport.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) 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 index 692e99ce95..99f0fbda74 100644 --- 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 @@ -57,6 +57,14 @@ function startWorker(serverBaseUrl: string) { return { done, stop }; } +/** + * A socket taken from an HTTP server on `upgrade` or `connect` 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. */ async function listenBridge(wsUrl: (port: number) => string) { const received: string[] = []; @@ -70,6 +78,7 @@ async function listenBridge(wsUrl: (port: number) => string) { 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)) upgrade(socket); @@ -138,6 +147,7 @@ test('the worker opens a loopback socket around an environment proxy', async () }); for (const event of ['upgrade', 'connect'] as const) { proxy.on(event, (req: http.IncomingMessage, socket: Duplex) => { + tolerateReset(socket); proxied.push(`${event} ${req.url}`); socket.destroy(); }); From 3db25a8686e2fdf28b8447e4a3a4ba94bd30ee38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 15:13:39 +0100 Subject: [PATCH 12/22] fix(remote): close the gaps a focused review found - proxy: drop a relayed Location whose serialized or decoded path holds the upstream token; refuse an upstream base URL with a username or password during admission - Limrun download: refuse the initial URL before the cleanup path, so an existing destination file stays - direct requester: pipe a streamed body instead of buffering it - bridge socket: only wss, or ws to loopback, by the original scheme - Apple runner: only the CoreDevice tunnel route may carry the token over plain http off loopback, and the docs say so Co-Authored-By: Claude Sonnet 5.5 --- .../src/__tests__/runner-transport.test.ts | 37 +++++- .../apple-runner/src/runner-command-route.ts | 16 ++- packages/apple-runner/src/runner-transport.ts | 8 +- .../src/credential-transport.test.ts | 17 +-- .../contracts/src/credential-transport.ts | 31 ++--- packages/host-kit/src/direct-http.test.ts | 107 ++++++++++++++++++ packages/host-kit/src/direct-http.ts | 37 +++++- .../provider-revyl/src/revyl-client.test.ts | 7 +- packages/proxy/README.md | 18 +-- .../daemon-proxy-credential-transport.test.ts | 27 ++++- packages/proxy/src/daemon-proxy.ts | 13 +-- packages/proxy/src/upstream-admission.ts | 25 ++++ packages/proxy/src/upstream-response-relay.ts | 15 ++- ...tunnel-worker-credential-transport.test.ts | 25 +++- .../client-companion-tunnel-worker.ts | 2 +- src/core/limrun-download-file.test.ts | 16 +++ src/core/limrun-download-file.ts | 21 ++-- website/docs/docs/error-reasons.md | 3 +- website/docs/docs/security-trust.md | 2 +- 19 files changed, 360 insertions(+), 67 deletions(-) create mode 100644 packages/proxy/src/upstream-admission.ts diff --git a/packages/apple-runner/src/__tests__/runner-transport.test.ts b/packages/apple-runner/src/__tests__/runner-transport.test.ts index 58691082be..9627417998 100644 --- a/packages/apple-runner/src/__tests__/runner-transport.test.ts +++ b/packages/apple-runner/src/__tests__/runner-transport.test.ts @@ -41,7 +41,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'; import { loadRealHostKitCapabilities } from '@agent-device/test-kit'; @@ -234,6 +238,37 @@ test('a forwarded runner route never sends its tokens over plain http off loopba assert.equal(fetchMock.mock.calls.length, 0); }); +// The same address is allowed on the tunnel route (the fallback cases below), so the exclusion +// follows how the route was resolved, not what the address looks like. +test.each([ + ['whose endpoint carries its forwarding', { url: 'http://[fd00::123]:8100/command' }], + ['whose endpoint names no forwarding', undefined], +])('a forwarded route to a tunnel-shaped address %s is refused', async (_label, http) => { + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + const route = { + kind: 'network', + url: 'http://[fd00::123]:8100/command', + cachedTunnelIp: false, + via: 'forwarded', + } as const; + + await assert.rejects( + () => + postRunnerCommandOverRoute(iosDevice, route, { + endpoint: { ...RUNNER_ENDPOINT_FIXTURE, ...(http ? { http } : {}) }, + 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('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..433ab570be 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; + /** + * How the URL was resolved: this Mac's loopback, the tunnel address CoreDevice reports for + * this device, or a URL a provider forwards. Only the tunnel route may carry the runner token + * over plain http to a host that is not loopback, because its tunnel encrypts the traffic. + */ + via: 'loopback' | 'coredevice-tunnel' | 'forwarded'; } | { kind: 'usbmux'; @@ -58,7 +64,7 @@ export function createRunnerCommandRouteResolver( timeoutBudgetMs?: number, forceRefresh = false, ): Promise => { - if (http) return { kind: 'network', url: http.url, cachedTunnelIp: false }; + if (http) return { kind: 'network', url: http.url, cachedTunnelIp: false, via: 'forwarded' }; if (runsOnThisHost(device)) return buildLoopbackRoute(port); const control = resolveIosPhysicalDeviceControl(device); if (control.backend === 'xctest') return buildUsbmuxRoute(device, port); @@ -103,7 +109,12 @@ function runsOnThisHost(device: DeviceInfo): boolean { } function buildLoopbackRoute(port: number): RunnerCommandRoute { - return { kind: 'network', url: `http://127.0.0.1:${port}/command`, cachedTunnelIp: false }; + return { + kind: 'network', + url: `http://127.0.0.1:${port}/command`, + cachedTunnelIp: false, + via: 'loopback', + }; } function buildTunnelRoute( @@ -115,6 +126,7 @@ function buildTunnelRoute( kind: 'network', url: tunnelIp ? `http://[${tunnelIp}]:${port}/command` : null, cachedTunnelIp, + via: 'coredevice-tunnel', }; } diff --git a/packages/apple-runner/src/runner-transport.ts b/packages/apple-runner/src/runner-transport.ts index 27e198b171..2546e12388 100644 --- a/packages/apple-runner/src/runner-transport.ts +++ b/packages/apple-runner/src/runner-transport.ts @@ -105,10 +105,10 @@ export async function postRunnerCommandOverRoute( 'no', ); } - // A forwarded route is a provider-supplied URL that receives the runner token and the provider's - // own headers, so it gets the credential transport rule. Local routes are loopback, USB, or the - // device's CoreDevice tunnel. - if (endpoint.http) { + // The request carries the runner token, and a forwarded one the provider's own headers. The + // resolver builds the loopback URL and the CoreDevice tunnel URL itself; the tunnel is the one + // plain-http route off this machine. Every other route meets the credential transport rule. + if (route.via !== 'loopback' && route.via !== 'coredevice-tunnel') { const { assertSecureCredentialTransport } = await import('@agent-device/contracts/credential-transport'); try { diff --git a/packages/contracts/src/credential-transport.test.ts b/packages/contracts/src/credential-transport.test.ts index f288034812..8584ac15fd 100644 --- a/packages/contracts/src/credential-transport.test.ts +++ b/packages/contracts/src/credential-transport.test.ts @@ -49,19 +49,20 @@ test.each([ }); test.each([ - ['wss://bridge.example.test/bridge?ticket=t', 'https:'], - ['https://bridge.example.test/bridge', 'https:'], - ['ws://127.0.0.1:4310/bridge?ticket=t', 'http:'], - ['WS://[::1]:4310/bridge', 'http:'], - ['http://localhost:4310/bridge', 'http:'], -])('a credential socket may open to %s', (url, protocol) => { - expect(assertSecureCredentialSocket(url, 'Bridge socket URL').protocol).toBe(protocol); + '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://bridge.example.test/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) => { diff --git a/packages/contracts/src/credential-transport.ts b/packages/contracts/src/credential-transport.ts index 0691829304..ac5478441a 100644 --- a/packages/contracts/src/credential-transport.ts +++ b/packages/contracts/src/credential-transport.ts @@ -7,8 +7,9 @@ import { isLoopbackHostname } from './loopback-host.ts'; /** Why a client refuses to send a credential before any request leaves. */ const CREDENTIAL_TRANSPORT_REASONS = { - // A credential would travel over plain http to a host that is not loopback, or to a URL that does - // not parse. The refusal names the setting, never the destination. + // 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'>; @@ -26,25 +27,29 @@ export function isSecureCredentialDestination(url: URL): boolean { export function assertSecureCredentialTransport(url: string | URL, subject: string): URL { const destination = typeof url === 'string' ? URL.parse(url) : url; if (destination && isSecureCredentialDestination(destination)) return destination; - throw new AppError( - 'INVALID_ARGS', + throw refusal( 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.`, - { - reason: CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason, - hint: 'Use an https 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.', - }, ); } /** - * The same rule for a WebSocket that carries a credential: `wss` counts as https, and `ws` as plain - * http, so loopback only. Returns the destination in that http(s) form. + * 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:') destination.protocol = 'https:'; - if (destination?.protocol === 'ws:') destination.protocol = 'http:'; - return assertSecureCredentialTransport(destination ?? url, subject); + if (destination?.protocol === 'wss:') return destination; + if (destination?.protocol === 'ws:' && isLoopbackHostname(destination.hostname)) { + return destination; + } + throw refusal(`${subject} must use wss to send credentials; ws is allowed only on loopback.`); +} + +function refusal(message: string): AppError { + return new AppError('INVALID_ARGS', message, { + reason: CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason, + 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.', + }); } diff --git a/packages/host-kit/src/direct-http.test.ts b/packages/host-kit/src/direct-http.test.ts index e54f09a9be..c67191ad95 100644 --- a/packages/host-kit/src/direct-http.test.ts +++ b/packages/host-kit/src/direct-http.test.ts @@ -2,6 +2,7 @@ import { afterEach, expect, test, vi } from 'vitest'; import { execFile } from 'node:child_process'; import http from 'node:http'; import path from 'node:path'; +import { Readable } from 'node:stream'; import { promisify } from 'node:util'; import type { AddressInfo } from 'node:net'; import { fetchOverDirectHttp, fetchWithCredential, loadDirectHttpAgent } from './direct-http.ts'; @@ -244,3 +245,109 @@ test('the credential requester keeps its direct agent whatever the options name' direct, ]); }); + +/** A server that records each upload's framing and body, and reports its first bytes. */ +async function serveUpload() { + const uploads: Array<{ length?: string; encoding?: string; body: string }> = []; + const started = deferred(); + const { origin, closed } = await serveWith((req, res) => { + const upload = { + length: req.headers['content-length'], + encoding: req.headers['transfer-encoding'], + body: '', + }; + uploads.push(upload); + req.on('data', (chunk) => { + upload.body += String(chunk); + started.resolve(); + }); + req.on('end', () => res.end()); + }); + return { origin, closed, uploads, started: started.promise }; +} + +test.each([ + ['declares the length its headers give', { 'content-length': '12' }, '12', undefined], + ['is chunked without a declared length', undefined, undefined, 'chunked'], +])('a streamed body is sent as it arrives and %s', async (_label, headers, length, encoding) => { + const server = await serveUpload(); + async function* body() { + yield Buffer.from('first,'); + // A sender that read the whole body first would never get here. + await server.started; + yield Buffer.from('second'); + } + + const response = await fetchWithCredential(server.origin, { + method: 'PUT', + ...(headers ? { headers } : {}), + body: body() as unknown as BodyInit, + duplex: 'half', + } as RequestInit); + + expect(response.status).toBe(200); + expect(server.uploads).toEqual([{ length, encoding, body: 'first,second' }]); +}); + +/** One chunk, then silence; `release` runs when the stream is cancelled or destroyed. */ +const stalledStreams: Array<[string, (release: () => void) => unknown]> = [ + [ + 'a web stream', + (release) => + new ReadableStream({ + start: (stream) => stream.enqueue(Buffer.from('first,')), + cancel: release, + }), + ], + [ + 'a Node stream', + (release) => { + const stream = new Readable({ + read: () => {}, + destroy: (error, done) => { + release(); + done(error); + }, + }); + stream.push('first,'); + return stream; + }, + ], +]; + +test.each(stalledStreams)('an abort during an upload releases %s', async (_label, source) => { + const server = await serveUpload(); + const released = deferred(); + const controller = new AbortController(); + const reason = new Error('caller gave up'); + + const pending = fetchWithCredential(server.origin, { + method: 'PUT', + body: source(released.resolve) as BodyInit, + signal: controller.signal, + duplex: 'half', + } as RequestInit); + await server.started; + controller.abort(reason); + + await expect(pending).rejects.toBe(reason); + await released.promise; + await server.closed; +}); + +test('a streamed body that fails rejects the request as fetch does', async () => { + const server = await serveUpload(); + const failure = new Error('disk gone'); + async function* body() { + yield Buffer.from('first,'); + throw failure; + } + + await expect( + fetchWithCredential(server.origin, { + method: 'PUT', + body: body() as unknown as BodyInit, + duplex: 'half', + } as RequestInit), + ).rejects.toMatchObject({ message: 'fetch failed', cause: failure }); +}); diff --git a/packages/host-kit/src/direct-http.ts b/packages/host-kit/src/direct-http.ts index 0a36fede1c..1b446f85c7 100644 --- a/packages/host-kit/src/direct-http.ts +++ b/packages/host-kit/src/direct-http.ts @@ -1,4 +1,5 @@ import type { Agent, IncomingMessage } from 'node:http'; +import type { ReadableStream as WebReadableStream } from 'node:stream/web'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; // Loaded at send time by the code that sends a credential over plain http, never at module scope. @@ -47,8 +48,14 @@ const DIRECT_HTTP_REASONS = { * with `TypeError('fetch failed')` carrying the cause. An abort ends the exchange with the signal's * reason, and five silent minutes end it with a `direct_http_idle_timeout` error: the call rejects * with it, or after the response, the body read does. + * + * `request`'s own body is read whole, so the request declares its length. A `streamedBody` is piped + * instead, as it arrives, with the length the headers declare or else chunked. */ -export async function fetchOverDirectHttp(request: Request): Promise { +export async function fetchOverDirectHttp( + request: Request, + streamedBody?: AsyncIterable, +): Promise { const url = new URL(request.url); if (url.protocol !== 'http:') throw new TypeError('fetchOverDirectHttp sends plain http only'); // The module object itself, so a stubbed `request` is the one called. @@ -111,11 +118,28 @@ export async function fetchOverDirectHttp(request: Request): Promise { // the caller's only that long. req.once('close', () => request.signal.removeEventListener('abort', abort)); req.on('error', fail); + if (streamedBody) { + // A stream is destroyed or cancelled even while a read is pending, which the return of an + // async iterator over it would wait for. + const source = + streamedBody instanceof Readable + ? streamedBody + : streamedBody instanceof ReadableStream + ? Readable.fromWeb(streamedBody as WebReadableStream) + : Readable.from(streamedBody, { objectMode: false }); + source.on('error', (error) => { + fail(error); + req.destroy(); + }); + // Releases the source, and the file behind it, when the exchange ends first. + req.once('close', () => source.destroy()); + source.pipe(req); + return; + } if (!request.body) { req.end(); return; } - // Read whole, so the request declares its length. request.arrayBuffer().then( (body) => req.end(Buffer.from(body)), (error: unknown) => { @@ -139,5 +163,12 @@ export async function fetchWithCredential( ): Promise { if (send) return await send(input, init); if (new URL(input).protocol !== 'http:') return await fetch(input, init); - return await fetchOverDirectHttp(new Request(input, init)); + const { body } = init; + if (!isStreamedBody(body)) return await fetchOverDirectHttp(new Request(input, init)); + return await fetchOverDirectHttp(new Request(input, { ...init, body: null }), body); +} + +/** A body that arrives in pieces: a web or Node stream, or any other async iterable. */ +function isStreamedBody(body: unknown): body is AsyncIterable { + return typeof body === 'object' && body !== null && Symbol.asyncIterator in body; } diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index f98a4cdce5..105cf40f43 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -27,8 +27,10 @@ test('uses the public Revyl backend when no URL is configured', () => { test('a loopback backend and upload URL are reached directly, never through global fetch', async () => { const received: string[] = []; + const lengths: Array = []; const server = http.createServer((req, res) => { received.push(`${req.method} ${req.url} ${req.headers.authorization ?? ''}`.trim()); + if (req.method === 'PUT') lengths.push(req.headers['content-length']); req.resume(); req.on('end', () => res.end('{}')); }); @@ -42,11 +44,14 @@ test('a loopback backend and upload URL are reached directly, never through glob clientVersion: '0.0.0-test', }); await client.verifyCredentials(); + const { size } = await fs.stat(import.meta.filename); await client.uploadSessionArtifact( `${origin}/upload?signature=signed`, - { filePath: import.meta.filename, size: (await fs.stat(import.meta.filename)).size }, + { filePath: import.meta.filename, size }, 'application/zip', ); + // A presigned PUT declares its length even though the file is streamed. + assert.deepEqual(lengths, [String(size)]); assert.deepEqual(received, [ 'GET /api/v1/entity/users/get_user_uuid Bearer test-key', diff --git a/packages/proxy/README.md b/packages/proxy/README.md index 9ffd89c3e0..d273107b5c 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -157,16 +157,18 @@ upstream token and `redirect: 'manual'`: return a 3xx response as it is and neve proxy relays a 3xx, such as the daemon's `308` resume response, to its client. It relays a `Location` only when it targets the daemon itself, as a path on the proxy's client-facing origin without its query or fragment. It drops one that points elsewhere, has userinfo, or has the -upstream token in its path. 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`. +upstream token in its path, written or percent-decoded. 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`. 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` -(`details.reason: "insecure_credential_transport"` on `/rpc`). +`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`. On `/rpc`, `details.reason` is `proxy_upstream_userinfo` for a username or +password, and `insecure_credential_transport` otherwise. 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 diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index bcf0f4f2b6..9b28747be4 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -51,6 +51,13 @@ test.each([ ['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'], ] as const)( '%s never sends the upstream token to %s', async (_label, _destination, upstreamBaseUrl, transport) => { @@ -89,7 +96,9 @@ test.each([ ]) { const response = await proxy.handle(request); expect(response.status, request.url).toBe(400); - expect(await response.text(), request.url).toContain('Proxy upstreamBaseUrl'); + const refusal = await response.text(); + expect(refusal, request.url).toContain('Proxy upstreamBaseUrl'); + expect(refusal, request.url).not.toMatch(/operator|hunter2/); } expect(sent).toEqual([]); }, @@ -176,6 +185,22 @@ test.each([ }, ); +test('a relayed Location is dropped when its path holds the upstream token as written', async () => { + // A token that reads differently once decoded: `a%2Fb` decodes to `a/b`. + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'https://daemon.example.test', + upstreamToken: 'a%2Fb', + clientToken: 'client-secret', + upstreamFetch: async () => + new Response(null, { status: 307, headers: { location: '/artifacts/a%2Fb' } }), + }); + + const response = await proxy.handle(rpc()); + + expect(response.status).toBe(307); + expect(response.headers.get('location')).toBe(null); +}); + test('the default transports relay a daemon redirect with its target on every route', async () => { const daemon = await serve((req, res) => { req.resume(); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index e69dab91a0..a72f341ea3 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -69,8 +69,9 @@ export type DaemonProxyAuthenticate = ( export type DaemonProxyOptions = { /** * 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`; with `upstreamFetch` it is - * the logical URL your transport routes. Any other URL refuses every request before it is sent. + * 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. */ @@ -580,11 +581,9 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti // Loaded on the first upstream exchange, never at module scope: the proxy entry stays lean. let upstreamAdmission: Promise | undefined; const admitUpstream = () => - (upstreamAdmission ??= import('@agent-device/contracts/credential-transport').then( - ({ assertSecureCredentialTransport }) => { - assertSecureCredentialTransport(upstreamBaseUrl, 'Proxy upstreamBaseUrl'); - }, - )); + (upstreamAdmission ??= import('./upstream-admission.ts').then(({ assertAdmittedUpstream }) => { + assertAdmittedUpstream(upstreamBaseUrl); + })); const customUpstreamFetch = options.upstreamFetch; const upstreamFetch: DaemonProxyUpstreamFetch = customUpstreamFetch ?? diff --git a/packages/proxy/src/upstream-admission.ts b/packages/proxy/src/upstream-admission.ts new file mode 100644 index 0000000000..c0acad1f06 --- /dev/null +++ b/packages/proxy/src/upstream-admission.ts @@ -0,0 +1,25 @@ +import { assertSecureCredentialTransport } 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 { + const upstream = assertSecureCredentialTransport(upstreamBaseUrl, 'Proxy upstreamBaseUrl'); + if (!upstream.username && !upstream.password) 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.', + }, + ); +} diff --git a/packages/proxy/src/upstream-response-relay.ts b/packages/proxy/src/upstream-response-relay.ts index ab6e4bc9de..19dff84ab2 100644 --- a/packages/proxy/src/upstream-response-relay.ts +++ b/packages/proxy/src/upstream-response-relay.ts @@ -57,9 +57,9 @@ function routeResponseHeaders(route: string): readonly string[] { * The `Location` of a relayed upstream 3xx, as the client must see it. Only a target on the * upstream daemon itself is relayed, as a path moved onto the client-facing origin and base path * the request came in on. Its query and fragment are dropped: the daemon redirects with neither, - * and both can carry a credential. A target elsewhere, with userinfo, or whose decoded path holds - * the upstream token is dropped whole: the proxy never hands a client a credential or a foreign - * destination. + * and both can carry a credential. A target elsewhere, with userinfo, or whose path holds the + * upstream token, as serialized or decoded, is dropped whole: the proxy never hands a client a + * credential or a foreign destination. */ function relayedLocation(relay: RelayedResponse): string | undefined { const raw = relay.upstreamResponse.headers.get('location'); @@ -69,8 +69,13 @@ function relayedLocation(relay: RelayedResponse): string | undefined { if (!target || target.origin !== upstreamBase.origin || target.username || target.password) { return undefined; } - const path = decodedPath(target); - if (path === undefined || path.includes(relay.upstreamToken)) return undefined; + const decoded = decodedPath(target); + if ( + decoded === undefined || + [target.pathname, decoded].some((path) => path.includes(relay.upstreamToken)) + ) { + return undefined; + } const basePath = upstreamBase.pathname.replace(/\/+$/, ''); if (basePath && target.pathname !== basePath && !target.pathname.startsWith(`${basePath}/`)) { return undefined; 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 index 99f0fbda74..3cf34b48a6 100644 --- 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 @@ -6,6 +6,7 @@ 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'; @@ -125,17 +126,33 @@ test('the worker reaches a loopback bridge directly, never through global fetch' assert.equal(proxied.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 bridge. +// without the check would show up at the sink. So would `http` or `https` on loopback, which a +// `WebSocket` accepts. test.for([ (port: number) => `ws://0.0.0.0:${port}/bridge?ticket=secret`, (port: number) => `ws://0.0.0.0:${port}/bridge`, - (port: number) => `http://0.0.0.0:${port}/bridge?ticket=secret`, -])('the worker refuses a plain socket off loopback before it opens', async (wsUrl) => { - const bridge = await listenBridge(wsUrl); + (port: number) => `http://127.0.0.1:${port}/bridge?ticket=secret`, + (port: number) => `https://127.0.0.1:${port}/bridge`, +])('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 startWorker(bridge.origin).done; + assert.deepEqual(sink.connections, []); assert.deepEqual(bridge.received, [registered, unregistered]); }); 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 aff63647bf..952e5b6b9d 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.ts @@ -188,7 +188,7 @@ async function prepareBridgeSocket(wsUrl: string): Promise<() => WebSocket> { const destination = refuseWithoutRetry(() => assertSecureCredentialSocket(wsUrl, 'Metro companion bridge socket URL'), ); - if (destination.protocol === 'https:') return () => new WebSocket(wsUrl); + if (destination.protocol === 'wss:') return () => new WebSocket(wsUrl); const { Agent, WebSocket: DirectWebSocket } = await import('undici'); return () => new DirectWebSocket(wsUrl, { dispatcher: new Agent() }) as unknown as WebSocket; } diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index 8199af8381..7c1dd9bde5 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -310,3 +310,19 @@ test('a same-origin redirect is followed with the headers, at most five times', await expect(download(loop)).rejects.toMatchObject(refusedRedirect); expect(hops).toBe(6); }); + +test('a refused download URL leaves an existing file at the destination untouched', async () => { + const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); + fs.writeFileSync(destinationPath, 'earlier download'); + + await expect( + downloadLimrunFile({ + url: 'http://limrun.invalid/files?signature=signed', + headers: {}, + destinationPath, + timeoutMs: 5_000, + }), + ).rejects.toMatchObject(insecure); + + expect(fs.readFileSync(destinationPath, 'utf8')).toBe('earlier download'); +}); diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index 73f5d1c2a0..caf62153e7 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -15,8 +15,9 @@ const RESPONSE_BODY_PREVIEW_BYTES = 500; const MAX_DOWNLOAD_REDIRECTS = 5; 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. httpError: { reason: 'limrun_download_http_error' }, @@ -32,14 +33,16 @@ 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 fetchDownload(options, signal); + const response = await fetchDownload(url, options.headers, signal); if (!response.ok) throw await httpFailure(response, options); if (!response.body) { throw new AppError('COMMAND_FAILED', 'Limrun download returned no body', { @@ -63,10 +66,14 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise { +async function fetchDownload( + from: URL, + initialHeaders: LimrunFileDownload['headers'], + signal: AbortSignal, +): Promise { const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); - let url = assertSecureCredentialTransport(options.url, 'Limrun download URL'); - let headers = options.headers; + let url = from; + let headers = initialHeaders; for (let redirects = 0; ; redirects += 1) { const response = await fetchWithCredential(url.href, { method: 'GET', diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 6bf209f626..3f7c0d1bf6 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` @@ -900,7 +901,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `insecure_credential_transport` | A credential would travel over plain http to a host that is not loopback, or to a URL that does not parse. The refusal names the setting, never the destination. | +| `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/security-trust.md b/website/docs/docs/security-trust.md index 8a995c9590..11f481a387 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -21,7 +21,7 @@ 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. -A client never sends a daemon, proxy, Metro host bridge, cloud auth, or provider credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect; it relays the redirect response to its client, whose requests follow at most a same-origin redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, or that are signed, such as Limrun API and download URLs and Revyl upload URLs, are checked right before each request. A Limrun download follows a redirect only from https to https or on the same origin, and drops its headers when it leaves the origin. The Metro companion opens the host bridge's socket only over `wss`, or `ws` to loopback. +A client never sends a daemon, proxy, Metro host bridge, cloud auth, or provider credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. 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 address CoreDevice reports for the device's tunnel, and that tunnel encrypts the traffic. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect; it relays the redirect response to its client, whose requests follow at most a same-origin redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, or that are signed, such as Limrun API and download URLs and Revyl upload URLs, are checked right before each request. A Limrun download follows a redirect only from https to https or on the same origin, and drops its headers when it leaves the origin. The Metro companion opens the host bridge's socket only over `wss`, or `ws` to loopback. 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. From 3b9b896dc12996039693aa495de398ac161faf5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 15:20:24 +0100 Subject: [PATCH 13/22] fix(remote): release aborted uploads and narrow the tunnel exception - direct requester: release a streamed body when the exchange fails or never starts, including an abort before the request - Apple runner: treat a reported device address as the CoreDevice tunnel only when it is in fd00::/8, and say so in the security docs - proxy: refuse a username or password before the scheme check, so every scheme reports proxy_upstream_userinfo Co-Authored-By: Claude Sonnet 5.5 --- .../src/__tests__/runner-transport.test.ts | 19 ++ .../apple-runner/src/runner-command-route.ts | 17 +- packages/apple-runner/src/runner-transport.ts | 10 +- packages/host-kit/src/direct-http.test.ts | 21 +++ packages/host-kit/src/direct-http.ts | 169 +++++++++--------- .../daemon-proxy-credential-transport.test.ts | 22 +++ packages/proxy/src/upstream-admission.ts | 8 +- website/docs/docs/security-trust.md | 2 +- 8 files changed, 178 insertions(+), 90 deletions(-) diff --git a/packages/apple-runner/src/__tests__/runner-transport.test.ts b/packages/apple-runner/src/__tests__/runner-transport.test.ts index 9627417998..b321aae5f4 100644 --- a/packages/apple-runner/src/__tests__/runner-transport.test.ts +++ b/packages/apple-runner/src/__tests__/runner-transport.test.ts @@ -269,6 +269,25 @@ test.each([ 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 433ab570be..9f3f33787d 100644 --- a/packages/apple-runner/src/runner-command-route.ts +++ b/packages/apple-runner/src/runner-command-route.ts @@ -1,3 +1,4 @@ +import { BlockList, isIPv6 } from 'node:net'; import type { RunnerEndpoint } from './runner-contract.ts'; import { isMacOs, type DeviceInfo } from '@agent-device/kernel/device'; import { resolveIosPhysicalDeviceControl } from './host.ts'; @@ -21,10 +22,11 @@ export type RunnerCommandRoute = cachedTunnelIp: boolean; /** * How the URL was resolved: this Mac's loopback, the tunnel address CoreDevice reports for - * this device, or a URL a provider forwards. Only the tunnel route may carry the runner token - * over plain http to a host that is not loopback, because its tunnel encrypts the traffic. + * this device, a reported address that is not a tunnel address, or a URL a provider forwards. + * Only the tunnel route may carry the runner token over plain http to a host that is not + * loopback, because its tunnel encrypts the traffic. */ - via: 'loopback' | 'coredevice-tunnel' | 'forwarded'; + via: 'loopback' | 'coredevice-tunnel' | 'device-address' | 'forwarded'; } | { kind: 'usbmux'; @@ -126,10 +128,17 @@ function buildTunnelRoute( kind: 'network', url: tunnelIp ? `http://[${tunnelIp}]:${port}/command` : null, cachedTunnelIp, - via: 'coredevice-tunnel', + via: tunnelIp && isCoreDeviceTunnelAddress(tunnelIp) ? 'coredevice-tunnel' : 'device-address', }; } +/** CoreDevice gives its tunnel a unique local IPv6 address, in `fd00::/8`. */ +function isCoreDeviceTunnelAddress(address: string): boolean { + const range = new BlockList(); + range.addSubnet('fd00::', 8, 'ipv6'); + return isIPv6(address) && range.check(address, 'ipv6'); +} + function readDeviceTunnelIpCache(deviceId: string): string | null { const cached = deviceTunnelIpCache.get(deviceId); if (!cached) return null; diff --git a/packages/apple-runner/src/runner-transport.ts b/packages/apple-runner/src/runner-transport.ts index 2546e12388..1fd02934a3 100644 --- a/packages/apple-runner/src/runner-transport.ts +++ b/packages/apple-runner/src/runner-transport.ts @@ -106,13 +106,17 @@ export async function postRunnerCommandOverRoute( ); } // The request carries the runner token, and a forwarded one the provider's own headers. The - // resolver builds the loopback URL and the CoreDevice tunnel URL itself; the tunnel is the one - // plain-http route off this machine. Every other route meets the credential transport rule. + // resolver marks the loopback URL it builds and the CoreDevice tunnel address it recognizes; the + // tunnel is the one plain-http route off this machine. Every other route meets the credential + // transport rule. if (route.via !== 'loopback' && route.via !== 'coredevice-tunnel') { const { assertSecureCredentialTransport } = await import('@agent-device/contracts/credential-transport'); try { - assertSecureCredentialTransport(route.url, 'Runner forwarding URL'); + assertSecureCredentialTransport( + route.url, + route.via === 'forwarded' ? 'Runner forwarding URL' : 'Runner device address', + ); } catch (error) { throw discloseDispatch(error as AppError, 'no'); } diff --git a/packages/host-kit/src/direct-http.test.ts b/packages/host-kit/src/direct-http.test.ts index c67191ad95..772f277158 100644 --- a/packages/host-kit/src/direct-http.test.ts +++ b/packages/host-kit/src/direct-http.test.ts @@ -335,6 +335,27 @@ test.each(stalledStreams)('an abort during an upload releases %s', async (_label await server.closed; }); +test.each(stalledStreams)( + 'an upload aborted before it starts releases %s and sends nothing', + async (_label, source) => { + const server = await serveUpload(); + const released = deferred(); + const reason = new Error('caller gave up'); + + await expect( + fetchWithCredential(server.origin, { + method: 'PUT', + body: source(released.resolve) as BodyInit, + signal: AbortSignal.abort(reason), + duplex: 'half', + } as RequestInit), + ).rejects.toBe(reason); + + await released.promise; + expect(server.uploads).toEqual([]); + }, +); + test('a streamed body that fails rejects the request as fetch does', async () => { const server = await serveUpload(); const failure = new Error('disk gone'); diff --git a/packages/host-kit/src/direct-http.ts b/packages/host-kit/src/direct-http.ts index 1b446f85c7..88a96c1413 100644 --- a/packages/host-kit/src/direct-http.ts +++ b/packages/host-kit/src/direct-http.ts @@ -64,90 +64,99 @@ export async function fetchOverDirectHttp( loadDirectHttpAgent('http:'), import('node:stream'), ]); - request.signal.throwIfAborted(); - return await new Promise((resolve, reject) => { - let response: IncomingMessage | undefined; - const fail = (cause: unknown) => reject(new TypeError('fetch failed', { cause })); - const end = (reason: Error) => { - reject(reason); - response?.destroy(reason); - req.destroy(); - }; - const req = http.request( - { - host: url.hostname.replace(/^\[(.*)\]$/, '$1'), - port: url.port, - path: `${url.pathname}${url.search}`, - method: request.method, - headers: Object.fromEntries(request.headers), - agent, - timeout: IDLE_TIMEOUT_MS, - }, - (res) => { - response = res; - // The body stream reports an error to its reader; an unread body has no other listener. - res.on('error', () => undefined); - const status = res.statusCode ?? 502; - if (request.redirect === 'error' && REDIRECT_STATUSES.has(status)) { - res.destroy(); - fail(new Error('unexpected redirect')); - return; - } - const nullBody = request.method === 'HEAD' || NULL_BODY_STATUSES.has(status); - if (nullBody) res.resume(); - resolve( - new Response(nullBody ? null : (Readable.toWeb(res) as ReadableStream), { - status, - statusText: res.statusMessage, - headers: responseHeadersOf(res), + // Taken over before anything can end the exchange, so that every way it fails releases it. A + // stream is destroyed or cancelled even while a read is pending, which the return of an async + // iterator over it would wait for. + const source = + streamedBody === undefined || streamedBody instanceof Readable + ? streamedBody + : streamedBody instanceof ReadableStream + ? Readable.fromWeb(streamedBody as WebReadableStream) + : Readable.from(streamedBody, { objectMode: false }); + source?.on('error', () => undefined); + const exchange = () => + new Promise((resolve, reject) => { + let response: IncomingMessage | undefined; + const fail = (cause: unknown) => reject(new TypeError('fetch failed', { cause })); + const end = (reason: Error) => { + reject(reason); + response?.destroy(reason); + req.destroy(); + }; + const req = http.request( + { + host: url.hostname.replace(/^\[(.*)\]$/, '$1'), + port: url.port, + path: `${url.pathname}${url.search}`, + method: request.method, + headers: Object.fromEntries(request.headers), + agent, + timeout: IDLE_TIMEOUT_MS, + }, + (res) => { + response = res; + // The body stream reports an error to its reader; an unread body has no other listener. + res.on('error', () => undefined); + const status = res.statusCode ?? 502; + if (request.redirect === 'error' && REDIRECT_STATUSES.has(status)) { + res.destroy(); + fail(new Error('unexpected redirect')); + return; + } + const nullBody = request.method === 'HEAD' || NULL_BODY_STATUSES.has(status); + if (nullBody) res.resume(); + resolve( + new Response(nullBody ? null : (Readable.toWeb(res) as ReadableStream), { + status, + statusText: res.statusMessage, + headers: responseHeadersOf(res), + }), + ); + }, + ); + req.on('timeout', () => { + end( + new AppError('COMMAND_FAILED', 'Plain-http request timed out waiting for the peer', { + reason: DIRECT_HTTP_REASONS.idleTimeout.reason, + timeoutMs: IDLE_TIMEOUT_MS, }), ); - }, - ); - req.on('timeout', () => { - end( - new AppError('COMMAND_FAILED', 'Plain-http request timed out waiting for the peer', { - reason: DIRECT_HTTP_REASONS.idleTimeout.reason, - timeoutMs: IDLE_TIMEOUT_MS, - }), + }); + const abort = () => end(request.signal.reason as Error); + request.signal.addEventListener('abort', abort, { once: true }); + // This listener also keeps `request` reachable while the exchange lives: its signal follows + // the caller's only that long. + req.once('close', () => request.signal.removeEventListener('abort', abort)); + req.on('error', fail); + if (source) { + source.on('error', (error) => { + fail(error); + req.destroy(); + }); + // Releases the source, and the file behind it, when the exchange ends first. + req.once('close', () => source.destroy()); + source.pipe(req); + return; + } + if (!request.body) { + req.end(); + return; + } + request.arrayBuffer().then( + (body) => req.end(Buffer.from(body)), + (error: unknown) => { + fail(error); + req.destroy(); + }, ); }); - const abort = () => end(request.signal.reason as Error); - request.signal.addEventListener('abort', abort, { once: true }); - // This listener also keeps `request` reachable while the exchange lives: its signal follows - // the caller's only that long. - req.once('close', () => request.signal.removeEventListener('abort', abort)); - req.on('error', fail); - if (streamedBody) { - // A stream is destroyed or cancelled even while a read is pending, which the return of an - // async iterator over it would wait for. - const source = - streamedBody instanceof Readable - ? streamedBody - : streamedBody instanceof ReadableStream - ? Readable.fromWeb(streamedBody as WebReadableStream) - : Readable.from(streamedBody, { objectMode: false }); - source.on('error', (error) => { - fail(error); - req.destroy(); - }); - // Releases the source, and the file behind it, when the exchange ends first. - req.once('close', () => source.destroy()); - source.pipe(req); - return; - } - if (!request.body) { - req.end(); - return; - } - request.arrayBuffer().then( - (body) => req.end(Buffer.from(body)), - (error: unknown) => { - fail(error); - req.destroy(); - }, - ); - }); + try { + request.signal.throwIfAborted(); + return await exchange(); + } catch (error) { + source?.destroy(); + throw error; + } } /** diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index 9b28747be4..4e9d1e571e 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -185,6 +185,28 @@ test.each([ }, ); +test.each([ + 'http://operator@daemon.example.test', + 'http://operator:hunter2@127.0.0.1:4310', + 'https://operator:hunter2@daemon.example.test', +])('%s is refused for its username whatever its scheme', async (upstreamBaseUrl) => { + const upstreamFetch = vi.fn(async () => Response.json({})); + const proxy = createDaemonProxy({ + upstreamBaseUrl, + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + upstreamFetch, + }); + + const response = await proxy.handle(rpc()); + + expect(response.status).toBe(400); + const refusal = await response.text(); + expect(refusal).toContain('proxy_upstream_userinfo'); + expect(refusal).not.toMatch(/operator|hunter2/); + expect(upstreamFetch).not.toHaveBeenCalled(); +}); + test('a relayed Location is dropped when its path holds the upstream token as written', async () => { // A token that reads differently once decoded: `a%2Fb` decodes to `a/b`. const proxy = createDaemonProxy({ diff --git a/packages/proxy/src/upstream-admission.ts b/packages/proxy/src/upstream-admission.ts index c0acad1f06..8e3877da3d 100644 --- a/packages/proxy/src/upstream-admission.ts +++ b/packages/proxy/src/upstream-admission.ts @@ -12,8 +12,12 @@ const UPSTREAM_ADMISSION_REASONS = { /** Refuses every upstream base URL the proxy must not send to. The refusal never quotes it. */ export function assertAdmittedUpstream(upstreamBaseUrl: string): void { - const upstream = assertSecureCredentialTransport(upstreamBaseUrl, 'Proxy upstreamBaseUrl'); - if (!upstream.username && !upstream.password) return; + // 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.', diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 11f481a387..5e46ba76a5 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -21,7 +21,7 @@ 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. -A client never sends a daemon, proxy, Metro host bridge, cloud auth, or provider credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. 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 address CoreDevice reports for the device's tunnel, and that tunnel encrypts the traffic. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect; it relays the redirect response to its client, whose requests follow at most a same-origin redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, or that are signed, such as Limrun API and download URLs and Revyl upload URLs, are checked right before each request. A Limrun download follows a redirect only from https to https or on the same origin, and drops its headers when it leaves the origin. The Metro companion opens the host bridge's socket only over `wss`, or `ws` to loopback. +A client never sends a daemon, proxy, Metro host bridge, cloud auth, or provider credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. 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. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect; it relays the redirect response to its client, whose requests follow at most a same-origin redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, or that are signed, such as Limrun API and download URLs and Revyl upload URLs, are checked right before each request. A Limrun download follows a redirect only from https to https or on the same origin, and drops its headers when it leaves the origin. The Metro companion opens the host bridge's socket only over `wss`, or `ws` to loopback. 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. From 221f66275ea4beadced4078cc25e1b0ed07138bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 16:31:04 +0100 Subject: [PATCH 14/22] fix(remote): send every credential through one checked primitive fetchWithCredential applies the transport rule to every URL it sends to, sends plain http direct and follows only same-origin redirects. The node:http requester takes the URL and applies the same rule. - a localhost name connects only to loopback addresses, over HTTP and the companion socket - the companion relays only paths on the local base URL, sends relayed credentials under the rule, and fails with the typed refusal - proxy answers outside /rpc name the admission reason - Metro bridge and companion POSTs follow same-origin redirects again - the direct requester decodes gzip, deflate and br as fetch does - the trust page names what the rule covers Co-Authored-By: Claude Sonnet 5.5 --- .../src/__tests__/runner-transport.test.ts | 1 - .../src/__tests__/test-host-defaults.ts | 13 +- .../apple-runner/src/runner-command-route.ts | 28 +- packages/apple-runner/src/runner-transport.ts | 29 +- .../src/credential-transport.test.ts | 23 ++ .../contracts/src/credential-transport.ts | 53 +++- .../daemon-client-liveness-probe.test.ts | 2 +- ...lient-loopback-probe-pooled-socket.test.ts | 2 +- .../daemon-client-transport-localhost.test.ts | 66 ++++ .../__tests__/daemon-client-transport.test.ts | 4 +- .../src/daemon-client-liveness-probe.ts | 2 +- .../src/daemon-client-loopback-probe.ts | 5 +- .../src/daemon-client-transport.ts | 12 +- packages/host-kit/src/direct-http.test.ts | 295 ++++++++++++++++-- packages/host-kit/src/direct-http.ts | 234 ++++++++++++-- .../host-kit/src/internal/transport.test.ts | 15 +- packages/host-kit/src/internal/transport.ts | 31 +- packages/provider-revyl/src/revyl-client.ts | 7 +- packages/proxy/README.md | 5 +- .../daemon-proxy-credential-transport.test.ts | 50 ++- packages/proxy/src/daemon-proxy.ts | 11 +- packages/proxy/src/transfer-transport.ts | 8 +- packages/proxy/src/upstream-admission.ts | 17 +- .../companion/client-companion-local-relay.ts | 75 +++++ ...tunnel-worker-credential-transport.test.ts | 216 ++++++++++--- .../client-companion-tunnel-worker.ts | 140 +++++---- .../metro/client-metro-auto-companion.test.ts | 21 +- .../react-native/src/metro/client-metro.ts | 32 +- .../upload-client-cancellation.test.ts | 15 +- packages/remote/src/artifact-download.ts | 4 +- .../remote/src/remote-request-diagnostics.ts | 2 +- packages/remote/src/upload-client.ts | 18 +- packages/remote/src/upload-stream.ts | 4 +- src/cli/cloud-auth-request.ts | 75 ++--- src/core/interactors/limrun-ios-files.ts | 4 +- .../interactors/limrun-ios-runner-products.ts | 31 +- src/core/interactors/limrun-ios-runner.ts | 24 +- src/core/limrun-download-file.ts | 19 +- .../remote-proxy-request-diagnostics.test.ts | 2 +- test/wire-compat/ledger.json | 30 +- website/docs/docs/error-reasons.md | 2 +- website/docs/docs/remote-proxy.md | 2 +- website/docs/docs/security-trust.md | 10 +- 43 files changed, 1240 insertions(+), 399 deletions(-) create mode 100644 packages/daemon-client/src/__tests__/daemon-client-transport-localhost.test.ts create mode 100644 packages/react-native/src/companion/client-companion-local-relay.ts diff --git a/packages/apple-runner/src/__tests__/runner-transport.test.ts b/packages/apple-runner/src/__tests__/runner-transport.test.ts index b321aae5f4..9a34cd0589 100644 --- a/packages/apple-runner/src/__tests__/runner-transport.test.ts +++ b/packages/apple-runner/src/__tests__/runner-transport.test.ts @@ -250,7 +250,6 @@ test.each([ kind: 'network', url: 'http://[fd00::123]:8100/command', cachedTunnelIp: false, - via: 'forwarded', } as const; await assert.rejects( diff --git a/packages/apple-runner/src/__tests__/test-host-defaults.ts b/packages/apple-runner/src/__tests__/test-host-defaults.ts index a09249b7ec..87b0ed554e 100644 --- a/packages/apple-runner/src/__tests__/test-host-defaults.ts +++ b/packages/apple-runner/src/__tests__/test-host-defaults.ts @@ -94,8 +94,9 @@ function appleToolingTestAdapters(): Pick< * environment, and the explicit Apple adapters above. It reads no platform-apple or root code. */ export async function createAppleRunnerTestHostDefaults(): Promise { + const hostKit = await loadRealHostKitCapabilities(); return { - ...(await loadRealHostKitCapabilities()), + ...hostKit, ...appleToolingTestAdapters(), hostEnvironment: createLiveTestHostEnvironment, shellQuote, @@ -104,9 +105,13 @@ export async function createAppleRunnerTestHostDefaults(): Promise await fetch(input, init), + // An explicit network adapter: the real rule, with global `fetch` as its sender, so a suite that + // stubs `fetch` observes every runner send. The real capability sends plain http around it. + fetchWithCredential: (input, init, destination) => + hostKit.fetchWithCredential(input, init, { + ...destination, + send: async (to, request) => await fetch(to, request), + }), leaseOwnerStateDir: () => undefined, hasDeviceClaimAuthority: () => false, }; diff --git a/packages/apple-runner/src/runner-command-route.ts b/packages/apple-runner/src/runner-command-route.ts index 9f3f33787d..60ef4ea781 100644 --- a/packages/apple-runner/src/runner-command-route.ts +++ b/packages/apple-runner/src/runner-command-route.ts @@ -1,4 +1,3 @@ -import { BlockList, isIPv6 } from 'node:net'; import type { RunnerEndpoint } from './runner-contract.ts'; import { isMacOs, type DeviceInfo } from '@agent-device/kernel/device'; import { resolveIosPhysicalDeviceControl } from './host.ts'; @@ -21,12 +20,11 @@ export type RunnerCommandRoute = url: string | null; cachedTunnelIp: boolean; /** - * How the URL was resolved: this Mac's loopback, the tunnel address CoreDevice reports for - * this device, a reported address that is not a tunnel address, or a URL a provider forwards. - * Only the tunnel route may carry the runner token over plain http to a host that is not - * loopback, because its tunnel encrypts the traffic. + * 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. */ - via: 'loopback' | 'coredevice-tunnel' | 'device-address' | 'forwarded'; + coreDeviceTunnel?: true; } | { kind: 'usbmux'; @@ -66,7 +64,7 @@ export function createRunnerCommandRouteResolver( timeoutBudgetMs?: number, forceRefresh = false, ): Promise => { - if (http) return { kind: 'network', url: http.url, cachedTunnelIp: false, via: 'forwarded' }; + if (http) return { kind: 'network', url: http.url, cachedTunnelIp: false }; if (runsOnThisHost(device)) return buildLoopbackRoute(port); const control = resolveIosPhysicalDeviceControl(device); if (control.backend === 'xctest') return buildUsbmuxRoute(device, port); @@ -111,12 +109,7 @@ function runsOnThisHost(device: DeviceInfo): boolean { } function buildLoopbackRoute(port: number): RunnerCommandRoute { - return { - kind: 'network', - url: `http://127.0.0.1:${port}/command`, - cachedTunnelIp: false, - via: 'loopback', - }; + return { kind: 'network', url: `http://127.0.0.1:${port}/command`, cachedTunnelIp: false }; } function buildTunnelRoute( @@ -128,17 +121,10 @@ function buildTunnelRoute( kind: 'network', url: tunnelIp ? `http://[${tunnelIp}]:${port}/command` : null, cachedTunnelIp, - via: tunnelIp && isCoreDeviceTunnelAddress(tunnelIp) ? 'coredevice-tunnel' : 'device-address', + coreDeviceTunnel: true, }; } -/** CoreDevice gives its tunnel a unique local IPv6 address, in `fd00::/8`. */ -function isCoreDeviceTunnelAddress(address: string): boolean { - const range = new BlockList(); - range.addSubnet('fd00::', 8, 'ipv6'); - return isIPv6(address) && range.check(address, 'ipv6'); -} - function readDeviceTunnelIpCache(deviceId: string): string | null { const cached = deviceTunnelIpCache.get(deviceId); if (!cached) return null; diff --git a/packages/apple-runner/src/runner-transport.ts b/packages/apple-runner/src/runner-transport.ts index 1fd02934a3..b7641ac50a 100644 --- a/packages/apple-runner/src/runner-transport.ts +++ b/packages/apple-runner/src/runner-transport.ts @@ -105,22 +105,6 @@ export async function postRunnerCommandOverRoute( 'no', ); } - // The request carries the runner token, and a forwarded one the provider's own headers. The - // resolver marks the loopback URL it builds and the CoreDevice tunnel address it recognizes; the - // tunnel is the one plain-http route off this machine. Every other route meets the credential - // transport rule. - if (route.via !== 'loopback' && route.via !== 'coredevice-tunnel') { - const { assertSecureCredentialTransport } = - await import('@agent-device/contracts/credential-transport'); - try { - assertSecureCredentialTransport( - route.url, - route.via === 'forwarded' ? 'Runner forwarding URL' : 'Runner device address', - ); - } catch (error) { - throw discloseDispatch(error as AppError, 'no'); - } - } const response = await fetchWithTimeout( route.url, { @@ -130,6 +114,11 @@ export async function postRunnerCommandOverRoute( }, timeoutMs, signal, + // The request carries the runner token, and a forwarded one the provider's own headers. + { + subject: endpoint.http ? 'Runner forwarding URL' : 'Runner device address', + coreDeviceTunnel: route.coreDeviceTunnel, + }, ); if (endpoint.http && [502, 503, 504].includes(response.status)) { await response.body?.cancel(); @@ -161,13 +150,15 @@ export async function fetchWithTimeout( init: RequestInit, timeoutMs: number, requestSignal?: AbortSignal, + destination: Readonly<{ subject: string; coreDeviceTunnel?: boolean }> = { + subject: 'Runner URL', + }, ): Promise { const timeoutSignal = AbortSignal.timeout(timeoutMs); const signal = requestSignal ? AbortSignal.any([requestSignal, timeoutSignal]) : timeoutSignal; try { - // The token travels in a header, so a redirect must never carry it elsewhere, and a - // plain-http send never goes through an environment proxy. - return await fetchWithCredential(url, { ...init, redirect: 'error', signal }); + // The token travels in a header, so a redirect must never carry it elsewhere. + return await fetchWithCredential(url, { ...init, redirect: 'error', signal }, destination); } catch (error) { // `AbortSignal.timeout` rejects with a bare DOMException that no recovery rule can // read. Only a rejection carrying that signal's own reason is our deadline: a diff --git a/packages/contracts/src/credential-transport.test.ts b/packages/contracts/src/credential-transport.test.ts index 8584ac15fd..ceedf5c772 100644 --- a/packages/contracts/src/credential-transport.test.ts +++ b/packages/contracts/src/credential-transport.test.ts @@ -72,3 +72,26 @@ test.each([ }), ); }); + +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 index ac5478441a..9673313880 100644 --- a/packages/contracts/src/credential-transport.ts +++ b/packages/contracts/src/credential-transport.ts @@ -1,33 +1,57 @@ +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. Callers check the final URL right before each send. +// machine. `@agent-device/host-kit` applies it to every URL it sends a credential to. /** 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. + // A credential would travel over plain http or ws to a host that is not loopback, to a `localhost` + // that resolves to no loopback address, 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): URL { +export function assertSecureCredentialTransport( + url: string | URL, + subject: string, + exceptions: CredentialTransportExceptions = {}, +): URL { const destination = typeof url === 'string' ? URL.parse(url) : url; - if (destination && isSecureCredentialDestination(destination)) return destination; - throw refusal( + 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.`, @@ -44,12 +68,23 @@ export function assertSecureCredentialSocket(url: string, subject: string): URL if (destination?.protocol === 'ws:' && isLoopbackHostname(destination.hostname)) { return destination; } - throw refusal(`${subject} must use wss to send credentials; ws is allowed only on loopback.`); + throw credentialTransportRefusal( + `${subject} must use wss to send credentials; ws is allowed only on loopback.`, + ); } -function refusal(message: string): AppError { +/** The typed refusal. It is only ever thrown before the credential leaves. */ +export 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/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts b/packages/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts index f87a58618d..b87871b986 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts @@ -144,7 +144,7 @@ test('the health leg rides a fresh connection, never the keep-alive pool', async else primed = true; res.end('{}'); }); - const httpRequester = await loadNodeHttpRequester('http:'); + const httpRequester = await loadNodeHttpRequester(new URL('http://127.0.0.1')); await withLoopback(server, async (port) => { // Prime: a full keep-alive request/response whose socket returns to the global pool. await new Promise((resolve, reject) => { diff --git a/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts index 1996a2ff99..e4d713d571 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts @@ -47,7 +47,7 @@ test('a fresh connect the host refused is not answered around by a pooled socket // the agent. It goes through the SAME module object the probe loads, or no candidate lands in the // pool and the case proves nothing. The request is bounded so a pool this case does not control // cannot hold it open to the test budget. - const requester = await hostTransport.loadNodeHttpRequester('http:'); + const requester = await hostTransport.loadNodeHttpRequester(new URL('http://127.0.0.1')); await new Promise((resolve, reject) => { const request = requester.request( { host: '127.0.0.1', port, path: '/health', method: 'GET', timeout: 2_000 }, diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport-localhost.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport-localhost.test.ts new file mode 100644 index 0000000000..6aba3d4624 --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-transport-localhost.test.ts @@ -0,0 +1,66 @@ +// A remote daemon URL that names `localhost` is admitted by name, so every send to it must connect +// only to a loopback address, whatever the resolver answers. + +import { afterEach, expect, test, vi } from 'vitest'; +import dns from 'node:dns'; +import http from 'node:http'; +import { isCredentialTransportRefusal } from '@agent-device/contracts/credential-transport'; +import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; +import { + bindTestCommandHost, + closeLoopbackServer, + createTestHostEnvironment, + listenOnLoopback, + mkdtempForTestSync, +} from '@agent-device/test-kit'; +import { + probeDaemonReachability, + readRemoteDaemonHealth, + sendRequest, +} from '../daemon-client-transport.ts'; + +bindTestCommandHost(); + +const servers: http.Server[] = []; +afterEach(async () => { + vi.restoreAllMocks(); + await Promise.all(servers.splice(0).map((server) => closeLoopbackServer(server))); +}); + +test('a localhost that resolves off loopback receives no health, probe or RPC request', async () => { + const received: string[] = []; + const server = http.createServer((req, res) => { + received.push(`${req.method} ${req.url} ${req.headers.authorization}`); + res.end('{}'); + }); + servers.push(server); + const info = { + token: 'daemon-secret', + pid: 0, + baseUrl: `http://localhost:${await listenOnLoopback(server)}`, + }; + // `0.0.0.0` reaches this machine's listener and is not a loopback address. + vi.spyOn(dns, 'lookup').mockImplementation((( + _hostname: string, + options: dns.LookupOptions, + callback: (...answer: unknown[]) => void, + ) => { + if (options.all) callback(null, [{ address: '0.0.0.0', family: 4 }]); + else callback(null, '0.0.0.0', 4); + }) as typeof dns.lookup); + + await expect(readRemoteDaemonHealth(info, 2_000)).rejects.toSatisfy(isCredentialTransportRefusal); + expect(await probeDaemonReachability(info, 'http', 2_000)).toMatchObject({ reachable: false }); + await expect( + sendRequest( + info, + { token: info.token, session: 'default', command: 'devices', positionals: [], flags: {} }, + 'http', + resolveDaemonPaths(mkdtempForTestSync('daemon-client-localhost-')), + 2_000, + { host: createTestHostEnvironment() }, + ), + ).rejects.toSatisfy(isCredentialTransportRefusal); + + expect(received).toEqual([]); +}); diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts index a7fa975558..187cc3b98b 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -119,9 +119,9 @@ test('the health deadline includes requester loading and forbids a late request' const actualLoad = hostTransport.loadNodeHttpRequester; const load = vi .spyOn(hostTransport, 'loadNodeHttpRequester') - .mockImplementation(async (protocol) => { + .mockImplementation(async (url, credential) => { await blocked; - return actualLoad(protocol); + return actualLoad(url, credential); }); let probing: Promise | undefined; try { diff --git a/packages/daemon-client/src/daemon-client-liveness-probe.ts b/packages/daemon-client/src/daemon-client-liveness-probe.ts index 7a35600be2..3bda5429fe 100644 --- a/packages/daemon-client/src/daemon-client-liveness-probe.ts +++ b/packages/daemon-client/src/daemon-client-liveness-probe.ts @@ -152,7 +152,7 @@ function probeHttpHealth(httpPort: number, deadlineAtMs: number): ProbeLeg { // This leg builds detached. Catch transport-construction errors here so they settle the probe. void (async () => { try { - const transport = await loadNodeHttpRequester('http:'); + const transport = await loadNodeHttpRequester(new URL(`http://127.0.0.1:${httpPort}/health`)); const request = transport.request( // `agent: false` is load-bearing, not hygiene: since Node 19 the global agent keeps sockets // alive, so a pooled request would ride an idle socket from an earlier command's health read diff --git a/packages/daemon-client/src/daemon-client-loopback-probe.ts b/packages/daemon-client/src/daemon-client-loopback-probe.ts index b72d113d41..90506a509a 100644 --- a/packages/daemon-client/src/daemon-client-loopback-probe.ts +++ b/packages/daemon-client/src/daemon-client-loopback-probe.ts @@ -147,7 +147,10 @@ export async function probeHttpEndpoint(probe: HttpEndpointProbe): Promise loadNodeHttpRequester(url.protocol), probe.timeoutMs); + const loaded = await settleWithin( + () => loadNodeHttpRequester(url, { subject: 'Daemon health probe URL' }), + probe.timeoutMs, + ); if (loaded.kind === 'deadline') return { reachable: false }; // What the loader spent is gone from the request's window: the budget belongs to the probe, not to // each step inside it. diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 8104d0c981..f751216cf0 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -298,14 +298,14 @@ async function readDaemonHttpHealth( const timeoutSignal = AbortSignal.timeout(Math.ceil(timeoutMs)); const signal = callerSignal ? AbortSignal.any([timeoutSignal, callerSignal]) : timeoutSignal; const transport = await Promise.race([ - loadNodeHttpRequester(url.protocol, 'direct'), + loadNodeHttpRequester(url, { subject: 'Remote daemon base URL' }), new Promise((resolve) => { signal.addEventListener('abort', () => resolve(null), { once: true }); }), ]); const unreachable = (): RemoteDaemonHealth => unreachableDaemonHealth(timeoutSignal, deadline); if (!transport || healthProbeExpired(signal, deadline)) return unreachable(); - return await new Promise((resolve) => { + return await new Promise((resolve, reject) => { const headers = info.baseUrl ? buildDaemonHttpAuthHeaders(info.token) : {}; const req = transport.request( { @@ -340,8 +340,9 @@ async function readDaemonHttpHealth( req.destroy(); resolve({ reachable: false, timedOut: true }); }); - req.on('error', () => { - resolve(unreachable()); + req.on('error', (error) => { + if (error instanceof AppError) reject(error); + else resolve(unreachable()); }); req.end(); }); @@ -811,7 +812,7 @@ async function sendHttpRequest( } if (checked) headers[DAEMON_HTTP_RPC_PROTOCOL_HEADER] = String(DAEMON_RPC_PROTOCOL_VERSION); const checkedRpc = checked ? await import('./daemon-client-checked-rpc.ts') : undefined; - const transport = await loadNodeHttpRequester(rpcUrl.protocol, 'direct'); + const transport = await loadNodeHttpRequester(rpcUrl, { subject: 'Remote daemon base URL' }); const callerSignal = options.signal; refuseAbortedRequest(callerSignal, req.meta?.requestId); @@ -951,6 +952,7 @@ async function sendHttpRequest( // from emitting a `daemon_request_socket_error` diagnostic; a genuine transport error still // arrives before the settle and rejects. if (settled) return; + if (err instanceof AppError) return rejectOnce(err); if (connectWatch?.unconnected()) return rejectOnce(connectWatch.failure(false)); rejectOnce(handleTransportError(err, req.meta?.requestId, remote, requestSent)); }); diff --git a/packages/host-kit/src/direct-http.test.ts b/packages/host-kit/src/direct-http.test.ts index 772f277158..83f1cee32e 100644 --- a/packages/host-kit/src/direct-http.test.ts +++ b/packages/host-kit/src/direct-http.test.ts @@ -4,8 +4,10 @@ import http from 'node:http'; import path from 'node:path'; import { Readable } from 'node:stream'; import { promisify } from 'node:util'; -import type { AddressInfo } from 'node:net'; -import { fetchOverDirectHttp, fetchWithCredential, loadDirectHttpAgent } from './direct-http.ts'; +import dns from 'node:dns'; +import net, { type AddressInfo } from 'node:net'; +import zlib from 'node:zlib'; +import { fetchWithCredential, loadDirectHttpAgent, type CredentialSend } from './direct-http.ts'; import { loadNodeHttpRequester } from './transport.ts'; // A credential sent over plain http goes only to loopback, and an environment proxy on another host @@ -62,7 +64,7 @@ test.each([ (target: string) => ` import http from 'node:http'; import { loadDirectHttpAgent } from ${JSON.stringify(TRANSPORT)}; - const agent = await loadDirectHttpAgent('http:'); + const agent = await loadDirectHttpAgent(); await new Promise((resolve, reject) => { const req = http.request(${JSON.stringify(target)}, { agent, headers: { authorization: 'Bearer secret' } }, (res) => { res.resume(); res.on('end', resolve); }); req.on('error', reject); @@ -74,14 +76,7 @@ test.each([ 'fetchWithCredential', (target: string) => ` import { fetchWithCredential } from ${JSON.stringify(TRANSPORT)}; - const response = await fetchWithCredential(${JSON.stringify(target)}, { headers: { authorization: 'Bearer secret' } }); - console.log(await response.text() === 'ok' ? 'sent' : 'bad');`, - ], - [ - 'fetchOverDirectHttp', - (target: string) => ` - import { fetchOverDirectHttp } from ${JSON.stringify(TRANSPORT)}; - const response = await fetchOverDirectHttp(new Request(${JSON.stringify(target)}, { headers: { authorization: 'Bearer secret' } })); + const response = await fetchWithCredential(${JSON.stringify(target)}, { headers: { authorization: 'Bearer secret' } }, { subject: 'Test URL' }); console.log(await response.text() === 'ok' ? 'sent' : 'bad');`, ], ])('%s reaches loopback directly, never through an environment proxy', async (_label, script) => { @@ -97,6 +92,11 @@ test.each([ expect(direct).toEqual(['GET /rpc Bearer secret']); }); +/** One request through the primitive, as a caller with no transport of its own sends it. */ +function send(url: string, init: RequestInit = {}, options: Partial = {}) { + return fetchWithCredential(url, init, { subject: 'Test URL', ...options }); +} + function deferred() { let resolve!: () => void; const promise = new Promise((done) => (resolve = done)); @@ -133,7 +133,7 @@ test('a post declares its length and returns a redirect without following it', a }); }); - const response = await fetchWithCredential(origin, { + const response = await send(origin, { method: 'POST', body: 'payload', redirect: 'manual', @@ -141,7 +141,7 @@ test('a post declares its length and returns a redirect without following it', a expect(response.status).toBe(307); await expect( - fetchWithCredential(origin, { method: 'POST', body: 'payload', redirect: 'error' }), + send(origin, { method: 'POST', body: 'payload', redirect: 'error' }), ).rejects.toThrow(TypeError); expect(seen).toEqual(['7 payload', '7 payload']); }); @@ -151,7 +151,7 @@ test('a refused connection rejects as fetch does, with the socket error as the c const port = await listenLocal(server); await closeLocal(server); - await expect(fetchWithCredential(`http://127.0.0.1:${port}/`)).rejects.toMatchObject({ + await expect(send(`http://127.0.0.1:${port}/`)).rejects.toMatchObject({ name: 'TypeError', message: 'fetch failed', cause: { code: 'ECONNREFUSED' }, @@ -164,7 +164,7 @@ test('an abort before the response rejects with its reason and closes the connec const controller = new AbortController(); const reason = new Error('caller gave up'); - const pending = fetchWithCredential(origin, { signal: controller.signal }); + const pending = send(origin, { signal: controller.signal }); await received.promise; controller.abort(reason); @@ -176,7 +176,7 @@ test('an abort during the response body fails the read and closes the connection const { origin, closed } = await serveWith(sendHalf); const controller = new AbortController(); const reason = new Error('caller gave up'); - const response = await fetchWithCredential(origin, { signal: controller.signal }); + const response = await send(origin, { signal: controller.signal }); const reader = response.body!.getReader(); await reader.read(); @@ -207,7 +207,7 @@ test('a peer that never answers ends the request with the idle timeout', async ( const { origin, closed } = await serveWith(stayQuiet); const asked = shortenIdleTimeout(); - await expect(fetchOverDirectHttp(new Request(origin))).rejects.toMatchObject(idleTimeout); + await expect(send(origin)).rejects.toMatchObject(idleTimeout); await closed; expect(asked).toEqual([300_000]); @@ -216,7 +216,7 @@ test('a peer that never answers ends the request with the idle timeout', async ( test('a body that goes silent fails the read with the idle timeout', async () => { const { origin, closed } = await serveWith(sendHalf); shortenIdleTimeout(); - const response = await fetchWithCredential(origin); + const response = await send(origin); await expect(response.text()).rejects.toMatchObject(idleTimeout); await closed; @@ -224,11 +224,11 @@ test('a body that goes silent fails the read with the idle timeout', async () => test('the credential requester keeps its direct agent whatever the options name', async () => { const { origin } = await serveWith((_req, res) => void res.end()); - const direct = await loadDirectHttpAgent('http:'); + const pooled = await loadDirectHttpAgent(); const request = vi.spyOn(http, 'request'); - const requester = await loadNodeHttpRequester('http:', 'direct'); + const requester = await loadNodeHttpRequester(new URL(origin), { subject: 'Test URL' }); - for (const agent of [undefined, new http.Agent()]) { + for (const agent of [undefined, new http.Agent(), false as const]) { const options: http.RequestOptions = { host: '127.0.0.1', port: new URL(origin).port, agent }; await new Promise((resolve, reject) => { const sent = requester.request(options, (res) => { @@ -240,10 +240,11 @@ test('the credential requester keeps its direct agent whatever the options name' }); } - expect(request.mock.calls.map(([options]) => (options as http.RequestOptions).agent)).toEqual([ - direct, - direct, - ]); + const used = request.mock.calls.map(([options]) => (options as http.RequestOptions).agent); + expect(used.slice(0, 2)).toEqual([pooled, pooled]); + // `agent: false` asks for a connection of its own, still a direct one. + expect(used[2]).not.toBe(pooled); + expect(used[2]).toBeInstanceOf(http.Agent); }); /** A server that records each upload's framing and body, and reports its first bytes. */ @@ -278,7 +279,7 @@ test.each([ yield Buffer.from('second'); } - const response = await fetchWithCredential(server.origin, { + const response = await send(server.origin, { method: 'PUT', ...(headers ? { headers } : {}), body: body() as unknown as BodyInit, @@ -321,7 +322,7 @@ test.each(stalledStreams)('an abort during an upload releases %s', async (_label const controller = new AbortController(); const reason = new Error('caller gave up'); - const pending = fetchWithCredential(server.origin, { + const pending = send(server.origin, { method: 'PUT', body: source(released.resolve) as BodyInit, signal: controller.signal, @@ -343,7 +344,7 @@ test.each(stalledStreams)( const reason = new Error('caller gave up'); await expect( - fetchWithCredential(server.origin, { + send(server.origin, { method: 'PUT', body: source(released.resolve) as BodyInit, signal: AbortSignal.abort(reason), @@ -365,10 +366,246 @@ test('a streamed body that fails rejects the request as fetch does', async () => } await expect( - fetchWithCredential(server.origin, { + send(server.origin, { method: 'PUT', body: body() as unknown as BodyInit, duplex: 'half', } as RequestInit), ).rejects.toMatchObject({ message: 'fetch failed', cause: failure }); }); + +/** A loopback server answering each path from `routes`, recording every request it gets. */ +async function serveRoutes(routes: Record, string?]>) { + const received: string[] = []; + const { origin } = await serveWith((req, res) => { + let body = ''; + req.on('data', (chunk) => (body += String(chunk))); + req.on('end', () => { + received.push( + [req.method, req.url, req.headers.authorization, req.headers['content-type'], body].join( + ' ', + ), + ); + const [status, headers, answer] = routes[req.url ?? ''] ?? [200, {}, 'done']; + res.writeHead(status, headers).end(answer); + }); + }); + return { origin, received }; +} + +const credentialPost = { + method: 'POST', + headers: { authorization: 'Bearer secret', 'content-type': 'text/plain' }, + body: 'payload', +}; + +test.each([ + [307, 'POST /moved Bearer secret text/plain payload'], + [308, 'POST /moved Bearer secret text/plain payload'], + [301, 'GET /moved Bearer secret '], + [303, 'GET /moved Bearer secret '], +])('a same-origin %i is followed as fetch would send it', async (status, followed) => { + const server = await serveRoutes({ '/start': [status, { location: '/moved' }] }); + + const response = await send(`${server.origin}/start`, credentialPost); + + expect(await response.text()).toBe('done'); + expect(server.received).toEqual(['POST /start Bearer secret text/plain payload', followed]); +}); + +test('a redirect off the origin is returned as the answer, and its target gets nothing', async () => { + const other = await serveRoutes({}); + const server = await serveRoutes({ + '/start': [307, { location: `${other.origin}/moved` }], + '/user': [307, { location: '//user:password@127.0.0.1/moved' }], + }); + + for (const path of ['/start', '/user']) { + expect((await send(`${server.origin}${path}`, credentialPost)).status).toBe(307); + } + expect(other.received).toEqual([]); +}); + +test('an https request redirected to plain http is returned, not followed', async () => { + const sent: string[] = []; + const response = await send('https://remote.example/start', credentialPost, { + send: async (input) => { + sent.push(String(input)); + return new Response(null, { + status: 307, + headers: { location: 'http://remote.example/start' }, + }); + }, + }); + + expect(response.status).toBe(307); + expect(sent).toEqual(['https://remote.example/start']); +}); + +test('a redirect loop ends after three hops, and a Request is sent once', async () => { + const server = await serveRoutes({ '/loop': [307, { location: '/loop' }] }); + + expect((await send(`${server.origin}/loop`)).status).toBe(307); + expect(server.received).toHaveLength(4); + + const once = await fetchWithCredential( + new Request(`${server.origin}/loop`), + {}, + { subject: 'x' }, + ); + expect(once.status).toBe(307); + expect(server.received).toHaveLength(5); +}); + +test.each(['http://10.0.0.7/start', 'http://[fd00::1]/start', 'not a url'])( + '%s is refused before any transport sees it', + async (url) => { + const transport = vi.fn(); + const request = vi.spyOn(http, 'request'); + + for (const options of [{}, { send: transport }]) { + await expect(send(url, credentialPost, options)).rejects.toMatchObject({ + details: { reason: 'insecure_credential_transport', dispatched: 'no' }, + }); + } + expect(transport).not.toHaveBeenCalled(); + expect(request).not.toHaveBeenCalled(); + }, +); + +/** Makes the resolver answer `localhost` with `address`, in both callback shapes. */ +function resolveLocalhostTo(address: string): void { + vi.spyOn(dns, 'lookup').mockImplementation((( + _hostname: string, + options: dns.LookupOptions, + callback: (...answer: unknown[]) => void, + ) => { + if (options.all) callback(null, [{ address, family: 4 }]); + else callback(null, address, 4); + }) as typeof dns.lookup); +} + +test('localhost that resolves off loopback receives nothing, on every direct agent', async () => { + const server = await serveRoutes({}); + const url = new URL(server.origin.replace('127.0.0.1', 'localhost')); + // `0.0.0.0` reaches this machine's listener and is not a loopback address. + resolveLocalhostTo('0.0.0.0'); + const refused = { details: { reason: 'insecure_credential_transport' } }; + + await expect(send(url.href, credentialPost)).rejects.toMatchObject(refused); + const requester = await loadNodeHttpRequester(url, { subject: 'Test URL' }); + for (const agent of [undefined, false as const]) { + await expect( + new Promise((resolve, reject) => { + const sent = requester.request( + { host: url.hostname, port: url.port, agent, headers: credentialPost.headers }, + resolve, + ); + sent.on('error', reject); + sent.end(); + }), + ).rejects.toMatchObject(refused); + } + expect(server.received).toEqual([]); +}); + +test('localhost that resolves to loopback is reached', async () => { + const server = await serveRoutes({}); + resolveLocalhostTo('127.0.0.1'); + + const response = await send(server.origin.replace('127.0.0.1', 'localhost')); + + expect(await response.text()).toBe('done'); +}); + +const PLAIN = 'compressed '.repeat(200); + +test.each([ + ['gzip', zlib.gzipSync(PLAIN)], + ['x-gzip', zlib.gzipSync(PLAIN)], + ['deflate', zlib.deflateSync(PLAIN)], + ['deflate', zlib.deflateRawSync(PLAIN)], + ['br', zlib.brotliCompressSync(PLAIN)], + ['gzip, br', zlib.brotliCompressSync(zlib.gzipSync(PLAIN))], +])('a %s answer is decoded, with the headers of the decoded body', async (encoding, bytes) => { + const { origin } = await serveWith((_req, res) => { + res.writeHead(200, { 'content-encoding': encoding, 'content-length': bytes.length }).end(bytes); + }); + + const response = await send(origin); + + expect(await response.text()).toBe(PLAIN); + expect(response.headers.get('content-encoding')).toBe(null); + expect(response.headers.get('content-length')).toBe(null); +}); + +test('a coding fetch does not decode is passed through with its headers', async () => { + const { origin } = await serveWith((_req, res) => { + res.writeHead(200, { 'content-encoding': 'compress', 'content-length': '5' }).end('bytes'); + }); + + const response = await send(origin); + + expect(await response.text()).toBe('bytes'); + expect(response.headers.get('content-encoding')).toBe('compress'); +}); + +test('a damaged compressed answer fails the read', async () => { + const { origin } = await serveWith((_req, res) => { + res.writeHead(200, { 'content-encoding': 'gzip' }).end('not gzip'); + }); + + await expect((await send(origin)).text()).rejects.toThrow(); +}); + +test('an abort during a compressed answer fails the read with its reason', async () => { + const { origin, closed } = await serveWith((_req, res) => { + res.writeHead(200, { 'content-encoding': 'gzip' }); + res.write(zlib.gzipSync(PLAIN).subarray(0, 20)); + }); + const controller = new AbortController(); + const reason = new Error('caller gave up'); + const pending = (await send(origin, { signal: controller.signal })).text(); + + controller.abort(reason); + + await expect(pending).rejects.toBe(reason); + await closed; +}); + +test('a CoreDevice tunnel request goes to the bracketed address through node:http', async () => { + const seen: string[] = []; + const standIn = await serveWith((req, res) => { + seen.push(`${req.method} ${req.url} ${req.headers.host} ${req.headers['content-length']}`); + res.end('{}'); + }); + const options: http.RequestOptions[] = []; + const request = http.request; + // No machine holds the tunnel address, so the connection is the stand-in's; the rest of the + // request is what `node:http` was given. + vi.spyOn(http, 'request').mockImplementation((( + asked: http.RequestOptions, + callback: (res: http.IncomingMessage) => void, + ) => { + options.push(asked); + return request( + { + ...asked, + agent: undefined, + createConnection: () => net.connect(Number(new URL(standIn.origin).port), '127.0.0.1'), + }, + callback, + ); + }) as typeof http.request); + + const response = await send( + 'http://[fd00::1]:8100/command', + { method: 'POST', body: 'tap' }, + { coreDeviceTunnel: true }, + ); + + expect(response.status).toBe(200); + expect(options).toMatchObject([{ host: 'fd00::1', port: '8100', path: '/command' }]); + expect(options[0]!.agent).toBe(await loadDirectHttpAgent()); + expect(seen).toEqual(['POST /command [fd00::1]:8100 3']); +}); diff --git a/packages/host-kit/src/direct-http.ts b/packages/host-kit/src/direct-http.ts index 88a96c1413..5b4ac42716 100644 --- a/packages/host-kit/src/direct-http.ts +++ b/packages/host-kit/src/direct-http.ts @@ -1,25 +1,68 @@ +import type { LookupAddress } from 'node:dns'; import type { Agent, IncomingMessage } from 'node:http'; +import type { LookupFunction } from 'node:net'; +import type { Duplex, Transform } from 'node:stream'; import type { ReadableStream as WebReadableStream } from 'node:stream/web'; +import { + assertSecureCredentialTransport, + credentialTransportRefusal, + type CredentialTransportExceptions, +} from '@agent-device/contracts/credential-transport'; +import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; -// Loaded at send time by the code that sends a credential over plain http, never at module scope. +// The one way a credential leaves this process over HTTP: `fetchWithCredential`, and the agent and +// lookup it shares with the `node:http` and WebSocket senders. Loaded at send time by the code that +// sends a credential, never at module scope. + +/** + * Resolves a name to loopback addresses only. `localhost` is the one name a plain-http credential + * may name, and a resolver is free to answer it with any address. + */ +export const lookupLoopbackOnly: LookupFunction = (hostname, options, callback) => { + void import('node:dns').then(({ default: dns }) => { + dns.lookup(hostname, { ...options, all: true }, (error, addresses: LookupAddress[]) => { + if (error) return callback(error, []); + const loopback = addresses.filter(({ address }) => isLoopbackHostname(address)); + const [first] = loopback; + if (!first) { + const refusal = credentialTransportRefusal( + 'localhost resolves to no loopback address, so no credential is sent to it.', + ); + return callback(refusal, []); + } + if (options.all) callback(null, loopback); + else callback(null, first.address, first.family); + }); + }); +}; let directHttpAgent: Agent | undefined; /** * The agent for a plain-http request that carries a credential: a direct connection that never - * routes through an environment proxy (`NODE_USE_ENV_PROXY` with `HTTP_PROXY`). Plain http - * carries credentials only to loopback, and a proxy on another host would read them in cleartext. - * Returns `undefined` for https, which keeps the default agent. + * routes through an environment proxy (`NODE_USE_ENV_PROXY` with `HTTP_PROXY`), which would read + * the credential in cleartext, and that connects a name only to a loopback address. A `fresh` agent + * opens its own connection instead of reusing a pooled one. */ -export async function loadDirectHttpAgent(protocol: string): Promise { - if (protocol !== 'http:') return undefined; +export async function loadDirectHttpAgent(fresh = false): Promise { const http = (await import('node:http')).default; - directHttpAgent ??= new http.Agent({ keepAlive: true, scheduling: 'lifo', timeout: 5_000 }); + const options = { lookup: lookupLoopbackOnly }; + if (fresh) return new http.Agent(options); + directHttpAgent ??= new http.Agent({ + ...options, + keepAlive: true, + scheduling: 'lifo', + timeout: 5_000, + }); return directHttpAgent; } -const NULL_BODY_STATUSES = new Set([204, 205, 304]); +export const NULL_BODY_STATUSES: ReadonlySet = new Set([204, 205, 304]); + +export function isRedirectStatus(status: number): boolean { + return [301, 302, 303, 307, 308].includes(status); +} /** A `node:http` response's headers as Fetch `Headers`, repeated values kept in order. */ export function responseHeadersOf(res: IncomingMessage): Headers { @@ -31,7 +74,6 @@ export function responseHeadersOf(res: IncomingMessage): Headers { return headers; } -const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); // The silence `fetch` allows while it waits for response headers or the next body bytes. It // replaces the agent's 5 s timeout, which is for pooled sockets and would end a long command. const IDLE_TIMEOUT_MS = 300_000; @@ -41,28 +83,80 @@ const DIRECT_HTTP_REASONS = { idleTimeout: { reason: 'direct_http_idle_timeout' }, } as const satisfies ReasonTable<'remote connection'>; +type Decoding = { + zlib: typeof import('node:zlib'); + Transform: typeof import('node:stream').Transform; +}; + +/** The decoders `fetch` applies for a `Content-Encoding`, or none when it names another coding. */ +function contentDecoders(decoding: Decoding, encoding: string | null): Transform[] { + const { zlib } = decoding; + // Flushes what has arrived, so a streamed answer is readable as it comes. + const options = { flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH }; + const codings = (encoding ?? '').toLowerCase().split(','); + const decoders = codings.reverse().map((coding) => { + switch (coding.trim()) { + case 'gzip': + case 'x-gzip': + return zlib.createGunzip(options); + case 'deflate': + return createDeflateDecoder(decoding, options); + case 'br': + return zlib.createBrotliDecompress({ flush: zlib.constants.BROTLI_OPERATION_FLUSH }); + default: + return undefined; + } + }); + return decoders.every((decoder) => decoder !== undefined) ? decoders : []; +} + +/** `deflate` is zlib-wrapped by the standard and raw from some servers; the first byte tells. */ +function createDeflateDecoder( + { zlib, Transform }: Decoding, + options: import('node:zlib').ZlibOptions, +): Transform { + let inflate: import('node:zlib').Inflate | undefined; + const decoder: Transform = new Transform({ + transform(chunk: Buffer, _encoding, done) { + if (!inflate) { + const wrapped = (chunk[0]! & 0x0f) === 0x08; + inflate = wrapped ? zlib.createInflate(options) : zlib.createInflateRaw(options); + inflate.on('data', (decoded) => decoder.push(decoded)); + inflate.on('error', (error) => decoder.destroy(error)); + } + inflate.write(chunk, () => done()); + }, + flush(done) { + if (!inflate) return done(); + inflate.once('end', () => done()); + inflate.end(); + }, + }); + return decoder; +} + /** - * Sends one Fetch request over `node:http` with `loadDirectHttpAgent`, for a plain-http - * destination that receives a credential. It never follows a redirect: a 3xx is returned as is, or - * fails the request that asks for `redirect: 'error'`. As with `fetch`, a failed exchange rejects - * with `TypeError('fetch failed')` carrying the cause. An abort ends the exchange with the signal's - * reason, and five silent minutes end it with a `direct_http_idle_timeout` error: the call rejects - * with it, or after the response, the body read does. + * Sends one request over `node:http` with the direct agent. It never follows a redirect: a 3xx is + * returned as is, or fails the request that asks for `redirect: 'error'`. As with `fetch`, a gzip, + * deflate or br body is decoded, and a failed exchange rejects with `TypeError('fetch failed')` + * carrying the cause, except a typed refusal, which rejects as itself. An abort ends the exchange + * with the signal's reason, and five silent minutes end it with a `direct_http_idle_timeout` error: + * the call rejects with it, or after the response, the body read does. * * `request`'s own body is read whole, so the request declares its length. A `streamedBody` is piped * instead, as it arrives, with the length the headers declare or else chunked. */ -export async function fetchOverDirectHttp( +async function fetchOverDirectHttp( request: Request, streamedBody?: AsyncIterable, ): Promise { const url = new URL(request.url); - if (url.protocol !== 'http:') throw new TypeError('fetchOverDirectHttp sends plain http only'); // The module object itself, so a stubbed `request` is the one called. - const [{ default: http }, agent, { Readable }] = await Promise.all([ + const [{ default: http }, agent, { Readable, Transform, pipeline }, zlib] = await Promise.all([ import('node:http'), - loadDirectHttpAgent('http:'), + loadDirectHttpAgent(), import('node:stream'), + import('node:zlib'), ]); // Taken over before anything can end the exchange, so that every way it fails releases it. A // stream is destroyed or cancelled even while a read is pending, which the return of an async @@ -77,7 +171,8 @@ export async function fetchOverDirectHttp( const exchange = () => new Promise((resolve, reject) => { let response: IncomingMessage | undefined; - const fail = (cause: unknown) => reject(new TypeError('fetch failed', { cause })); + const fail = (cause: unknown) => + reject(cause instanceof AppError ? cause : new TypeError('fetch failed', { cause })); const end = (reason: Error) => { reject(reason); response?.destroy(reason); @@ -98,18 +193,30 @@ export async function fetchOverDirectHttp( // The body stream reports an error to its reader; an unread body has no other listener. res.on('error', () => undefined); const status = res.statusCode ?? 502; - if (request.redirect === 'error' && REDIRECT_STATUSES.has(status)) { + if (request.redirect === 'error' && isRedirectStatus(status)) { res.destroy(); fail(new Error('unexpected redirect')); return; } const nullBody = request.method === 'HEAD' || NULL_BODY_STATUSES.has(status); if (nullBody) res.resume(); + const headers = responseHeadersOf(res); + const decoders = nullBody + ? [] + : contentDecoders({ zlib, Transform }, headers.get('content-encoding')); + let body: IncomingMessage | Duplex = res; + if (decoders.length > 0) { + headers.delete('content-encoding'); + headers.delete('content-length'); + body = decoders.at(-1)!; + // Carries a failure or a cancellation between the socket and the reader. + pipeline([res, ...decoders], () => undefined); + } resolve( - new Response(nullBody ? null : (Readable.toWeb(res) as ReadableStream), { + new Response(nullBody ? null : (Readable.toWeb(body) as ReadableStream), { status, statusText: res.statusMessage, - headers: responseHeadersOf(res), + headers, }), ); }, @@ -159,24 +266,89 @@ export async function fetchOverDirectHttp( } } +/** How many same-origin redirects a credential-bearing request follows. */ +const MAX_FOLLOWED_REDIRECTS = 3; + +export type CredentialSend = CredentialTransportExceptions & { + /** Names the setting a refusal is about. */ + subject: string; + /** The caller's own transport, which carries every request the rule admits. */ + send?: typeof fetch; +}; + /** - * Sends one credential-bearing Fetch request. Plain http goes direct through - * `fetchOverDirectHttp`, so an environment proxy never reads the credential in cleartext; anything - * else goes through global `fetch`. The caller has already applied the credential transport rule. - * An injected `send` is the caller's own transport and carries every request. + * Sends a request that carries a credential, and is the only way to send one with Fetch semantics. + * Every URL it sends to meets the credential transport rule first. Plain http goes direct over + * `node:http`, never through an environment proxy; https goes through global `fetch`; an injected + * `send` replaces both. + * + * It never follows a redirect off the origin. A URL with `redirect: 'follow'`, the default, follows + * up to three redirects on the same origin, keeping method and body on a 307 or 308; any other + * redirect is returned as the answer. A `Request` is sent once. */ export async function fetchWithCredential( - input: string | URL, - init: RequestInit = {}, - send?: typeof fetch, + input: string | URL | Request, + init: RequestInit, + { subject, send, ...exceptions }: CredentialSend, +): Promise { + const redirect = init.redirect ?? (input instanceof Request ? input.redirect : 'follow'); + let target = input; + let hop = init; + for (let followed = 0; ; followed += 1) { + const url = assertSecureCredentialTransport( + target instanceof Request ? target.url : target, + subject, + exceptions, + ); + const next = { ...hop, redirect: redirect === 'error' ? redirect : ('manual' as const) }; + const response = await sendOnce(target, next, send); + if (redirect !== 'follow' || target instanceof Request) return response; + const followedTo = + followed < MAX_FOLLOWED_REDIRECTS ? sameOriginHop(response, url, hop) : undefined; + if (!followedTo) return response; + await response.body?.cancel().catch(() => undefined); + [target, hop] = followedTo; + } +} + +async function sendOnce( + input: string | URL | Request, + init: RequestInit, + send: typeof fetch | undefined, ): Promise { if (send) return await send(input, init); - if (new URL(input).protocol !== 'http:') return await fetch(input, init); + const url = new URL(input instanceof Request ? input.url : input); + if (url.protocol !== 'http:') return await fetch(input, init); const { body } = init; if (!isStreamedBody(body)) return await fetchOverDirectHttp(new Request(input, init)); return await fetchOverDirectHttp(new Request(input, { ...init, body: null }), body); } +/** + * The URL and request a redirect on the same origin leads to, as `fetch` would send it, or + * `undefined` for any other answer. A streamed body cannot be sent twice. + */ +function sameOriginHop( + response: Response, + from: URL, + init: RequestInit, +): [URL, RequestInit] | undefined { + if (!isRedirectStatus(response.status)) return undefined; + const location = response.headers.get('location'); + if (location === null) return undefined; + const url = URL.parse(location, from); + if (!url || url.origin !== from.origin || url.username || url.password) return undefined; + const method = (init.method ?? 'GET').toUpperCase(); + const becomesGet = + response.status === 303 + ? method !== 'GET' && method !== 'HEAD' + : response.status < 303 && method === 'POST'; + if (!becomesGet) return isStreamedBody(init.body) ? undefined : [url, init]; + const headers = new Headers(init.headers); + for (const name of ['content-type', 'content-length', 'content-encoding']) headers.delete(name); + return [url, { ...init, method: 'GET', body: null, headers }]; +} + /** A body that arrives in pieces: a web or Node stream, or any other async iterable. */ function isStreamedBody(body: unknown): body is AsyncIterable { return typeof body === 'object' && body !== null && Symbol.asyncIterator in body; diff --git a/packages/host-kit/src/internal/transport.test.ts b/packages/host-kit/src/internal/transport.test.ts index 51dfd5420b..baec8612f3 100644 --- a/packages/host-kit/src/internal/transport.test.ts +++ b/packages/host-kit/src/internal/transport.test.ts @@ -24,9 +24,20 @@ test('consumeTextLines trims complete lines and retains a partial line', () => { assert.equal(second.buffer, ''); }); +test.each(['http://10.0.0.7:4310', 'http://[fd00::1]:4310'])( + 'loadNodeHttpRequester refuses a credential to %s', + async (url) => { + await assert.rejects( + () => loadNodeHttpRequester(new URL(url), { subject: 'Test URL' }), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'insecure_credential_transport', + ); + }, +); + test('loadNodeHttpRequester selects the protocol module and keeps request mutable', async () => { - const httpRequester = await loadNodeHttpRequester('http:'); - const httpsRequester = await loadNodeHttpRequester('https:'); + const httpRequester = await loadNodeHttpRequester(new URL('http://127.0.0.1')); + const httpsRequester = await loadNodeHttpRequester(new URL('https://remote.example')); assert.equal(httpRequester, http); assert.equal(httpsRequester, https); diff --git a/packages/host-kit/src/internal/transport.ts b/packages/host-kit/src/internal/transport.ts index 89cab8438a..bc06b4b800 100644 --- a/packages/host-kit/src/internal/transport.ts +++ b/packages/host-kit/src/internal/transport.ts @@ -38,23 +38,32 @@ export type NodeHttpRequester = Pick; * object a static `import http from 'node:http'` yields -- its `request` * property is mutable, which the transport tests rely on to stub requests. * - * `credential: 'direct'` is for a request that carries a credential: over plain http (loopback - * only) it connects directly and never through an environment proxy. Call that requester as - * `request(options, callback)`, its only form. Its direct agent always replaces an `agent` among - * the options, because any other agent could route the credential through a proxy. It still calls - * the module's `request` at send time. + * Pass `credential` for a request that carries one. `url` then meets the credential transport rule, + * and plain http connects directly, never through an environment proxy, and to `localhost` only at a + * loopback address. That requester is called as `request(options, callback)`, its only form, with + * the options of `url`. Its direct agent always replaces an `agent` among them, since another agent + * could send the credential through a proxy; `agent: false` asks for a connection of its own. It + * still calls the module's `request` at send time. */ export async function loadNodeHttpRequester( - protocol: string, - credential?: 'direct', + url: URL, + credential?: { subject: string }, ): Promise { - if (protocol === 'https:') return (await import('node:https')).default; + if (credential) { + const rule = await import('@agent-device/contracts/credential-transport'); + rule.assertSecureCredentialTransport(url, credential.subject); + } + if (url.protocol === 'https:') return (await import('node:https')).default; const http = (await import('node:http')).default; - if (credential !== 'direct') return http; - const agent = await (await import('../direct-http.ts')).loadDirectHttpAgent(protocol); + if (!credential) return http; + const { loadDirectHttpAgent } = await import('../direct-http.ts'); + const [pooled, fresh] = [await loadDirectHttpAgent(), await loadDirectHttpAgent(true)]; return { request: ((options: RequestOptions, callback?: (res: IncomingMessage) => void) => - http.request({ ...options, agent }, callback)) as NodeHttpRequester['request'], + http.request( + { ...options, agent: options.agent === false ? fresh : pooled }, + callback, + )) as NodeHttpRequester['request'], }; } diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index 99491eca9c..84bcc94a0a 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -179,11 +179,9 @@ export type RevylClient = Readonly<{ export function createRevylClient(options: RevylClientOptions): RevylClient { const backendUrl = resolveRevylBackendUrl(options.backendUrl ?? REVYL_DEFAULT_BACKEND_URL); - // Without an injected `fetch`, plain http (loopback only) goes direct, never through an - // environment proxy. const transmit: RevylTransmit = async (url, init) => { const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); - return await fetchWithCredential(url, init, options.fetch); + return await fetchWithCredential(url, init, { subject: 'Revyl URL', send: options.fetch }); }; const baseHeaders = { Authorization: `Bearer ${options.apiKey}`, @@ -309,7 +307,8 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { }); }, async uploadSessionArtifact(uploadUrl, file, contentType, signal) { - // Revyl chooses this URL, and its signature is the credential. + // 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' } = { diff --git a/packages/proxy/README.md b/packages/proxy/README.md index d273107b5c..9fadbf31f1 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -167,8 +167,9 @@ resent. `/health` refuses such an answer too: the proxy then answers `/health` w `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`. On `/rpc`, `details.reason` is `proxy_upstream_userinfo` for a username or -password, and `insecure_credential_transport` otherwise. +`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 diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index 4e9d1e571e..72f7e2918e 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -2,6 +2,7 @@ // loopback, whatever transport carries it, and not to wherever an upstream redirect points. import { afterEach, expect, test, vi } from 'vitest'; +import dns from 'node:dns'; import http from 'node:http'; import https from 'node:https'; import type { AddressInfo } from 'node:net'; @@ -93,12 +94,24 @@ test.each([ 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/); + 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([]); }, @@ -274,3 +287,38 @@ test.each([ expect(response.status).toBe(500); expect(await response.json()).toMatchObject({ ok: false, code: 'COMMAND_FAILED' }); }); + +test('a default upstream on a localhost that resolves off loopback receives nothing', async () => { + const reached: string[] = []; + const daemon = await serve((req, res) => { + reached.push(`${req.method} ${req.url}`); + res.end('{}'); + }); + // `0.0.0.0` reaches this machine's listener and is not a loopback address. + vi.spyOn(dns, 'lookup').mockImplementation((( + _hostname: string, + options: dns.LookupOptions, + callback: (...answer: unknown[]) => void, + ) => { + if (options.all) callback(null, [{ address: '0.0.0.0', family: 4 }]); + else callback(null, '0.0.0.0', 4); + }) as typeof dns.lookup); + const proxy = createDaemonProxy({ + upstreamBaseUrl: daemon.replace('127.0.0.1', 'localhost'), + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + }); + + for (const request of [ + new Request('https://gateway.example.test/agent-device/health'), + new Request('https://gateway.example.test/agent-device/artifacts/build', { + headers: { authorization: 'Bearer client-secret' }, + }), + ]) { + const response = await proxy.handle(request); + expect(await response.json(), request.url).toMatchObject({ + reason: 'insecure_credential_transport', + }); + } + expect(reached).toEqual([]); +}); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index a72f341ea3..38ad92df79 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -449,7 +449,6 @@ 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`. @@ -587,10 +586,10 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti const customUpstreamFetch = options.upstreamFetch; const upstreamFetch: DaemonProxyUpstreamFetch = customUpstreamFetch ?? - (async (request) => - new URL(request.url).protocol === 'http:' - ? await (await import('@agent-device/host-kit/direct-http')).fetchOverDirectHttp(request) - : await fetch(request)); + (async (request) => { + const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); + return await fetchWithCredential(request, {}, { subject: 'Proxy upstreamBaseUrl' }); + }); return { upstreamBaseUrl, publicOrigin: @@ -966,12 +965,14 @@ async function proxyErrorResponse(error: unknown, request: Request): Promise; -const NULL_BODY_STATUSES = new Set([204, 205, 304]); /** Forwards one exchange over `node:http(s)`, without redirects or retries; plain http goes direct. */ export function createNodeTransferFetch(): (request: Request) => Promise { @@ -142,7 +141,10 @@ async function exchangeOverNodeHttp( ): Promise { const url = new URL(request.url); const [transport, { urlToHttpOptions }] = await untilAborted(exchange.signal, () => - Promise.all([loadNodeHttpRequester(url.protocol, 'direct'), import('node:url')]), + Promise.all([ + loadNodeHttpRequester(url, { subject: 'Proxy upstreamBaseUrl' }), + import('node:url'), + ]), ); exchange.signal.throwIfAborted(); const { auth: _auth, ...target } = urlToHttpOptions(url); diff --git a/packages/proxy/src/upstream-admission.ts b/packages/proxy/src/upstream-admission.ts index 8e3877da3d..4d0dfc7114 100644 --- a/packages/proxy/src/upstream-admission.ts +++ b/packages/proxy/src/upstream-admission.ts @@ -1,4 +1,7 @@ -import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; +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 @@ -27,3 +30,15 @@ export function assertAdmittedUpstream(upstreamBaseUrl: string): void { }, ); } + +/** + * 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..a99a8de7df --- /dev/null +++ b/packages/react-native/src/companion/client-companion-local-relay.ts @@ -0,0 +1,75 @@ +import net from 'node:net'; +import { isSecureCredentialDestination } from '@agent-device/contracts/credential-transport'; +import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; +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, +// and the sockets it opens itself. + +/** 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: a path on the local base's origin, and nothing else. */ +export function relayTarget(localBaseUrl: string, requestPath: string): URL { + const base = new URL(`${normalizeBaseUrl(localBaseUrl)}/`); + const target = URL.parse(requestPath, base); + if (URL.canParse(requestPath) || 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 request the bridge relays to the local dev server. One that carries a credential, or + * goes where a credential may, goes through `fetchWithCredential`: every URL checked, loopback + * direct, redirects on the same origin only. Any other uses global `fetch`. + */ +export async function fetchRelayedRequest(target: URL, init: RequestInit): Promise { + const headers = new Headers(init.headers); + const credentialed = CREDENTIAL_HEADERS.some((name) => headers.has(name)); + if (!credentialed && !isSecureCredentialDestination(target)) return await fetch(target, init); + const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); + return await fetchWithCredential(target, init, { subject: 'Metro companion local base URL' }); +} + +/** + * Opens the companion's sockets. A plain socket to loopback connects directly, because the global + * `WebSocket` hands its URL to an environment proxy, and to `localhost` only at a loopback address. + * Every other socket is the global `WebSocket`. + */ +export async function createCompanionSocketDialer() { + const [{ Agent, WebSocket: DirectWebSocket }, { lookupLoopbackOnly }] = await Promise.all([ + import('undici'), + import('@agent-device/host-kit/direct-http'), + ]); + const agent = new Agent({ connect: { lookup: lookupLoopbackOnly } }); + const plainLoopback = (url: URL) => + (url.protocol === 'ws:' || url.protocol === 'http:') && isLoopbackHostname(url.hostname); + return { + /** Refuses a name that resolves off this machine here, where the refusal stays typed. */ + async verify(url: string): Promise { + const destination = new URL(url); + const host = destination.hostname.replace(/^\[(.*)\]$/, '$1'); + if (!plainLoopback(destination) || net.isIP(host)) return; + await new Promise((resolve, reject) => { + lookupLoopbackOnly(host, { all: true }, (error) => (error ? reject(error) : resolve())); + }); + }, + open(url: string): WebSocket { + if (!plainLoopback(new URL(url))) return new WebSocket(url); + return new DirectWebSocket(url, { dispatcher: agent }) as unknown as WebSocket; + }, + close: async (): Promise => await agent.destroy(), + }; +} + +export type CompanionSocketDialer = Awaited>; 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 index 3cf34b48a6..3e0bbe6ac9 100644 --- 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 @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; +import dns from 'node:dns'; import { once } from 'node:events'; import fs from 'node:fs'; import http from 'node:http'; @@ -10,6 +11,7 @@ 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, @@ -21,7 +23,11 @@ import { ENV_COMPANION_TUNNEL_SERVER_BASE_URL, METRO_COMPANION_RUN_ARG, } from './client-companion-tunnel-contract.ts'; -import { acceptWebSocketUpgrade } from './client-companion-tunnel-worker.fixtures.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'; @@ -34,15 +40,15 @@ afterEach(async () => { vi.restoreAllMocks(); }); -/** Runs the worker in process; `done` resolves when it exits, and `stop` ends its lease first. */ -function startWorker(serverBaseUrl: string) { +/** 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: 'http://127.0.0.1:1', + localBaseUrl, registerPath: REGISTER_PATH, unregisterPath: UNREGISTER_PATH, bridgeScope: { tenantId: 'tenant-1', runId: 'run-1', leaseId: 'lease-1' }, @@ -52,7 +58,7 @@ function startWorker(serverBaseUrl: string) { ); const stop = async () => { fs.rmSync(statePath, { force: true }); - await done; + await done.catch(() => undefined); }; cleanupTasks.push(stop); return { done, stop }; @@ -66,28 +72,45 @@ function tolerateReset(socket: Duplex): void { socket.on('error', () => undefined); } -/** A loopback bridge whose registration answers `wsUrl(port)`, recording what reaches it. */ -async function listenBridge(wsUrl: (port: number) => string) { +/** + * A loopback bridge whose registration answers `wsUrl(port)`, recording what reaches it and what + * the companion sends on the socket. `moved` redirects each registration path once. + */ +async function listenBridge(wsUrl: (port: number) => string, moved = false) { 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(); + if (moved && !req.url!.endsWith('/moved')) { + res.writeHead(307, { location: `${req.url}/moved` }).end(); + return; + } 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)) upgrade(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); - return { origin: `http://127.0.0.1:${port}`, received, upgraded }; + /** 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`; @@ -107,7 +130,7 @@ test.for(['http://bridge.invalid', 'http:', 'https://', 'https:'])( throw new Error('nothing may be sent'); }) as typeof http.request); - await startWorker(serverBaseUrl).done; + await assert.rejects(startWorker(serverBaseUrl).done, isCredentialTransportRefusal); assert.deepEqual(sent, []); }, @@ -150,30 +173,14 @@ test.for([ const sink = await listenSink(); const bridge = await listenBridge(() => wsUrl(sink.port)); - await startWorker(bridge.origin).done; + await assert.rejects(startWorker(bridge.origin).done, isCredentialTransportRefusal); assert.deepEqual(sink.connections, []); assert.deepEqual(bridge.received, [registered, unregistered]); }); -test('the worker opens a loopback socket around an environment proxy', async () => { - const proxied: string[] = []; - const proxy = http.createServer((req, res) => { - proxied.push(`${req.method} ${req.url}`); - res.writeHead(502).end(); - }); - for (const event of ['upgrade', 'connect'] as const) { - proxy.on(event, (req: http.IncomingMessage, socket: Duplex) => { - tolerateReset(socket); - proxied.push(`${event} ${req.url}`); - socket.destroy(); - }); - } - cleanupTasks.push(() => closeLoopbackServer(proxy)); - const proxyUrl = `http://127.0.0.1:${await listenOnLoopback(proxy)}`; - const bridge = await listenBridge((port) => `ws://127.0.0.1:${port}/bridge?ticket=secret`); - - // Node reads `NODE_USE_ENV_PROXY` at startup, so this worker runs as its own process. +/** Runs the worker as its own process against `origin`, with `env` over this one's. */ +function spawnWorker(origin: string, env: NodeJS.ProcessEnv = {}) { const child = spawn( process.execPath, [ @@ -184,18 +191,14 @@ test('the worker opens a loopback socket around an environment proxy', async () { env: { ...process.env, - [ENV_COMPANION_TUNNEL_SERVER_BASE_URL]: bridge.origin, + [ENV_COMPANION_TUNNEL_SERVER_BASE_URL]: 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', - NODE_USE_ENV_PROXY: '1', - HTTP_PROXY: proxyUrl, - http_proxy: proxyUrl, - NO_PROXY: '', - no_proxy: '', + ...env, }, stdio: 'ignore', }, @@ -205,6 +208,34 @@ test('the worker opens a loopback socket around an environment proxy', async () child.kill('SIGKILL'); await exited; }); + return exited; +} + +test('the worker opens a loopback socket around an environment proxy', async () => { + const proxied: string[] = []; + const proxy = http.createServer((req, res) => { + proxied.push(`${req.method} ${req.url}`); + res.writeHead(502).end(); + }); + for (const event of ['upgrade', 'connect'] as const) { + proxy.on(event, (req: http.IncomingMessage, socket: Duplex) => { + tolerateReset(socket); + proxied.push(`${event} ${req.url}`); + socket.destroy(); + }); + } + cleanupTasks.push(() => closeLoopbackServer(proxy)); + const proxyUrl = `http://127.0.0.1:${await listenOnLoopback(proxy)}`; + const bridge = await listenBridge((port) => `ws://127.0.0.1:${port}/bridge?ticket=secret`); + + // Node reads `NODE_USE_ENV_PROXY` at startup, so this worker runs as its own process. + const exited = spawnWorker(bridge.origin, { + NODE_USE_ENV_PROXY: '1', + HTTP_PROXY: proxyUrl, + http_proxy: proxyUrl, + NO_PROXY: '', + no_proxy: '', + }); await Promise.race([ bridge.upgraded, @@ -214,3 +245,118 @@ test('the worker opens a loopback socket around an environment proxy', async () assert.deepEqual(bridge.received, [registered, 'UPGRADE /bridge?ticket=secret']); assert.deepEqual(proxied, []); }); + +test('a refused socket URL ends the worker process as failed', async () => { + const bridge = await listenBridge(() => 'ws://0.0.0.0:1/bridge'); + + const [exitCode] = await spawnWorker(bridge.origin); + + assert.equal(exitCode, 1); + assert.deepEqual(bridge.received, [registered]); +}); + +test('a bridge socket on a localhost that resolves off loopback never opens', async () => { + const bridge = await listenBridge((port) => `ws://localhost:${port}/bridge?ticket=secret`); + // `0.0.0.0` reaches this machine's listener and is not a loopback address. + vi.spyOn(dns, 'lookup').mockImplementation((( + _hostname: string, + options: dns.LookupOptions, + callback: (...answer: unknown[]) => void, + ) => { + if (options.all) callback(null, [{ address: '0.0.0.0', family: 4 }]); + else callback(null, '0.0.0.0', 4); + }) as typeof dns.lookup); + + await assert.rejects(startWorker(bridge.origin).done, isCredentialTransportRefusal); + + assert.deepEqual(bridge.received, [registered, unregistered]); +}); + +test('registration and unregistration follow a same-origin redirect with the token', async () => { + const bridge = await listenBridge((port) => `ws://127.0.0.1:${port}/bridge`, true); + const worker = startWorker(bridge.origin); + + (await bridge.upgraded).destroy(); + await worker.stop(); + + for (const path of [REGISTER_PATH, UNREGISTER_PATH]) { + assert.ok(bridge.received.includes(`${path}/moved Bearer test-token`), `${bridge.received}`); + } +}); + +/** A server recording the credential headers of each request that reaches it. */ +async function listenLocalServer(location?: () => string) { + const received: string[] = []; + const server = http.createServer((req, res) => { + received.push(`${req.url} ${req.headers.authorization ?? req.headers.cookie ?? '-'}`); + req.resume(); + if (location && req.url === '/redirect') 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.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('a relayed credential reaches loopback directly and stays on its origin', async () => { + const other = await listenLocalServer(); + const local = await listenLocalServer(() => `http://0.0.0.0:${other.port}/redirected`); + const bridge = await relayingBridge(local.origin); + const proxied = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); + + const direct = await bridge.relay(httpRequest('/secret', { cookie: 'session=app' })); + const redirected = await bridge.relay(httpRequest('/redirect', { cookie: 'session=app' })); + + assert.equal(direct.status, 200); + assert.equal(redirected.status, 307); + assert.deepEqual(local.received, ['/secret session=app', '/redirect session=app']); + assert.deepEqual(other.received, []); + assert.equal(proxied.mock.calls.length, 0); +}); 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 952e5b6b9d..a8d1be5b8f 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.ts @@ -26,9 +26,17 @@ import { normalizeBaseUrl } from '../metro/base-url.ts'; import { assertSecureCredentialSocket, assertSecureCredentialTransport, + isCredentialTransportRefusal, } from '@agent-device/contracts/credential-transport'; +import { + createCompanionSocketDialer, + fetchRelayedRequest, + relayTarget, + type CompanionSocketDialer, +} 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 = { @@ -89,12 +97,16 @@ async function registerCompanion( const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); let response: Response; try { - response = await fetchWithCredential(registerUrl, { - method: 'POST', - headers: createHeaders(options.serverBaseUrl, options.bearerToken), - body: JSON.stringify(buildCompanionPayload(options)), - signal: AbortSignal.timeout(COMPANION_REGISTER_TIMEOUT_MS), - }); + response = await fetchWithCredential( + registerUrl, + { + method: 'POST', + headers: createHeaders(options.serverBaseUrl, options.bearerToken), + body: JSON.stringify(buildCompanionPayload(options)), + signal: AbortSignal.timeout(COMPANION_REGISTER_TIMEOUT_MS), + }, + { subject: BRIDGE_URL_SUBJECT }, + ); } catch (error) { if (error instanceof Error && error.name === 'TimeoutError') { throw new Error( @@ -166,43 +178,23 @@ function clampRetryDelay(delayMs: number): number { } /** - * The final URL a bearer request goes to, or a refusal no retry can fix. The base must be a URL - * with a host on its own: appending a path can give one to a base without it (`https://` becomes - * `https://api/...`). + * 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): string { - return refuseWithoutRetry(() => { - assertSecureCredentialTransport(serverBaseUrl, 'Metro companion bridge URL'); - const url = `${normalizeBaseUrl(serverBaseUrl)}${path}`; - assertSecureCredentialTransport(url, 'Metro companion bridge URL'); - return url; - }); + assertSecureCredentialTransport(serverBaseUrl, BRIDGE_URL_SUBJECT); + return `${normalizeBaseUrl(serverBaseUrl)}${path}`; } /** - * Prepares the bridge socket. The registered URL is what admits this companion to the bridge, so it - * follows the credential transport rule: `wss`, or `ws` to loopback. A `ws` socket connects - * directly, because the global `WebSocket` hands its URL to an environment proxy. + * 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. */ -async function prepareBridgeSocket(wsUrl: string): Promise<() => WebSocket> { - const destination = refuseWithoutRetry(() => - assertSecureCredentialSocket(wsUrl, 'Metro companion bridge socket URL'), - ); - if (destination.protocol === 'wss:') return () => new WebSocket(wsUrl); - const { Agent, WebSocket: DirectWebSocket } = await import('undici'); - return () => new DirectWebSocket(wsUrl, { dispatcher: new Agent() }) as unknown as WebSocket; -} - -/** Runs a transport check as part of registration: its refusal is one no retry can fix. */ -function refuseWithoutRetry(check: () => T): T { - try { - return check(); - } catch (error) { - throw new CompanionRegistrationError( - error instanceof Error ? error.message : String(error), - false, - ); - } +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 { @@ -215,12 +207,16 @@ async function unregisterCompanion(options: CompanionTunnelWorkerOptions): Promi try { const unregisterUrl = bearerDestination(options.serverBaseUrl, unregisterPath); const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); - await fetchWithCredential(unregisterUrl, { - method: 'POST', - headers: createHeaders(options.serverBaseUrl, options.bearerToken), - body: JSON.stringify(buildCompanionPayload(options)), - signal: AbortSignal.timeout(2_000), - }); + await fetchWithCredential( + unregisterUrl, + { + method: 'POST', + headers: createHeaders(options.serverBaseUrl, options.bearerToken), + body: JSON.stringify(buildCompanionPayload(options)), + signal: AbortSignal.timeout(2_000), + }, + { subject: BRIDGE_URL_SUBJECT }, + ); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); } @@ -244,7 +240,7 @@ 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', @@ -361,8 +354,22 @@ async function handleBridgeWebSocketOpen( message: Extract, options: CompanionTunnelWorkerOptions, upstreamSockets: Map, + dialer: CompanionSocketDialer, ): 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 = dialer.open(toUpstreamWebSocketUrl(options.localBaseUrl, message.path)); + } catch (error) { + refuse(error); + return; + } upstreamSocket.binaryType = 'arraybuffer'; let opened = false; upstreamSocket.addEventListener('message', (event) => { @@ -411,12 +418,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); } } @@ -445,6 +447,7 @@ async function handleBridgeMessage( message: MetroCompanionRequest, options: CompanionTunnelWorkerOptions, upstreamSockets: Map, + dialer: CompanionSocketDialer, ): Promise { switch (message.type) { case 'ping': { @@ -456,7 +459,7 @@ async function handleBridgeMessage( return; } case 'ws-open': { - await handleBridgeWebSocketOpen(bridgeSocket, message, options, upstreamSockets); + await handleBridgeWebSocketOpen(bridgeSocket, message, options, upstreamSockets, dialer); return; } case 'ws-frame': { @@ -524,6 +527,7 @@ export async function runCompanionTunnelWorker( }, runtime.leaseCheckIntervalMs ?? COMPANION_TUNNEL_LEASE_CHECK_INTERVAL_MS); lifetimeHandle.unref(); let registerRetryDelayMs = runtime.reconnectDelayMs ?? COMPANION_TUNNEL_RECONNECT_DELAY_MS; + const dialer = await createCompanionSocketDialer(); try { while (!shutdownRequested && shouldKeepWorkerRunning(options)) { let registered = false; @@ -534,13 +538,15 @@ export async function runCompanionTunnelWorker( registerRetryDelayMs = runtime.reconnectDelayMs ?? COMPANION_TUNNEL_RECONNECT_DELAY_MS; registered = true; activeRegistrationComplete = true; - const connectBridge = await prepareBridgeSocket(registration.wsUrl); + // The registered URL is what admits this companion to the bridge. + assertSecureCredentialSocket(registration.wsUrl, 'Metro companion bridge socket URL'); + await dialer.verify(registration.wsUrl); if (shutdownRequested || !shouldKeepWorkerRunning(options)) { await unregisterActiveRegistration(); registered = false; break; } - const bridgeSocket = connectBridge(); + const bridgeSocket = dialer.open(registration.wsUrl); activeBridgeSocket = bridgeSocket; bridgeSocket.binaryType = 'arraybuffer'; try { @@ -548,7 +554,7 @@ export async function runCompanionTunnelWorker( bridgeSocket.addEventListener('message', (event) => { void (async () => { const message = await parseBridgeMessage(event); - await handleBridgeMessage(bridgeSocket, message, options, upstreamSockets); + await handleBridgeMessage(bridgeSocket, message, options, upstreamSockets, dialer); })().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); }); @@ -574,12 +580,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; @@ -596,6 +601,7 @@ export async function runCompanionTunnelWorker( process.off('SIGTERM', requestShutdown); process.off('SIGINT', requestShutdown); } + await dialer.close(); } } 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 15591ed40f..d5c7d5c5fd 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 @@ -562,9 +562,19 @@ test('a loopback bridge gets the bearer token directly, never through global fet ); const received: string[] = []; const bridge = http.createServer((req, res) => { - received.push(`${req.method} ${req.url} ${req.headers.authorization}`); - req.resume(); - res.writeHead(401).end('{"ok":false}'); + let body = ''; + req.on('data', (chunk) => (body += String(chunk))); + req.on('end', () => { + received.push( + `${req.method} ${req.url} ${req.headers.authorization} ${JSON.parse(body).tenantId}`, + ); + // The bridge moved its route: the POST follows on the same origin, with body and bearer. + if (req.url === '/api/metro/bridge') { + res.writeHead(307, { location: '/api/metro/bridge/v2' }).end(); + return; + } + res.writeHead(401).end('{"ok":false}'); + }); }); await new Promise((resolve) => bridge.listen(0, '127.0.0.1', resolve)); // The dev server probe carries no credential and stays on global fetch. @@ -589,7 +599,10 @@ test('a loopback bridge gets the bearer token directly, never through global fet ), ); - assert.deepEqual(received, ['POST /api/metro/bridge Bearer shared-token']); + assert.deepEqual(received, [ + 'POST /api/metro/bridge Bearer shared-token tenant-1', + 'POST /api/metro/bridge/v2 Bearer shared-token tenant-1', + ]); assert.equal(JSON.stringify(fetchMock.mock.calls).includes('shared-token'), false); } finally { vi.unstubAllGlobals(); diff --git a/packages/react-native/src/metro/client-metro.ts b/packages/react-native/src/metro/client-metro.ts index 92c6db153f..382a8bec9b 100644 --- a/packages/react-native/src/metro/client-metro.ts +++ b/packages/react-native/src/metro/client-metro.ts @@ -21,7 +21,10 @@ 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 { + assertSecureCredentialTransport, + isCredentialTransportRefusal, +} from '@agent-device/contracts/credential-transport'; import { ensureMetroCompanion } from '../companion/client-metro-companion.ts'; import type { MetroBridgeDescriptor, @@ -454,24 +457,27 @@ function isRetryableBridgeError(error: unknown): boolean { } async function configureMetroBridge(input: ProxyBridgeRequestOptions): Promise { - // Checked on the final URL, right before the bearer token is sent, and outside the retry. const bridgeUrl = `${input.baseUrl}/api/metro/bridge`; - assertSecureCredentialTransport(bridgeUrl, 'Metro bridge URL'); const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); let response: Response; try { - response = await fetchWithCredential(bridgeUrl, { - method: 'POST', - headers: createProxyHeaders(input.baseUrl, input.bearerToken), - body: JSON.stringify({ - ...input.scope, - ...(input.runtime ? { ios_runtime: input.runtime } : {}), - timeout_ms: input.timeoutMs, - }), - signal: AbortSignal.timeout(input.timeoutMs), - }); + response = await fetchWithCredential( + bridgeUrl, + { + method: 'POST', + headers: createProxyHeaders(input.baseUrl, input.bearerToken), + body: JSON.stringify({ + ...input.scope, + ...(input.runtime ? { ios_runtime: input.runtime } : {}), + timeout_ms: input.timeoutMs, + }), + signal: AbortSignal.timeout(input.timeoutMs), + }, + { subject: 'Metro bridge URL' }, + ); } catch (error) { + if (isCredentialTransportRefusal(error)) throw error; if (error instanceof Error && error.name === 'TimeoutError') { throw createMetroBridgeRequestError( `/api/metro/bridge timed out after ${input.timeoutMs}ms calling ${input.baseUrl}/api/metro/bridge`, diff --git a/packages/remote/src/__tests__/upload-client-cancellation.test.ts b/packages/remote/src/__tests__/upload-client-cancellation.test.ts index 22b9950881..3d8ae5c3db 100644 --- a/packages/remote/src/__tests__/upload-client-cancellation.test.ts +++ b/packages/remote/src/__tests__/upload-client-cancellation.test.ts @@ -18,19 +18,18 @@ import { uploadArtifact } from '../upload-client.ts'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { observeOutcome } from './support/upload-transfer-fixtures.ts'; -// Control requests to a plain-http (loopback) daemon go direct over `node:http`, never through an -// environment proxy, so that send is the control-plane seam these cases replace. +// Control requests send the daemon token through the credential primitive, so that send is the +// control-plane seam these cases replace. const directHttp = vi.hoisted(() => ({ send: undefined as ((request: Request) => Promise) | undefined, })); vi.mock('@agent-device/host-kit/direct-http', async (importOriginal) => { const actual = await importOriginal(); - return { - ...actual, - fetchOverDirectHttp: vi.fn(async (request: Request) => - directHttp.send ? await directHttp.send(request) : await actual.fetchOverDirectHttp(request), - ), - }; + const fetchWithCredential: typeof actual.fetchWithCredential = async (input, init, options) => + directHttp.send + ? await directHttp.send(new Request(input, init)) + : await actual.fetchWithCredential(input, init, options); + return { ...actual, fetchWithCredential: vi.fn(fetchWithCredential) }; }); const TEST_TOKEN = 'agent-device-upload-cancel-token'; diff --git a/packages/remote/src/artifact-download.ts b/packages/remote/src/artifact-download.ts index 864c9b2d83..3e41f13fed 100644 --- a/packages/remote/src/artifact-download.ts +++ b/packages/remote/src/artifact-download.ts @@ -159,7 +159,9 @@ async function requestRemoteArtifact( materialize(res: http.IncomingMessage, signal: AbortSignal): Promise; }, ): Promise { - const transport = await loadNodeHttpRequester(params.artifactUrl.protocol, 'direct'); + const transport = await loadNodeHttpRequester(params.artifactUrl, { + subject: 'Artifact download URL', + }); await destination.prepare(); return await new Promise((resolve, reject) => { let settled = false; diff --git a/packages/remote/src/remote-request-diagnostics.ts b/packages/remote/src/remote-request-diagnostics.ts index 8bd6434bce..29d2b25ceb 100644 --- a/packages/remote/src/remote-request-diagnostics.ts +++ b/packages/remote/src/remote-request-diagnostics.ts @@ -146,7 +146,7 @@ async function fetchRemoteRequestDiagnostics(params: { return 'daemon base URL is not a valid URL'; } try { - const transport = await loadNodeHttpRequester(url.protocol, 'direct'); + const transport = await loadNodeHttpRequester(url, { subject: 'Remote daemon base URL' }); await fs.promises.mkdir(path.dirname(destinationPath), { recursive: true }); return await new Promise((resolve) => { let settled = false; diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index 764d59724f..8e1290be2b 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -338,17 +338,13 @@ async function requestUploadControl( watchdog.signal.throwIfAborted(); watchdog.arm(phase, UPLOAD_CONTROL_PLANE_TIMEOUT_MS); try { - // Redirects could forward the daemon token, so these control requests never follow them. Plain - // http (loopback only) goes direct, never through an environment proxy. - const request = new Request(url, { - ...init, - method: 'POST', - redirect: 'error', - signal: watchdog.signal, - }); - const response = await (url.protocol === 'http:' - ? (await import('@agent-device/host-kit/direct-http')).fetchOverDirectHttp(request) - : fetch(request)); + const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); + // Redirects could forward the daemon token, so these control requests never follow them. + const response = await fetchWithCredential( + url, + { ...init, method: 'POST', redirect: 'error', signal: watchdog.signal }, + { subject: 'Upload URL' }, + ); const body: unknown = response.ok ? await response.json().catch(() => undefined) : undefined; watchdog.signal.throwIfAborted(); return { response, body }; diff --git a/packages/remote/src/upload-stream.ts b/packages/remote/src/upload-stream.ts index 27baa30408..04bfcc102a 100644 --- a/packages/remote/src/upload-stream.ts +++ b/packages/remote/src/upload-stream.ts @@ -108,7 +108,7 @@ async function streamFileToHttpRequestAttempt(options: { // This module sits in the CLI's eager import closure via the remote-artifact // upload client, but only a remote daemon ever uploads, so the HTTP stack // loads here rather than at import time. - const transport = await loadNodeHttpRequester(options.url.protocol, 'direct'); + const transport = await loadNodeHttpRequester(options.url, { subject: 'Upload URL' }); const payloadSize = fs.statSync(options.payloadPath).size; const headers = buildUploadRequestHeaders(options.headers, options.startOffset, payloadSize); emitUploadAttemptStarted(options.progress, options.startOffset, payloadSize); @@ -151,6 +151,8 @@ async function streamFileToHttpRequestAttempt(options: { req.on('error', (err) => { if (phases.responseStarted) return; + // A typed refusal says why nothing was sent. + if (err instanceof AppError) return fail(err); fail( new AppError( 'COMMAND_FAILED', diff --git a/src/cli/cloud-auth-request.ts b/src/cli/cloud-auth-request.ts index 0173f7968a..a0eee1cf5f 100644 --- a/src/cli/cloud-auth-request.ts +++ b/src/cli/cloud-auth-request.ts @@ -1,12 +1,7 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; -import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { readCloudJsonResponse } from './cloud-response.ts'; const HTTP_TIMEOUT_MS = 15_000; -const MAX_CLOUD_AUTH_REDIRECTS = 3; -const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); -// Fetch turns a POST into a GET without a body on these. A 307 or 308 keeps the method and body. -const GET_REDIRECT_STATUSES = new Set([301, 302, 303]); const CLOUD_AUTH_REQUEST_REASONS = { // A cloud auth request got a redirect it does not follow: to another origin, past the third hop, @@ -50,62 +45,46 @@ export async function postCloudAuthJson(options: { * Sends one credential-bearing cloud request and returns the final answer. The URL must be https, * or plain http to loopback. A redirect is followed only to the same origin, at most three times, * and never to a target with a username or password. A 301, 302 or 303 turns a POST into a GET - * without its body or headers; a GET keeps its headers on the same origin. + * without its body; a GET keeps its headers on the same origin. */ export async function fetchCloudOnOneOrigin( requestUrl: URL, request: RequestInit, - // di-seam-approved: the same fetch-global seam as postCloudAuthJson's fetchImpl. Without it, - // plain http (loopback only) goes direct, never through an environment proxy. + // di-seam-approved: the same fetch-global seam as postCloudAuthJson's fetchImpl. fetchImpl?: typeof fetch, ): Promise { - assertSecureCredentialTransport(requestUrl, 'Cloud base URL'); - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); - // One timeout covers the whole redirect chain. - const signal = AbortSignal.timeout(HTTP_TIMEOUT_MS); - let url = requestUrl; - let init = request; - for (let redirects = 0; ; redirects += 1) { - const response = await fetchWithCredential( - url, - { ...init, redirect: 'manual', signal }, - fetchImpl, - ); - if (!REDIRECT_STATUSES.has(response.status)) return response; - await response.body?.cancel().catch(() => undefined); - url = readRedirectTarget(response, url, requestUrl, redirects); - if (GET_REDIRECT_STATUSES.has(response.status) && init.method !== 'GET') { - init = { method: 'GET' }; - } - } + const { fetchWithCredential, isRedirectStatus } = + await import('@agent-device/host-kit/direct-http'); + const response = await fetchWithCredential( + requestUrl, + // One timeout covers the whole redirect chain. + { ...request, signal: AbortSignal.timeout(HTTP_TIMEOUT_MS) }, + { subject: 'Cloud base URL', send: fetchImpl }, + ); + if (!isRedirectStatus(response.status)) return response; + await response.body?.cancel().catch(() => undefined); + throw redirectRefused(response, requestUrl); } -function readRedirectTarget( - response: Response, - current: URL, - requestUrl: URL, - redirects: number, -): URL { +/** Why a redirect the send did not follow ends the request. */ +function redirectRefused(response: Response, requestUrl: URL): AppError { const location = response.headers.get('location'); - const target = location === null ? null : URL.parse(location, current); - const refusal = describeRefusedRedirect(target, requestUrl, redirects); - if (target && !refusal) return target; - throw new AppError('COMMAND_FAILED', `Cloud auth endpoint answered with ${refusal}.`, { - reason: CLOUD_AUTH_REQUEST_REASONS.redirectRefused.reason, - status: response.status, - hint: `Cloud auth requests stay on ${requestUrl.origin}. Check that it is the cloud API origin.`, - }); + const target = location === null ? null : URL.parse(location, requestUrl); + return new AppError( + 'COMMAND_FAILED', + `Cloud auth endpoint answered with ${describeRefusedRedirect(target, requestUrl)}.`, + { + reason: CLOUD_AUTH_REQUEST_REASONS.redirectRefused.reason, + status: response.status, + hint: `Cloud auth requests stay on ${requestUrl.origin}. Check that it is the cloud API origin.`, + }, + ); } -function describeRefusedRedirect( - target: URL | null, - requestUrl: URL, - redirects: number, -): string | undefined { +function describeRefusedRedirect(target: URL | null, requestUrl: URL): string { if (!target) return 'a redirect that has no readable Location'; // Fetch rejects such a URL with an error that quotes it, and the target can echo a credential. if (target.username || target.password) return 'a redirect to a URL with a username or password'; if (target.origin !== requestUrl.origin) return 'a redirect to another origin'; - if (redirects >= MAX_CLOUD_AUTH_REDIRECTS) return 'more than three redirects'; - return undefined; + return 'more than three redirects'; } diff --git a/src/core/interactors/limrun-ios-files.ts b/src/core/interactors/limrun-ios-files.ts index 146635a23f..0d4d1d2962 100644 --- a/src/core/interactors/limrun-ios-files.ts +++ b/src/core/interactors/limrun-ios-files.ts @@ -9,7 +9,6 @@ import { import type { LimrunRuntimeDependencies } from '@agent-device/provider-limrun'; import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import { downloadLimrunFile } from '../limrun-download-file.ts'; -import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; type Session = Parameters[0]; type Files = AppleToolProvider['simulatorFiles']; @@ -66,7 +65,7 @@ export function createLimrunSimulatorFiles( signal.throwIfAborted(); const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); const response = await fetchWithCredential( - assertSecureCredentialTransport(url, 'Limrun API URL'), + url, { method, headers: { @@ -77,6 +76,7 @@ export function createLimrunSimulatorFiles( signal, redirect: 'error', }, + { subject: 'Limrun API URL' }, ); if (!response.ok) { await response.body?.cancel(); diff --git a/src/core/interactors/limrun-ios-runner-products.ts b/src/core/interactors/limrun-ios-runner-products.ts index 20e5917b7e..c57f28adc4 100644 --- a/src/core/interactors/limrun-ios-runner-products.ts +++ b/src/core/interactors/limrun-ios-runner-products.ts @@ -13,7 +13,6 @@ import { createGzip } from 'node:zlib'; import { extractArchiveSafely } from '@agent-device/host-kit/archive'; import { escapeXmlTextAndAttribute } from '@agent-device/xml'; import { downloadLimrunFile } from '../limrun-download-file.ts'; -import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; /** Stages the version-matched release runner, or an explicitly supplied development build. */ export async function prepareLimrunRunnerProducts(input: { @@ -247,24 +246,26 @@ export async function uploadLimrunRunnerProducts( for (const file of payloads) yield* createReadStream(path.join(directory, file.path), { signal }); } - const syncUrl = `${apiUrl}/sync`; - assertSecureCredentialTransport(syncUrl, 'Limrun API URL'); const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); const stream = createGzip(); const compression = pipeline(Readable.from(body()), stream, { signal }).catch(() => {}); try { - const response = await fetchWithCredential(syncUrl, { - method: 'POST', - headers: { - Authorization: `Bearer ${token}`, - 'Content-Type': 'application/octet-stream', - 'Content-Encoding': 'gzip', - }, - body: Readable.toWeb(stream) as ReadableStream, - duplex: 'half', - signal, - redirect: 'error', - } as RequestInit & { duplex: 'half' }); + const response = await fetchWithCredential( + `${apiUrl}/sync`, + { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/octet-stream', + 'Content-Encoding': 'gzip', + }, + body: Readable.toWeb(stream) as ReadableStream, + duplex: 'half', + signal, + redirect: 'error', + } as RequestInit & { duplex: 'half' }, + { subject: 'Limrun API URL' }, + ); if (!response.ok) { await response.body?.cancel(); throw limrunRunnerError( diff --git a/src/core/interactors/limrun-ios-runner.ts b/src/core/interactors/limrun-ios-runner.ts index ffaff9f175..e7f89c180f 100644 --- a/src/core/interactors/limrun-ios-runner.ts +++ b/src/core/interactors/limrun-ios-runner.ts @@ -168,16 +168,20 @@ export async function createLimrunIosRunner( async () => { runRequested = true; const result = await awaitWithSignal( - fetchWithCredential(`${apiUrl}/xctest/run`, { - method: 'POST', - headers: { ...headers, 'Content-Type': 'application/json' }, - body: JSON.stringify({ - root: path.basename(directory), - xctestrun: 'Runner.xctestrun', - }), - signal, - redirect: 'error', - }), + fetchWithCredential( + `${apiUrl}/xctest/run`, + { + method: 'POST', + headers: { ...headers, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + root: path.basename(directory), + xctestrun: 'Runner.xctestrun', + }), + signal, + redirect: 'error', + }, + { subject: 'Limrun API URL' }, + ), launchSignal, ); if (!result.ok) { diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index caf62153e7..c66fa8aaf3 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -13,7 +13,6 @@ import { assertSecureCredentialTransport } from '@agent-device/contracts/credent const RESPONSE_BODY_PREVIEW_BYTES = 500; const MAX_DOWNLOAD_REDIRECTS = 5; -const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); // 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 @@ -71,18 +70,18 @@ async function fetchDownload( initialHeaders: LimrunFileDownload['headers'], signal: AbortSignal, ): Promise { - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); + const { fetchWithCredential, isRedirectStatus } = + await import('@agent-device/host-kit/direct-http'); let url = from; let headers = initialHeaders; for (let redirects = 0; ; redirects += 1) { - const response = await fetchWithCredential(url.href, { - method: 'GET', - headers, - redirect: 'manual', - signal, - }); + const response = await fetchWithCredential( + url.href, + { method: 'GET', headers, redirect: 'manual', signal }, + { subject: 'Limrun download URL' }, + ); const location = response.headers.get('location'); - if (!REDIRECT_STATUSES.has(response.status) || location === null) return response; + if (!isRedirectStatus(response.status) || location === null) return response; await response.body?.cancel().catch(() => undefined); const target = URL.parse(location, url); if (!target || !isFollowedRedirect(url, target) || redirects >= MAX_DOWNLOAD_REDIRECTS) { @@ -92,7 +91,7 @@ async function fetchDownload( }); } if (target.origin !== url.origin) headers = {}; - url = assertSecureCredentialTransport(target, 'Limrun download URL'); + url = target; } } diff --git a/test/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts b/test/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts index a4bf1c9ab9..5ff42dc42a 100644 --- a/test/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts +++ b/test/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts @@ -109,7 +109,7 @@ test('Provider-backed integration local proxy serves the daemon diagnostics reco // The token travels over plain http to loopback, so the request takes the direct agent that // never routes through an environment proxy. assert.deepEqual(directOptions, { - agent: await loadDirectHttpAgent('http:'), + agent: await loadDirectHttpAgent(), protocol: 'http:', host: '127.0.0.1', port: String(daemon.httpPort), diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index b6a248e55d..35e479f4e9 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,7 +71,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealth": "sha256:1ff542dadff6d92233c464b7d09052d809f36186bb60acdb572c48bfc1eb5c1f", "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealthLink": "sha256:96a79a8ff5a078916ee7bffed1d9624d0ba9c0dcbd8e2c55f9abf37fccfef744", "packages/daemon-client/src/daemon-client-transport.ts#isHealthService": "sha256:ffd2c774e0efca5e5d2b01f9d37fe9b76aaf5e7569e07d9208fe667473771c10", - "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth": "sha256:f5c01ec3975732318ac1e682b84d75fb9398d109b85302bf5ba189d98dfbf8ab", + "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth": "sha256:a22237c62f5f413c0c1f3ec1e3b5603c89e25ed3bb6317d30ececfb4b04506f7", "packages/daemon-client/src/daemon-client-transport.ts#readHealthLink": "sha256:c4f638b4df43f572e105b6f8df578fe90ebf64cb56002e4d029a109bdbc167d1", "packages/daemon-client/src/daemon-client-transport.ts#readHealthPayload": "sha256:4e85ffc3e35e02379c393e9312344757e003cf1f0ad9eb8d1f77d90c81c861f1", "packages/daemon-client/src/daemon-client-transport.ts#readHealthVersion": "sha256:856bd74aa8b2f205b6b30855755f16391015bffc1b6a323f618b51c26e749bfd", @@ -165,7 +165,7 @@ "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint": "sha256:c1d5fe2fe90c425502cf8b7c87d6606374d6af65b4e9faf942a416f683930bdc", "packages/remote/src/remote-request-diagnostics.ts#buildRemoteRequestDiagnosticsUrl": "sha256:30a1a9bf0df24d3564a616699916a3bb4360c2b4d21c4ad0562fb0c1e738d0a9", - "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics": "sha256:75a4e0305576be8ff3be797c6cc7215f1a2df389c208f8b911ae036fe826583d", + "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics": "sha256:a2e04f82f6aca33bad8dc84eaa2581d910a4eb5012bb6b48757d735a9895daed", "packages/remote/src/remote-request-diagnostics.ts#localizeRemoteDaemonError": "sha256:35cfa186ad64663ae4dbb4e102d49238532cd7e3b75e8337edcc3d1fd77f92d5", "packages/remote/src/upload-client-artifact.ts#PreparedUploadArtifact": "sha256:5c40027d47feda3c946e836372b9f08ad866ab1612708b0d506551545f931ea4", "packages/remote/src/upload-client.ts#ARTIFACT_HASH_ALGORITHM": "sha256:328c135ea5f9d89fd2c142b440d5402a61d19f9044bf0504dfc2c525e58c1909", @@ -175,7 +175,7 @@ "packages/remote/src/upload-client.ts#finalizeDirectUpload": "sha256:ca3fa667ab2a60fb8af095bddeacb4875dcd2d12db783585a0fb045db35da212", "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:86e2a092caf2aef3404957eb4abba9dc35ac6e68eea99448085da3c927f24a45", + "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:4b1e2bf81db43907bd61934aafb36090f2f7503f6180d6f21dacd137da6d5f28", "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", @@ -190,7 +190,7 @@ "packages/remote/src/upload-stream.ts#parseNonNegativeIntegerHeader": "sha256:5cbe9c6994459d673d988a51407e65556e28175b187ce0a9d27cbb6331962834", "packages/remote/src/upload-stream.ts#parseUploadResumeOffset": "sha256:297184ea22a6dc1cda9aee17034122ae0ea2f43d0355647f6fcf02f3f4b5ca0e", "packages/remote/src/upload-stream.ts#streamFileToHttpRequest": "sha256:c2b5e1369c8b1c9420036e23163d21e43fa2ac8b889c6a8f028cc6095055a16f", - "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt": "sha256:84beddf7c503a75f8d2f1e124ae94f198233f12e3d4a44518f0ae6c55bb6f69e", + "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt": "sha256:3286664cab72bc809a49e497507fc423c2340250e63bec0bf9d2037db9ad34e1", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_INSTANCE_HEADER": "sha256:d2bb3f4846470188a0fc1724271da0f0bcbdf2337bd6bf331508142cadcb65d8", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER": "sha256:4564c2ce437d30d7a823e3326f4375c0750ba8d42bec22b4d02e8eb7f7db2973", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_INSTANCE_MISMATCH_HEADER": "sha256:a197edaf7f9fa94a6aab269856aa852da3204cc586f5fd23198689eb11908b61", @@ -256,7 +256,7 @@ "packages/remote/src/artifact-download.ts#RemoteArtifactRequest": "sha256:6cce66499f34bb18139917df592e554395936964025089024d6c6f67e4fa4b98", "packages/remote/src/artifact-download.ts#RemoteArtifactFetch": "sha256:e83939ec48a66917df9ec84becf53b6ca3c8115cfdada10731046381ac9e32c1", "packages/remote/src/artifact-download.ts#fetchRemoteArtifactFromUrl": "sha256:de6e71abdc758f760beffba0dc260473f88a8c60b13540b9c14d39f1a3d5e3a1", - "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:bcd2a587fc699de6575feb95576e03e40f969852f77d9ed492ae02d49ea72ffc", + "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:85890c420579d6055b54caa37736c3d7627852f12bc243677a658cdbdf7c0ea7", "packages/daemon-client/src/daemon-client-checked-rpc.ts#isCheckedRpcOutcomeResponse": "sha256:75fb9f3444a3f8f4a762811ba7cbe02d92a39ed4e55483ea0cf7f029e5720a3e", "packages/daemon-client/src/daemon-client-checked-rpc.ts#CheckedRpcOutcome": "sha256:8aa7e58307417460bb54938f6bbbd340254e14ffbbaf2093272996909592f7be", "packages/daemon-client/src/daemon-client-checked-rpc.ts#ReadHealthLink": "sha256:86a9e6f1ebdaecca3ddaa16081c221321c01c684b70197961ecd71a3f54a464f", @@ -464,8 +464,8 @@ }, { "declaration": "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth", - "digest": "sha256:f5c01ec3975732318ac1e682b84d75fb9398d109b85302bf5ba189d98dfbf8ab", - "rationale": "The health-probe budget includes requester loading and response completion. The caller AbortSignal joins the probe timer only in-process; caller cancellation remains distinct from probe expiry. No signal, timedOut flag, request route, auth header or accepted health payload field changes on the wire, so released daemons and proxies parse and respond as before (ADR 0006). #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." + "digest": "sha256:a22237c62f5f413c0c1f3ec1e3b5603c89e25ed3bb6317d30ececfb4b04506f7", + "rationale": "The health-probe budget includes requester loading and response completion. The caller AbortSignal joins the probe timer only in-process; caller cancellation remains distinct from probe expiry. No signal, timedOut flag, request route, auth header or accepted health payload field changes on the wire, so released daemons and proxies parse and respond as before (ADR 0006). #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request. The sender is now loaded with the request URL and applies the credential rule itself: a refused destination, or a localhost that resolves off loopback, ends as a typed refusal before anything is sent. Method, path, headers, and body are unchanged." }, { "declaration": "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint", @@ -474,8 +474,8 @@ }, { "declaration": "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics", - "digest": "sha256:75a4e0305576be8ff3be797c6cc7215f1a2df389c208f8b911ae036fe826583d", - "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." + "digest": "sha256:a2e04f82f6aca33bad8dc84eaa2581d910a4eb5012bb6b48757d735a9895daed", + "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request. The sender is now loaded with the request URL and applies the credential rule itself: a refused destination, or a localhost that resolves off loopback, ends as a typed refusal before anything is sent. Method, path, headers, and body are unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#uploadDirectArtifact", @@ -534,8 +534,8 @@ }, { "declaration": "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt", - "digest": "sha256:84beddf7c503a75f8d2f1e124ae94f198233f12e3d4a44518f0ae6c55bb6f69e", - "rationale": "#4441 keeps each attempt under its sequential phase watchdog and corrects its transport lifecycle: the connect ceiling now ends at actual socket or TLS-handshake establishment, body progress counts only transport writes, and an early response reads the accepted answer to its end, then destroys and joins the owned file/request pipeline and retires this attempt's phase watchdog before resolving or starting the redirect/resume attempt, so a completed hop's timers never reach the next hop. The outgoing-request phase observation now comes from @agent-device/host-kit/transport's observeClientRequestPhases, which listens to the same socket, TLS-handshake and finish events and is removed when the attempt settles. Bytes on the wire are unchanged: same route, method, headers, body framing, resume-offset handling and redirect limit. Only this client's own sequencing and deadlines moved, so a protocol-2 peer parses exactly what it parsed before. Request-body progress is now each non-empty request write that completes without an error, which Node reports once the bytes reach the local kernel, instead of drain, which fires only after a write returned false. The write wrapper passes every argument and the backpressure result through, so the bytes and framing on the wire do not change. That completed-write observer is host-kit's transport owner, which also stops reporting after the response starts, the signal aborts or the request is destroyed; no request changes. The attempt composes that write owner with the phase observer once per request and disposes both when it settles. Duplicate success disposal and abort-reason mapping are consolidated without changing precedence. The sole response-path pipeline join remains before outcome or next hop; URL, method, authentication, payloads and framing remain unchanged. Its two refusal errors now read details.reason from UPLOAD_TRANSFER_REASONS instead of literals in this declaration, so only the identifier expressions moved; the values published are the identical strings and nothing a peer sends or parses moves. #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." + "digest": "sha256:3286664cab72bc809a49e497507fc423c2340250e63bec0bf9d2037db9ad34e1", + "rationale": "#4441 keeps each attempt under its sequential phase watchdog and corrects its transport lifecycle: the connect ceiling now ends at actual socket or TLS-handshake establishment, body progress counts only transport writes, and an early response reads the accepted answer to its end, then destroys and joins the owned file/request pipeline and retires this attempt's phase watchdog before resolving or starting the redirect/resume attempt, so a completed hop's timers never reach the next hop. The outgoing-request phase observation now comes from @agent-device/host-kit/transport's observeClientRequestPhases, which listens to the same socket, TLS-handshake and finish events and is removed when the attempt settles. Bytes on the wire are unchanged: same route, method, headers, body framing, resume-offset handling and redirect limit. Only this client's own sequencing and deadlines moved, so a protocol-2 peer parses exactly what it parsed before. Request-body progress is now each non-empty request write that completes without an error, which Node reports once the bytes reach the local kernel, instead of drain, which fires only after a write returned false. The write wrapper passes every argument and the backpressure result through, so the bytes and framing on the wire do not change. That completed-write observer is host-kit's transport owner, which also stops reporting after the response starts, the signal aborts or the request is destroyed; no request changes. The attempt composes that write owner with the phase observer once per request and disposes both when it settles. Duplicate success disposal and abort-reason mapping are consolidated without changing precedence. The sole response-path pipeline join remains before outcome or next hop; URL, method, authentication, payloads and framing remain unchanged. Its two refusal errors now read details.reason from UPLOAD_TRANSFER_REASONS instead of literals in this declaration, so only the identifier expressions moved; the values published are the identical strings and nothing a peer sends or parses moves. #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request. The sender is now loaded with the request URL and applies the credential rule itself: a refused destination, or a localhost that resolves off loopback, ends as a typed refusal before anything is sent. Method, path, headers, and body are unchanged." }, { "declaration": "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath", @@ -549,8 +549,8 @@ }, { "declaration": "packages/remote/src/upload-client.ts#requestUploadControl", - "digest": "sha256:86e2a092caf2aef3404957eb4abba9dc35ac6e68eea99448085da3c927f24a45", - "rationale": "Lists the shared control Fetch/JSON owner so changes to method, headers, body or redirect forwarding remain wire-gated. Existing preflight/finalize routes and protocol-2 payloads are preserved; the original 30-second ceiling now retains typed local phase expiry and stops later legs. Non-success status handling is unchanged. #5150 sends a plain-http (loopback) control request over node:http with a direct agent instead of global fetch. It still follows no redirect, and method, headers, and JSON body are unchanged." + "digest": "sha256:4b1e2bf81db43907bd61934aafb36090f2f7503f6180d6f21dacd137da6d5f28", + "rationale": "Lists the shared control Fetch/JSON owner so changes to method, headers, body or redirect forwarding remain wire-gated. Existing preflight/finalize routes and protocol-2 payloads are preserved; the original 30-second ceiling now retains typed local phase expiry and stops later legs. Non-success status handling is unchanged. #5150 sends a plain-http (loopback) control request over node:http with a direct agent instead of global fetch. It still follows no redirect, and method, headers, and JSON body are unchanged. The sender is now loaded with the request URL and applies the credential rule itself: a refused destination, or a localhost that resolves off loopback, ends as a typed refusal before anything is sent. Method, path, headers, and body are unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#requestUploadPreflight", @@ -704,8 +704,8 @@ }, { "declaration": "packages/remote/src/artifact-download.ts#requestRemoteArtifact", - "digest": "sha256:bcd2a587fc699de6575feb95576e03e40f969852f77d9ed492ae02d49ea72ffc", - "rationale": "#5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request." + "digest": "sha256:85890c420579d6055b54caa37736c3d7627852f12bc243677a658cdbdf7c0ea7", + "rationale": "#5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request. The sender is now loaded with the request URL and applies the credential rule itself: a refused destination, or a localhost that resolves off loopback, ends as a typed refusal before anything is sent. Method, path, headers, and body are unchanged." } ] } diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 3f7c0d1bf6..1b9f446b3f 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -901,7 +901,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. | +| `insecure_credential_transport` | A credential would travel over plain http or ws to a host that is not loopback, to a `localhost` that resolves to no loopback address, 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 639681d9bc..3c6bcaf10e 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -46,7 +46,7 @@ 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`. +The client sends a token only over https, or over plain http to a loopback host (`127.0.0.0/8`, `::1`, or a `localhost` that resolves to one of them). 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. diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 5e46ba76a5..8da3caf47c 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -21,7 +21,15 @@ 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. -A client never sends a daemon, proxy, Metro host bridge, cloud auth, or provider credential over plain http to a host that is not loopback. It refuses such a URL before the first request, with `details.reason: "insecure_credential_transport"`. Use https, or a port forward to loopback. 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. The proxy applies the same rule to its upstream daemon URL for every transport, and never follows an upstream redirect; it relays the redirect response to its client, whose requests follow at most a same-origin redirect. A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). Provider URLs that receive a provider or runner token, or that are signed, such as Limrun API and download URLs and Revyl upload URLs, are checked right before each request. A Limrun download follows a redirect only from https to https or on the same origin, and drops its headers when it leaves the origin. The Metro companion opens the host bridge's socket only over `wss`, or `ws` to loopback. +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. + +- `localhost` counts only when it resolves to a loopback address. +- A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). +- A redirect is followed only on the same origin, except by a Limrun download, which also follows https to https and drops its headers when it leaves the origin. The proxy follows no upstream redirect; it relays the redirect response to its client. +- The Metro companion opens the host bridge's socket only over `wss`, or `ws` to loopback. A request the bridge relays to your dev server with an `Authorization` or `Cookie` header follows the same rule. +- 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. From 50fb538abeb626651900862462b13621643a8d5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 16:44:10 +0100 Subject: [PATCH 15/22] test(react-native): build the companion test redirect from constants The test bridge derived a redirect Location from the request URL. It now names each moved registration path itself. Co-Authored-By: Claude Sonnet 5.5 --- ...panion-tunnel-worker-credential-transport.test.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) 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 index 3e0bbe6ac9..65db60381e 100644 --- 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 @@ -72,6 +72,13 @@ function tolerateReset(socket: Duplex): void { socket.on('error', () => undefined); } +/** Where a registration path moved: a constant, never a value taken from the request. */ +function movedTo(path: string | undefined): string | undefined { + if (path === REGISTER_PATH) return `${REGISTER_PATH}/moved`; + if (path === UNREGISTER_PATH) return `${UNREGISTER_PATH}/moved`; + return undefined; +} + /** * A loopback bridge whose registration answers `wsUrl(port)`, recording what reaches it and what * the companion sends on the socket. `moved` redirects each registration path once. @@ -86,8 +93,9 @@ async function listenBridge(wsUrl: (port: number) => string, moved = false) { const server = http.createServer((req, res) => { received.push(`${req.url} ${req.headers.authorization}`); req.resume(); - if (moved && !req.url!.endsWith('/moved')) { - res.writeHead(307, { location: `${req.url}/moved` }).end(); + const location = moved ? movedTo(req.url) : undefined; + if (location) { + res.writeHead(307, { location }).end(); return; } res.end(JSON.stringify({ ok: true, data: { ws_url: wsUrl(port) } })); From 85cc91cc0d51138464ca1504d38041c15658aedc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 16:59:02 +0100 Subject: [PATCH 16/22] test(proxy): cover cancellation of a plain-http upstream exchange Client abort and upstreamTimeoutMs end the exchange on the default plain-http transport, before an answer and during one. Co-Authored-By: Claude Sonnet 5.5 --- .../src/daemon-proxy-cancellation.test.ts | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts index e0072965c0..d7f6422396 100644 --- a/packages/proxy/src/daemon-proxy-cancellation.test.ts +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -243,3 +243,93 @@ test('aborting the client request after a garbage collection aborts a pending au await authenticateAborted.promise; expect((await response).status).toBe(500); }); + +/** + * A loopback daemon that takes a request and then stays quiet, after half an answer when `answers`. + * `closed` resolves when the proxy ends the exchange. + */ +async function quietDaemon(answers: 'nothing' | 'half') { + const received = signalled(); + const closed = signalled(); + const server = http.createServer((req, res) => { + res.on('close', closed.resolve); + req.resume().on('end', () => { + if (answers === 'half') res.writeHead(200).write('half'); + received.resolve(); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + onTestFinished(async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }); + return { + url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + received: received.promise, + closed: closed.promise, + }; +} + +/** A proxy that reaches `upstreamBaseUrl` with its own transport, over plain http. */ +function proxyOverPlainHttp(upstreamBaseUrl: string, upstreamTimeoutMs?: number) { + return createDaemonProxy({ + upstreamBaseUrl, + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + ...(upstreamTimeoutMs === undefined ? {} : { upstreamTimeoutMs }), + }); +} + +const plainRoutes = { + rpc: (signal?: AbortSignal) => + rpcRequest({ jsonrpc: '2.0', id: 3, method: 'agent-device.command' }, { signal }), + health: (signal?: AbortSignal) => new Request(`${PROXY_ORIGIN}/agent-device/health`, { signal }), + diagnostics: (signal?: AbortSignal) => + new Request(`${PROXY_ORIGIN}/agent-device/sessions/default/requests/ref-1/diagnostics`, { + headers: { authorization: 'Bearer client-secret' }, + signal, + }), +}; + +test.each([ + ['rpc', 'nothing'], + ['rpc', 'half'], + ['health', 'nothing'], + ['diagnostics', 'nothing'], + ['diagnostics', 'half'], +] as const)( + 'aborting the client %s request ends its plain-http exchange, with %s answered', + async (route, answers) => { + const daemon = await quietDaemon(answers); + const client = new AbortController(); + // Like an embedder, the test keeps its request while the proxy answers it. + const clientRequest = plainRoutes[route](client.signal); + const response = proxyOverPlainHttp(daemon.url).handle(clientRequest); + await daemon.received; + await collectGarbage(); + client.abort(); + + await daemon.closed; + await (await response).body?.cancel().catch(() => undefined); + }, +); + +// The health probe keeps its own five-second bound instead of `upstreamTimeoutMs`. +test.each([ + ['rpc', 'nothing'], + ['rpc', 'half'], + ['diagnostics', 'nothing'], + ['diagnostics', 'half'], +] as const)( + 'upstreamTimeoutMs ends a quiet plain-http %s exchange, with %s answered', + async (route, answers) => { + const daemon = await quietDaemon(answers); + const clientRequest = plainRoutes[route](); + const response = proxyOverPlainHttp(daemon.url, 50).handle(clientRequest); + await daemon.received; + await collectGarbage(); + + await daemon.closed; + await (await response).body?.cancel().catch(() => undefined); + }, +); From 572b141b0ad1f3f112b14fb6218e4f93412f4af1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 17:55:48 +0100 Subject: [PATCH 17/22] refactor(remote)!: apply the credential transport rule over plain fetch Node keeps loopback destinations off environment proxies, so the direct node:http client protected against nothing. Remove it and go back to fetch and node:http as on main. Keep the one rule: a credential never travels over plain http or ws off loopback, and a redirect never carries it to another origin. Co-Authored-By: Claude Sonnet 5.5 --- .../src/__tests__/runner-transport.test.ts | 57 +- .../src/__tests__/test-host-defaults.ts | 10 +- packages/apple-runner/src/host.ts | 3 - packages/apple-runner/src/runner-transport.ts | 24 +- .../src/credential-transport.test.ts | 86 ++- .../contracts/src/credential-transport.ts | 70 +- ...emon-client-lifecycle-remote-trust.test.ts | 16 - .../daemon-client-liveness-probe.test.ts | 2 +- ...lient-loopback-probe-pooled-socket.test.ts | 2 +- .../daemon-client-transport-localhost.test.ts | 66 -- .../__tests__/daemon-client-transport.test.ts | 4 +- .../src/daemon-client-liveness-probe.ts | 2 +- .../src/daemon-client-loopback-probe.ts | 5 +- .../src/daemon-client-transport.ts | 12 +- packages/host-kit/package.json | 4 - packages/host-kit/src/direct-http.test.ts | 611 ------------------ packages/host-kit/src/direct-http.ts | 355 ---------- .../host-kit/src/internal/transport.test.ts | 15 +- packages/host-kit/src/internal/transport.ts | 33 +- .../platform-apple/src/core/runner-host.ts | 2 - .../provider-revyl/src/revyl-client.test.ts | 76 +-- packages/provider-revyl/src/revyl-client.ts | 16 +- packages/proxy/README.md | 16 +- packages/proxy/src/checked-rpc-admission.ts | 6 +- .../src/daemon-proxy-cancellation.test.ts | 90 --- .../daemon-proxy-credential-transport.test.ts | 130 +--- .../proxy/src/daemon-proxy-transfer.test.ts | 8 +- packages/proxy/src/daemon-proxy.ts | 25 +- packages/proxy/src/transfer-transport.ts | 15 +- packages/proxy/src/upstream-response-relay.ts | 5 - packages/react-native/package.json | 3 +- .../companion/client-companion-local-relay.ts | 50 +- ...tunnel-worker-credential-transport.test.ts | 154 +---- .../client-companion-tunnel-worker.ts | 23 +- packages/react-native/src/index-metro.test.ts | 5 +- .../metro/client-metro-auto-companion.test.ts | 60 -- .../react-native/src/metro/client-metro.ts | 4 +- .../upload-client-cancellation.test.ts | 35 +- packages/remote/src/artifact-download.ts | 4 +- .../remote/src/remote-request-diagnostics.ts | 2 +- packages/remote/src/upload-client.ts | 12 +- packages/remote/src/upload-stream.ts | 4 +- .../test-kit/src/host-kit-capabilities.ts | 33 +- pnpm-lock.yaml | 3 - scripts/layering/package-boundaries.test.ts | 2 - src/cli/__tests__/cloud-auth-request.test.ts | 17 +- src/cli/cloud-auth-request.ts | 6 +- .../cloud-profile-transport.test.ts | 86 +-- src/core/interactors/limrun-ios-files.test.ts | 29 - src/core/interactors/limrun-ios-files.ts | 25 +- .../interactors/limrun-ios-runner-products.ts | 31 +- .../interactors/limrun-ios-runner.test.ts | 22 +- src/core/interactors/limrun-ios-runner.ts | 27 +- src/core/limrun-download-file.test.ts | 127 +--- src/core/limrun-download-file.ts | 57 +- .../remote-proxy-request-diagnostics.test.ts | 5 - test/wire-compat/ledger.json | 33 +- website/docs/docs/error-reasons.md | 4 +- website/docs/docs/remote-proxy.md | 2 +- website/docs/docs/security-trust.md | 3 +- 60 files changed, 460 insertions(+), 2174 deletions(-) delete mode 100644 packages/daemon-client/src/__tests__/daemon-client-transport-localhost.test.ts delete mode 100644 packages/host-kit/src/direct-http.test.ts delete mode 100644 packages/host-kit/src/direct-http.ts diff --git a/packages/apple-runner/src/__tests__/runner-transport.test.ts b/packages/apple-runner/src/__tests__/runner-transport.test.ts index 9a34cd0589..5145ec4560 100644 --- a/packages/apple-runner/src/__tests__/runner-transport.test.ts +++ b/packages/apple-runner/src/__tests__/runner-transport.test.ts @@ -1,8 +1,6 @@ import { afterEach, beforeEach, test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; -import http from 'node:http'; -import type { AddressInfo } from 'node:net'; import path from 'node:path'; import { AppError, @@ -47,7 +45,6 @@ import { sendRunnerCommandOnce, } from '../runner-transport.ts'; import { mkdtempForTestSync } from './tmp-dir.ts'; -import { loadRealHostKitCapabilities } from '@agent-device/test-kit'; // The real `resolveIosPhysicalDeviceControl` resolves the CoreDevice tunnel IP // through root-level tooling this package cannot reach; a fake control backed @@ -238,12 +235,21 @@ test('a forwarded runner route never sends its tokens over plain http off loopba assert.equal(fetchMock.mock.calls.length, 0); }); -// The same address is allowed on the tunnel route (the fallback cases below), so the exclusion +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.each([ - ['whose endpoint carries its forwarding', { url: 'http://[fd00::123]:8100/command' }], - ['whose endpoint names no forwarding', undefined], -])('a forwarded route to a tunnel-shaped address %s is refused', async (_label, http) => { +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 = { @@ -255,7 +261,7 @@ test.each([ await assert.rejects( () => postRunnerCommandOverRoute(iosDevice, route, { - endpoint: { ...RUNNER_ENDPOINT_FIXTURE, ...(http ? { http } : {}) }, + endpoint: RUNNER_ENDPOINT_FIXTURE, command: { command: 'uptime' }, timeoutMs: 5_000, }), @@ -392,36 +398,3 @@ test('a cancellation during route resolution discloses that the command was neve ); assert.equal(vi.mocked(fetch).mock.calls.length, 0); }); - -test('the real transport sends a loopback runner command around global fetch', async () => { - const hostKit = await loadRealHostKitCapabilities(); - appleRunnerTestHost.update({ fetchWithCredential: hostKit.fetchWithCredential }); - const received: string[] = []; - const runner = http.createServer((req, res) => { - let body = ''; - req.on('data', (chunk) => (body += String(chunk))); - req.on('end', () => { - received.push(`${req.url} ${req.headers['content-length']} ${body.length}`); - if (req.url === '/moved') res.writeHead(307, { location: '/target' }).end(); - else res.end('{}'); - }); - }); - await new Promise((resolve) => runner.listen(0, '127.0.0.1', resolve)); - const origin = `http://127.0.0.1:${(runner.address() as AddressInfo).port}`; - const proxied = vi.fn().mockRejectedValue(new Error('proxied')); - vi.stubGlobal('fetch', proxied); - - try { - const post = { method: 'POST', body: 'command' }; - assert.equal((await fetchWithTimeout(`${origin}/command`, post, 5_000)).status, 200); - // The runner token travels in a header, so the redirect target gets nothing. - await assert.rejects(() => fetchWithTimeout(`${origin}/moved`, post, 5_000), TypeError); - - assert.deepEqual(received, ['/command 7 7', '/moved 7 7']); - assert.equal(proxied.mock.calls.length, 0); - } finally { - vi.unstubAllGlobals(); - runner.closeAllConnections(); - await new Promise((resolve) => runner.close(() => resolve())); - } -}); diff --git a/packages/apple-runner/src/__tests__/test-host-defaults.ts b/packages/apple-runner/src/__tests__/test-host-defaults.ts index 87b0ed554e..ef49d09d95 100644 --- a/packages/apple-runner/src/__tests__/test-host-defaults.ts +++ b/packages/apple-runner/src/__tests__/test-host-defaults.ts @@ -94,9 +94,8 @@ function appleToolingTestAdapters(): Pick< * environment, and the explicit Apple adapters above. It reads no platform-apple or root code. */ export async function createAppleRunnerTestHostDefaults(): Promise { - const hostKit = await loadRealHostKitCapabilities(); return { - ...hostKit, + ...(await loadRealHostKitCapabilities()), ...appleToolingTestAdapters(), hostEnvironment: createLiveTestHostEnvironment, shellQuote, @@ -105,13 +104,6 @@ export async function createAppleRunnerTestHostDefaults(): Promise - hostKit.fetchWithCredential(input, init, { - ...destination, - send: async (to, request) => await fetch(to, request), - }), leaseOwnerStateDir: () => undefined, hasDeviceClaimAuthority: () => false, }; diff --git a/packages/apple-runner/src/host.ts b/packages/apple-runner/src/host.ts index 16686cdb25..8ce159ac86 100644 --- a/packages/apple-runner/src/host.ts +++ b/packages/apple-runner/src/host.ts @@ -1,6 +1,5 @@ import type * as HostCommand from '@agent-device/host-kit/command'; import type * as HostDiagnostics from '@agent-device/host-kit/diagnostics'; -import type * as HostDirectHttp from '@agent-device/host-kit/direct-http'; import type * as HostFile from '@agent-device/host-kit/file'; import type * as HostProcess from '@agent-device/host-kit/process'; import type * as HostRequest from '@agent-device/host-kit/request'; @@ -99,7 +98,6 @@ export type AppleRunnerHost = Pick< | 'commandDeveloperDir' > & Pick & - Pick & Pick & Pick< typeof HostProcess, @@ -200,7 +198,6 @@ export const hostEnvironment = delegate('hostEnvironment'); export const shellQuote = delegate('shellQuote'); export const emitDiagnostic = delegate('emitDiagnostic'); export const withDiagnosticTimer = delegate('withDiagnosticTimer'); -export const fetchWithCredential = delegate('fetchWithCredential'); export const retryWithPolicy = delegate('retryWithPolicy'); export const isEnvTruthy = delegate('isEnvTruthy'); export const isProcessAlive = delegate('isProcessAlive'); diff --git a/packages/apple-runner/src/runner-transport.ts b/packages/apple-runner/src/runner-transport.ts index b7641ac50a..996c5e892f 100644 --- a/packages/apple-runner/src/runner-transport.ts +++ b/packages/apple-runner/src/runner-transport.ts @@ -3,7 +3,7 @@ import { discloseDispatch, AppError, } from '@agent-device/kernel/errors'; -import { Deadline, fetchWithCredential, resolveIosPhysicalDeviceControl } from './host.ts'; +import { Deadline, resolveIosPhysicalDeviceControl } from './host.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { createRunnerCommandRouteResolver, @@ -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, { @@ -114,11 +126,6 @@ export async function postRunnerCommandOverRoute( }, timeoutMs, signal, - // The request carries the runner token, and a forwarded one the provider's own headers. - { - subject: endpoint.http ? 'Runner forwarding URL' : 'Runner device address', - coreDeviceTunnel: route.coreDeviceTunnel, - }, ); if (endpoint.http && [502, 503, 504].includes(response.status)) { await response.body?.cancel(); @@ -150,15 +157,12 @@ export async function fetchWithTimeout( init: RequestInit, timeoutMs: number, requestSignal?: AbortSignal, - destination: Readonly<{ subject: string; coreDeviceTunnel?: boolean }> = { - subject: 'Runner URL', - }, ): Promise { const timeoutSignal = AbortSignal.timeout(timeoutMs); const signal = requestSignal ? AbortSignal.any([requestSignal, timeoutSignal]) : timeoutSignal; try { // The token travels in a header, so a redirect must never carry it elsewhere. - return await fetchWithCredential(url, { ...init, redirect: 'error', signal }, destination); + return await fetch(url, { ...init, redirect: 'error', signal }); } catch (error) { // `AbortSignal.timeout` rejects with a bare DOMException that no recovery rule can // read. Only a rejection carrying that signal's own reason is our deadline: a diff --git a/packages/contracts/src/credential-transport.test.ts b/packages/contracts/src/credential-transport.test.ts index ceedf5c772..08a07287c3 100644 --- a/packages/contracts/src/credential-transport.test.ts +++ b/packages/contracts/src/credential-transport.test.ts @@ -1,8 +1,9 @@ -import { expect, test } from 'vitest'; +import { expect, test, vi } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; import { assertSecureCredentialSocket, assertSecureCredentialTransport, + fetchWithCredential, } from './credential-transport.ts'; import { isLoopbackHostname } from './loopback-host.ts'; @@ -95,3 +96,86 @@ test.each([ assertSecureCredentialTransport(url, 'Runner URL', { coreDeviceTunnel: true }), ).toThrow(); }); + +/** Sends through a transport that answers each URL in `redirects` with that redirect. */ +async function followRedirects( + url: string, + redirects: Record, + followHttpsOffOrigin = false, +) { + const sent: string[] = []; + const response = await fetchWithCredential( + url, + { + method: 'POST', + headers: { authorization: 'Bearer secret', 'content-type': 'application/json' }, + body: 'payload', + }, + { + subject: 'Test URL', + followHttpsOffOrigin, + send: async (input, init) => { + const headers = new Headers(init?.headers); + const parts = [init?.method, String(input), init?.redirect, init?.body ?? '-']; + sent.push( + [...parts, headers.get('authorization') ?? '-', headers.get('content-type') ?? '-'].join( + ' ', + ), + ); + const redirect = redirects[String(input)]; + if (!redirect) return new Response('done'); + return new Response(null, { status: redirect[0], headers: { location: redirect[1] } }); + }, + }, + ); + return { status: response.status, sent }; +} + +const A = 'https://a.example/start'; +const first = `POST ${A} manual payload Bearer secret application/json`; + +test.each([307, 308])('a same-origin %s resends the method, body and headers', async (status) => { + expect(await followRedirects(A, { [A]: [status, '/moved'] })).toEqual({ + status: 200, + sent: [first, 'POST https://a.example/moved manual payload Bearer secret application/json'], + }); +}); + +test.each([301, 302, 303])('a same-origin %s turns a POST into a GET', async (status) => { + expect((await followRedirects(A, { [A]: [status, '/moved'] })).sent).toEqual([ + first, + 'GET https://a.example/moved manual - Bearer secret -', + ]); +}); + +test.each([ + ['another origin', 'https://b.example/start'], + ['plain http on the same host', 'http://a.example/start'], + ['a URL with a username', 'https://operator@a.example/start'], +])('a redirect to %s is returned, never followed', async (_label, location) => { + expect(await followRedirects(A, { [A]: [307, location] })).toEqual({ + status: 307, + sent: [first], + }); +}); + +test('three same-origin redirects are followed and the fourth is returned', async () => { + const { status, sent } = await followRedirects(A, { [A]: [307, A] }); + expect(status).toBe(307); + expect(sent).toHaveLength(4); +}); + +test('a download follows https off the origin without headers, and never to plain http', async () => { + const b = 'https://b.example/file'; + expect( + await followRedirects(A, { [A]: [307, b], [b]: [307, 'http://b.example/file'] }, true), + ).toEqual({ status: 307, sent: [first, `POST ${b} manual payload - -`] }); +}); + +test('a destination the rule refuses is never sent to', async () => { + const send = vi.fn(); + await expect( + fetchWithCredential('http://a.example', {}, { subject: 'Test URL', send }), + ).rejects.toMatchObject({ details: { reason: 'insecure_credential_transport' } }); + expect(send).not.toHaveBeenCalled(); +}); diff --git a/packages/contracts/src/credential-transport.ts b/packages/contracts/src/credential-transport.ts index 9673313880..a964c9479e 100644 --- a/packages/contracts/src/credential-transport.ts +++ b/packages/contracts/src/credential-transport.ts @@ -4,13 +4,13 @@ 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. `@agent-device/host-kit` applies it to every URL it sends a credential to. +// 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 `localhost` - // that resolves to no loopback address, 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. + // 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'>; @@ -74,7 +74,7 @@ export function assertSecureCredentialSocket(url: string, subject: string): URL } /** The typed refusal. It is only ever thrown before the credential leaves. */ -export function credentialTransportRefusal(message: string): AppError { +function credentialTransportRefusal(message: string): AppError { return new AppError('INVALID_ARGS', message, { reason: CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason, dispatched: 'no', @@ -88,3 +88,63 @@ export function isCredentialTransportRefusal(error: unknown): error is AppError error.details?.reason === CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason ); } + +const MAX_FOLLOWED_REDIRECTS = 3; + +export function isRedirectStatus(status: number): boolean { + return [301, 302, 303, 307, 308].includes(status); +} + +export type CredentialFetch = { + /** Names the setting a refusal is about. */ + subject: string; + /** The caller's transport; global `fetch` by default. */ + send?: typeof fetch; + /** For a download: also follows https to https on another origin, without the request headers. */ + followHttpsOffOrigin?: boolean; +}; + +/** + * `fetch` for a request that carries a credential and may be redirected. Every URL it sends to + * meets the credential transport rule. It follows up to three redirects itself, on the same origin, + * keeping the method and body on a 307 or 308. Any other redirect is returned as the answer. + */ +export async function fetchWithCredential( + url: string | URL, + init: RequestInit, + { subject, send = fetch, followHttpsOffOrigin = false }: CredentialFetch, +): Promise { + let target = assertSecureCredentialTransport(url, subject); + let request: RequestInit = { ...init, redirect: 'manual' }; + for (let followed = 0; ; followed += 1) { + const response = await send(target.href, request); + const next = followedTarget(response, target, followHttpsOffOrigin); + if (!next || followed === MAX_FOLLOWED_REDIRECTS) return response; + await response.body?.cancel().catch(() => undefined); + request = redirectedRequest(request, response.status); + if (next.origin !== target.origin) request = { ...request, headers: undefined }; + target = assertSecureCredentialTransport(next, subject); + } +} + +/** Where a redirect leads, when it is one `fetchWithCredential` follows. */ +function followedTarget(response: Response, from: URL, offOrigin: boolean): URL | undefined { + if (!isRedirectStatus(response.status)) return undefined; + const location = response.headers.get('location'); + if (location === null) return undefined; + const to = URL.parse(location, from); + if (!to || to.username || to.password) return undefined; + if (to.origin === from.origin) return to; + return offOrigin && from.protocol === 'https:' && to.protocol === 'https:' ? to : undefined; +} + +/** The request a followed redirect sends, with the change to GET that `fetch` makes. */ +function redirectedRequest(request: RequestInit, status: number): RequestInit { + const method = request.method?.toUpperCase() ?? 'GET'; + const becomesGet = + status === 303 ? method !== 'HEAD' : (status === 301 || status === 302) && method === 'POST'; + if (!becomesGet) return request; + const headers = new Headers(request.headers); + headers.delete('content-type'); + return { ...request, method: 'GET', body: undefined, headers }; +} 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 index 997a90f487..a32933d77b 100644 --- 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 @@ -9,7 +9,6 @@ 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'; -import { resolveClientSettings } from '../daemon-client-lifecycle.ts'; const REQUEST = { session: 'default', command: 'devices', positionals: [], flags: {} }; @@ -79,18 +78,3 @@ test('the connect checked-capability probe refuses a plain http daemon off loopb assert.doesNotMatch(JSON.stringify([refusal.message, refusal.details]), /remote-mac/); for (const spy of opened) assert.equal(spy.mock.calls.length, 0); }); - -test.each([ - 'http://127.0.0.1:4310/agent-device', - 'http://[::1]:4310/agent-device', - 'http://localhost:4310/agent-device', - 'https://remote-mac.example.test/agent-device', -])('a token for %s is admitted', (daemonBaseUrl) => { - const settings = resolveClientSettings( - { ...REQUEST, flags: { daemonBaseUrl } }, - 'remote-secret', - createTestHostEnvironment(), - ); - assert.equal(settings.remoteBaseUrl, daemonBaseUrl); - assert.equal(settings.remoteAuthToken, 'remote-secret'); -}); diff --git a/packages/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts b/packages/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts index b87871b986..f87a58618d 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts @@ -144,7 +144,7 @@ test('the health leg rides a fresh connection, never the keep-alive pool', async else primed = true; res.end('{}'); }); - const httpRequester = await loadNodeHttpRequester(new URL('http://127.0.0.1')); + const httpRequester = await loadNodeHttpRequester('http:'); await withLoopback(server, async (port) => { // Prime: a full keep-alive request/response whose socket returns to the global pool. await new Promise((resolve, reject) => { diff --git a/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts index e4d713d571..1996a2ff99 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts @@ -47,7 +47,7 @@ test('a fresh connect the host refused is not answered around by a pooled socket // the agent. It goes through the SAME module object the probe loads, or no candidate lands in the // pool and the case proves nothing. The request is bounded so a pool this case does not control // cannot hold it open to the test budget. - const requester = await hostTransport.loadNodeHttpRequester(new URL('http://127.0.0.1')); + const requester = await hostTransport.loadNodeHttpRequester('http:'); await new Promise((resolve, reject) => { const request = requester.request( { host: '127.0.0.1', port, path: '/health', method: 'GET', timeout: 2_000 }, diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport-localhost.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport-localhost.test.ts deleted file mode 100644 index 6aba3d4624..0000000000 --- a/packages/daemon-client/src/__tests__/daemon-client-transport-localhost.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -// A remote daemon URL that names `localhost` is admitted by name, so every send to it must connect -// only to a loopback address, whatever the resolver answers. - -import { afterEach, expect, test, vi } from 'vitest'; -import dns from 'node:dns'; -import http from 'node:http'; -import { isCredentialTransportRefusal } from '@agent-device/contracts/credential-transport'; -import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; -import { - bindTestCommandHost, - closeLoopbackServer, - createTestHostEnvironment, - listenOnLoopback, - mkdtempForTestSync, -} from '@agent-device/test-kit'; -import { - probeDaemonReachability, - readRemoteDaemonHealth, - sendRequest, -} from '../daemon-client-transport.ts'; - -bindTestCommandHost(); - -const servers: http.Server[] = []; -afterEach(async () => { - vi.restoreAllMocks(); - await Promise.all(servers.splice(0).map((server) => closeLoopbackServer(server))); -}); - -test('a localhost that resolves off loopback receives no health, probe or RPC request', async () => { - const received: string[] = []; - const server = http.createServer((req, res) => { - received.push(`${req.method} ${req.url} ${req.headers.authorization}`); - res.end('{}'); - }); - servers.push(server); - const info = { - token: 'daemon-secret', - pid: 0, - baseUrl: `http://localhost:${await listenOnLoopback(server)}`, - }; - // `0.0.0.0` reaches this machine's listener and is not a loopback address. - vi.spyOn(dns, 'lookup').mockImplementation((( - _hostname: string, - options: dns.LookupOptions, - callback: (...answer: unknown[]) => void, - ) => { - if (options.all) callback(null, [{ address: '0.0.0.0', family: 4 }]); - else callback(null, '0.0.0.0', 4); - }) as typeof dns.lookup); - - await expect(readRemoteDaemonHealth(info, 2_000)).rejects.toSatisfy(isCredentialTransportRefusal); - expect(await probeDaemonReachability(info, 'http', 2_000)).toMatchObject({ reachable: false }); - await expect( - sendRequest( - info, - { token: info.token, session: 'default', command: 'devices', positionals: [], flags: {} }, - 'http', - resolveDaemonPaths(mkdtempForTestSync('daemon-client-localhost-')), - 2_000, - { host: createTestHostEnvironment() }, - ), - ).rejects.toSatisfy(isCredentialTransportRefusal); - - expect(received).toEqual([]); -}); diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts index 187cc3b98b..a7fa975558 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -119,9 +119,9 @@ test('the health deadline includes requester loading and forbids a late request' const actualLoad = hostTransport.loadNodeHttpRequester; const load = vi .spyOn(hostTransport, 'loadNodeHttpRequester') - .mockImplementation(async (url, credential) => { + .mockImplementation(async (protocol) => { await blocked; - return actualLoad(url, credential); + return actualLoad(protocol); }); let probing: Promise | undefined; try { diff --git a/packages/daemon-client/src/daemon-client-liveness-probe.ts b/packages/daemon-client/src/daemon-client-liveness-probe.ts index 3bda5429fe..7a35600be2 100644 --- a/packages/daemon-client/src/daemon-client-liveness-probe.ts +++ b/packages/daemon-client/src/daemon-client-liveness-probe.ts @@ -152,7 +152,7 @@ function probeHttpHealth(httpPort: number, deadlineAtMs: number): ProbeLeg { // This leg builds detached. Catch transport-construction errors here so they settle the probe. void (async () => { try { - const transport = await loadNodeHttpRequester(new URL(`http://127.0.0.1:${httpPort}/health`)); + const transport = await loadNodeHttpRequester('http:'); const request = transport.request( // `agent: false` is load-bearing, not hygiene: since Node 19 the global agent keeps sockets // alive, so a pooled request would ride an idle socket from an earlier command's health read diff --git a/packages/daemon-client/src/daemon-client-loopback-probe.ts b/packages/daemon-client/src/daemon-client-loopback-probe.ts index 90506a509a..b72d113d41 100644 --- a/packages/daemon-client/src/daemon-client-loopback-probe.ts +++ b/packages/daemon-client/src/daemon-client-loopback-probe.ts @@ -147,10 +147,7 @@ export async function probeHttpEndpoint(probe: HttpEndpointProbe): Promise loadNodeHttpRequester(url, { subject: 'Daemon health probe URL' }), - probe.timeoutMs, - ); + const loaded = await settleWithin(() => loadNodeHttpRequester(url.protocol), probe.timeoutMs); if (loaded.kind === 'deadline') return { reachable: false }; // What the loader spent is gone from the request's window: the budget belongs to the probe, not to // each step inside it. diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index f751216cf0..21fe9a0d7f 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -298,14 +298,14 @@ async function readDaemonHttpHealth( const timeoutSignal = AbortSignal.timeout(Math.ceil(timeoutMs)); const signal = callerSignal ? AbortSignal.any([timeoutSignal, callerSignal]) : timeoutSignal; const transport = await Promise.race([ - loadNodeHttpRequester(url, { subject: 'Remote daemon base URL' }), + loadNodeHttpRequester(url.protocol), new Promise((resolve) => { signal.addEventListener('abort', () => resolve(null), { once: true }); }), ]); const unreachable = (): RemoteDaemonHealth => unreachableDaemonHealth(timeoutSignal, deadline); if (!transport || healthProbeExpired(signal, deadline)) return unreachable(); - return await new Promise((resolve, reject) => { + return await new Promise((resolve) => { const headers = info.baseUrl ? buildDaemonHttpAuthHeaders(info.token) : {}; const req = transport.request( { @@ -340,9 +340,8 @@ async function readDaemonHttpHealth( req.destroy(); resolve({ reachable: false, timedOut: true }); }); - req.on('error', (error) => { - if (error instanceof AppError) reject(error); - else resolve(unreachable()); + req.on('error', () => { + resolve(unreachable()); }); req.end(); }); @@ -812,7 +811,7 @@ async function sendHttpRequest( } if (checked) headers[DAEMON_HTTP_RPC_PROTOCOL_HEADER] = String(DAEMON_RPC_PROTOCOL_VERSION); const checkedRpc = checked ? await import('./daemon-client-checked-rpc.ts') : undefined; - const transport = await loadNodeHttpRequester(rpcUrl, { subject: 'Remote daemon base URL' }); + const transport = await loadNodeHttpRequester(rpcUrl.protocol); const callerSignal = options.signal; refuseAbortedRequest(callerSignal, req.meta?.requestId); @@ -952,7 +951,6 @@ async function sendHttpRequest( // from emitting a `daemon_request_socket_error` diagnostic; a genuine transport error still // arrives before the settle and rejects. if (settled) return; - if (err instanceof AppError) return rejectOnce(err); if (connectWatch?.unconnected()) return rejectOnce(connectWatch.failure(false)); rejectOnce(handleTransportError(err, req.meta?.requestId, remote, requestSent)); }); diff --git a/packages/host-kit/package.json b/packages/host-kit/package.json index afe25d002c..e75388b928 100644 --- a/packages/host-kit/package.json +++ b/packages/host-kit/package.json @@ -44,10 +44,6 @@ "types": "./src/diagnostics.ts", "default": "./src/diagnostics.ts" }, - "./direct-http": { - "types": "./src/direct-http.ts", - "default": "./src/direct-http.ts" - }, "./doctor-lines": { "types": "./src/doctor-lines.ts", "default": "./src/doctor-lines.ts" diff --git a/packages/host-kit/src/direct-http.test.ts b/packages/host-kit/src/direct-http.test.ts deleted file mode 100644 index 83f1cee32e..0000000000 --- a/packages/host-kit/src/direct-http.test.ts +++ /dev/null @@ -1,611 +0,0 @@ -import { afterEach, expect, test, vi } from 'vitest'; -import { execFile } from 'node:child_process'; -import http from 'node:http'; -import path from 'node:path'; -import { Readable } from 'node:stream'; -import { promisify } from 'node:util'; -import dns from 'node:dns'; -import net, { type AddressInfo } from 'node:net'; -import zlib from 'node:zlib'; -import { fetchWithCredential, loadDirectHttpAgent, type CredentialSend } from './direct-http.ts'; -import { loadNodeHttpRequester } from './transport.ts'; - -// A credential sent over plain http goes only to loopback, and an environment proxy on another host -// would read it in cleartext. Node reads `NODE_USE_ENV_PROXY` at startup, so each case runs a child. - -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(seen: string[]): Promise { - const server = http.createServer((req, res) => { - seen.push(`${req.method} ${req.url} ${req.headers.authorization ?? ''}`); - res.end('ok'); - }); - servers.push(server); - return await listenLocal(server); -} - -const TRANSPORT = path.join(import.meta.dirname, 'direct-http.ts'); - -async function runChild(script: string, proxyPort: number): Promise { - const { stdout } = await promisify(execFile)( - process.execPath, - ['--experimental-strip-types', '--input-type=module', '-e', script], - { - env: { - ...process.env, - NODE_USE_ENV_PROXY: '1', - HTTP_PROXY: `http://127.0.0.1:${proxyPort}`, - http_proxy: `http://127.0.0.1:${proxyPort}`, - NO_PROXY: '', - no_proxy: '', - }, - }, - ); - return stdout.trim(); -} - -test.each([ - [ - 'node:http with loadDirectHttpAgent', - (target: string) => ` - import http from 'node:http'; - import { loadDirectHttpAgent } from ${JSON.stringify(TRANSPORT)}; - const agent = await loadDirectHttpAgent(); - await new Promise((resolve, reject) => { - const req = http.request(${JSON.stringify(target)}, { agent, headers: { authorization: 'Bearer secret' } }, (res) => { res.resume(); res.on('end', resolve); }); - req.on('error', reject); - req.end(); - }); - console.log('sent');`, - ], - [ - 'fetchWithCredential', - (target: string) => ` - import { fetchWithCredential } from ${JSON.stringify(TRANSPORT)}; - const response = await fetchWithCredential(${JSON.stringify(target)}, { headers: { authorization: 'Bearer secret' } }, { subject: 'Test URL' }); - console.log(await response.text() === 'ok' ? 'sent' : 'bad');`, - ], -])('%s reaches loopback directly, never through an environment proxy', async (_label, script) => { - const proxied: string[] = []; - const direct: string[] = []; - const proxyPort = await serve(proxied); - const targetPort = await serve(direct); - - const output = await runChild(script(`http://127.0.0.1:${targetPort}/rpc`), proxyPort); - - expect(output).toBe('sent'); - expect(proxied).toEqual([]); - expect(direct).toEqual(['GET /rpc Bearer secret']); -}); - -/** One request through the primitive, as a caller with no transport of its own sends it. */ -function send(url: string, init: RequestInit = {}, options: Partial = {}) { - return fetchWithCredential(url, init, { subject: 'Test URL', ...options }); -} - -function deferred() { - let resolve!: () => void; - const promise = new Promise((done) => (resolve = done)); - return { promise, resolve }; -} - -/** A loopback server that answers as `respond` does and records what its connections saw. */ -async function serveWith(respond: http.RequestListener) { - const closed = deferred(); - const server = http.createServer((req, res) => { - res.on('close', () => closed.resolve()); - respond(req, res); - }); - servers.push(server); - const origin = `http://127.0.0.1:${await listenLocal(server)}`; - return { origin, closed: closed.promise }; -} - -const stayQuiet: http.RequestListener = () => {}; -const sendHalf: http.RequestListener = (_req, res) => void res.write('half'); - -test('a post declares its length and returns a redirect without following it', async () => { - const seen: string[] = []; - const target = await serveWith((req, res) => { - seen.push(req.url ?? ''); - res.end(); - }); - const { origin } = await serveWith((req, res) => { - let body = ''; - req.on('data', (chunk) => (body += String(chunk))); - req.on('end', () => { - seen.push(`${req.headers['content-length']} ${body}`); - res.writeHead(307, { location: `${target.origin}/moved` }).end(); - }); - }); - - const response = await send(origin, { - method: 'POST', - body: 'payload', - redirect: 'manual', - }); - - expect(response.status).toBe(307); - await expect( - send(origin, { method: 'POST', body: 'payload', redirect: 'error' }), - ).rejects.toThrow(TypeError); - expect(seen).toEqual(['7 payload', '7 payload']); -}); - -test('a refused connection rejects as fetch does, with the socket error as the cause', async () => { - const server = http.createServer(); - const port = await listenLocal(server); - await closeLocal(server); - - await expect(send(`http://127.0.0.1:${port}/`)).rejects.toMatchObject({ - name: 'TypeError', - message: 'fetch failed', - cause: { code: 'ECONNREFUSED' }, - }); -}); - -test('an abort before the response rejects with its reason and closes the connection', async () => { - const received = deferred(); - const { origin, closed } = await serveWith(() => received.resolve()); - const controller = new AbortController(); - const reason = new Error('caller gave up'); - - const pending = send(origin, { signal: controller.signal }); - await received.promise; - controller.abort(reason); - - await expect(pending).rejects.toBe(reason); - await closed; -}); - -test('an abort during the response body fails the read and closes the connection', async () => { - const { origin, closed } = await serveWith(sendHalf); - const controller = new AbortController(); - const reason = new Error('caller gave up'); - const response = await send(origin, { signal: controller.signal }); - const reader = response.body!.getReader(); - await reader.read(); - - const pending = reader.read(); - controller.abort(reason); - - await expect(pending).rejects.toBe(reason); - await closed; -}); - -/** Runs the real socket timeout at 20 ms, and records the bound the request asked for. */ -function shortenIdleTimeout(): unknown[] { - const asked: unknown[] = []; - const request = http.request; - vi.spyOn(http, 'request').mockImplementation((( - options: http.RequestOptions, - callback: (res: http.IncomingMessage) => void, - ) => { - asked.push(options.timeout); - return request({ ...options, timeout: 20 }, callback); - }) as typeof http.request); - return asked; -} - -const idleTimeout = { details: { reason: 'direct_http_idle_timeout' } }; - -test('a peer that never answers ends the request with the idle timeout', async () => { - const { origin, closed } = await serveWith(stayQuiet); - const asked = shortenIdleTimeout(); - - await expect(send(origin)).rejects.toMatchObject(idleTimeout); - - await closed; - expect(asked).toEqual([300_000]); -}); - -test('a body that goes silent fails the read with the idle timeout', async () => { - const { origin, closed } = await serveWith(sendHalf); - shortenIdleTimeout(); - const response = await send(origin); - - await expect(response.text()).rejects.toMatchObject(idleTimeout); - await closed; -}); - -test('the credential requester keeps its direct agent whatever the options name', async () => { - const { origin } = await serveWith((_req, res) => void res.end()); - const pooled = await loadDirectHttpAgent(); - const request = vi.spyOn(http, 'request'); - const requester = await loadNodeHttpRequester(new URL(origin), { subject: 'Test URL' }); - - for (const agent of [undefined, new http.Agent(), false as const]) { - const options: http.RequestOptions = { host: '127.0.0.1', port: new URL(origin).port, agent }; - await new Promise((resolve, reject) => { - const sent = requester.request(options, (res) => { - res.resume(); - res.on('end', resolve); - }); - sent.on('error', reject); - sent.end(); - }); - } - - const used = request.mock.calls.map(([options]) => (options as http.RequestOptions).agent); - expect(used.slice(0, 2)).toEqual([pooled, pooled]); - // `agent: false` asks for a connection of its own, still a direct one. - expect(used[2]).not.toBe(pooled); - expect(used[2]).toBeInstanceOf(http.Agent); -}); - -/** A server that records each upload's framing and body, and reports its first bytes. */ -async function serveUpload() { - const uploads: Array<{ length?: string; encoding?: string; body: string }> = []; - const started = deferred(); - const { origin, closed } = await serveWith((req, res) => { - const upload = { - length: req.headers['content-length'], - encoding: req.headers['transfer-encoding'], - body: '', - }; - uploads.push(upload); - req.on('data', (chunk) => { - upload.body += String(chunk); - started.resolve(); - }); - req.on('end', () => res.end()); - }); - return { origin, closed, uploads, started: started.promise }; -} - -test.each([ - ['declares the length its headers give', { 'content-length': '12' }, '12', undefined], - ['is chunked without a declared length', undefined, undefined, 'chunked'], -])('a streamed body is sent as it arrives and %s', async (_label, headers, length, encoding) => { - const server = await serveUpload(); - async function* body() { - yield Buffer.from('first,'); - // A sender that read the whole body first would never get here. - await server.started; - yield Buffer.from('second'); - } - - const response = await send(server.origin, { - method: 'PUT', - ...(headers ? { headers } : {}), - body: body() as unknown as BodyInit, - duplex: 'half', - } as RequestInit); - - expect(response.status).toBe(200); - expect(server.uploads).toEqual([{ length, encoding, body: 'first,second' }]); -}); - -/** One chunk, then silence; `release` runs when the stream is cancelled or destroyed. */ -const stalledStreams: Array<[string, (release: () => void) => unknown]> = [ - [ - 'a web stream', - (release) => - new ReadableStream({ - start: (stream) => stream.enqueue(Buffer.from('first,')), - cancel: release, - }), - ], - [ - 'a Node stream', - (release) => { - const stream = new Readable({ - read: () => {}, - destroy: (error, done) => { - release(); - done(error); - }, - }); - stream.push('first,'); - return stream; - }, - ], -]; - -test.each(stalledStreams)('an abort during an upload releases %s', async (_label, source) => { - const server = await serveUpload(); - const released = deferred(); - const controller = new AbortController(); - const reason = new Error('caller gave up'); - - const pending = send(server.origin, { - method: 'PUT', - body: source(released.resolve) as BodyInit, - signal: controller.signal, - duplex: 'half', - } as RequestInit); - await server.started; - controller.abort(reason); - - await expect(pending).rejects.toBe(reason); - await released.promise; - await server.closed; -}); - -test.each(stalledStreams)( - 'an upload aborted before it starts releases %s and sends nothing', - async (_label, source) => { - const server = await serveUpload(); - const released = deferred(); - const reason = new Error('caller gave up'); - - await expect( - send(server.origin, { - method: 'PUT', - body: source(released.resolve) as BodyInit, - signal: AbortSignal.abort(reason), - duplex: 'half', - } as RequestInit), - ).rejects.toBe(reason); - - await released.promise; - expect(server.uploads).toEqual([]); - }, -); - -test('a streamed body that fails rejects the request as fetch does', async () => { - const server = await serveUpload(); - const failure = new Error('disk gone'); - async function* body() { - yield Buffer.from('first,'); - throw failure; - } - - await expect( - send(server.origin, { - method: 'PUT', - body: body() as unknown as BodyInit, - duplex: 'half', - } as RequestInit), - ).rejects.toMatchObject({ message: 'fetch failed', cause: failure }); -}); - -/** A loopback server answering each path from `routes`, recording every request it gets. */ -async function serveRoutes(routes: Record, string?]>) { - const received: string[] = []; - const { origin } = await serveWith((req, res) => { - let body = ''; - req.on('data', (chunk) => (body += String(chunk))); - req.on('end', () => { - received.push( - [req.method, req.url, req.headers.authorization, req.headers['content-type'], body].join( - ' ', - ), - ); - const [status, headers, answer] = routes[req.url ?? ''] ?? [200, {}, 'done']; - res.writeHead(status, headers).end(answer); - }); - }); - return { origin, received }; -} - -const credentialPost = { - method: 'POST', - headers: { authorization: 'Bearer secret', 'content-type': 'text/plain' }, - body: 'payload', -}; - -test.each([ - [307, 'POST /moved Bearer secret text/plain payload'], - [308, 'POST /moved Bearer secret text/plain payload'], - [301, 'GET /moved Bearer secret '], - [303, 'GET /moved Bearer secret '], -])('a same-origin %i is followed as fetch would send it', async (status, followed) => { - const server = await serveRoutes({ '/start': [status, { location: '/moved' }] }); - - const response = await send(`${server.origin}/start`, credentialPost); - - expect(await response.text()).toBe('done'); - expect(server.received).toEqual(['POST /start Bearer secret text/plain payload', followed]); -}); - -test('a redirect off the origin is returned as the answer, and its target gets nothing', async () => { - const other = await serveRoutes({}); - const server = await serveRoutes({ - '/start': [307, { location: `${other.origin}/moved` }], - '/user': [307, { location: '//user:password@127.0.0.1/moved' }], - }); - - for (const path of ['/start', '/user']) { - expect((await send(`${server.origin}${path}`, credentialPost)).status).toBe(307); - } - expect(other.received).toEqual([]); -}); - -test('an https request redirected to plain http is returned, not followed', async () => { - const sent: string[] = []; - const response = await send('https://remote.example/start', credentialPost, { - send: async (input) => { - sent.push(String(input)); - return new Response(null, { - status: 307, - headers: { location: 'http://remote.example/start' }, - }); - }, - }); - - expect(response.status).toBe(307); - expect(sent).toEqual(['https://remote.example/start']); -}); - -test('a redirect loop ends after three hops, and a Request is sent once', async () => { - const server = await serveRoutes({ '/loop': [307, { location: '/loop' }] }); - - expect((await send(`${server.origin}/loop`)).status).toBe(307); - expect(server.received).toHaveLength(4); - - const once = await fetchWithCredential( - new Request(`${server.origin}/loop`), - {}, - { subject: 'x' }, - ); - expect(once.status).toBe(307); - expect(server.received).toHaveLength(5); -}); - -test.each(['http://10.0.0.7/start', 'http://[fd00::1]/start', 'not a url'])( - '%s is refused before any transport sees it', - async (url) => { - const transport = vi.fn(); - const request = vi.spyOn(http, 'request'); - - for (const options of [{}, { send: transport }]) { - await expect(send(url, credentialPost, options)).rejects.toMatchObject({ - details: { reason: 'insecure_credential_transport', dispatched: 'no' }, - }); - } - expect(transport).not.toHaveBeenCalled(); - expect(request).not.toHaveBeenCalled(); - }, -); - -/** Makes the resolver answer `localhost` with `address`, in both callback shapes. */ -function resolveLocalhostTo(address: string): void { - vi.spyOn(dns, 'lookup').mockImplementation((( - _hostname: string, - options: dns.LookupOptions, - callback: (...answer: unknown[]) => void, - ) => { - if (options.all) callback(null, [{ address, family: 4 }]); - else callback(null, address, 4); - }) as typeof dns.lookup); -} - -test('localhost that resolves off loopback receives nothing, on every direct agent', async () => { - const server = await serveRoutes({}); - const url = new URL(server.origin.replace('127.0.0.1', 'localhost')); - // `0.0.0.0` reaches this machine's listener and is not a loopback address. - resolveLocalhostTo('0.0.0.0'); - const refused = { details: { reason: 'insecure_credential_transport' } }; - - await expect(send(url.href, credentialPost)).rejects.toMatchObject(refused); - const requester = await loadNodeHttpRequester(url, { subject: 'Test URL' }); - for (const agent of [undefined, false as const]) { - await expect( - new Promise((resolve, reject) => { - const sent = requester.request( - { host: url.hostname, port: url.port, agent, headers: credentialPost.headers }, - resolve, - ); - sent.on('error', reject); - sent.end(); - }), - ).rejects.toMatchObject(refused); - } - expect(server.received).toEqual([]); -}); - -test('localhost that resolves to loopback is reached', async () => { - const server = await serveRoutes({}); - resolveLocalhostTo('127.0.0.1'); - - const response = await send(server.origin.replace('127.0.0.1', 'localhost')); - - expect(await response.text()).toBe('done'); -}); - -const PLAIN = 'compressed '.repeat(200); - -test.each([ - ['gzip', zlib.gzipSync(PLAIN)], - ['x-gzip', zlib.gzipSync(PLAIN)], - ['deflate', zlib.deflateSync(PLAIN)], - ['deflate', zlib.deflateRawSync(PLAIN)], - ['br', zlib.brotliCompressSync(PLAIN)], - ['gzip, br', zlib.brotliCompressSync(zlib.gzipSync(PLAIN))], -])('a %s answer is decoded, with the headers of the decoded body', async (encoding, bytes) => { - const { origin } = await serveWith((_req, res) => { - res.writeHead(200, { 'content-encoding': encoding, 'content-length': bytes.length }).end(bytes); - }); - - const response = await send(origin); - - expect(await response.text()).toBe(PLAIN); - expect(response.headers.get('content-encoding')).toBe(null); - expect(response.headers.get('content-length')).toBe(null); -}); - -test('a coding fetch does not decode is passed through with its headers', async () => { - const { origin } = await serveWith((_req, res) => { - res.writeHead(200, { 'content-encoding': 'compress', 'content-length': '5' }).end('bytes'); - }); - - const response = await send(origin); - - expect(await response.text()).toBe('bytes'); - expect(response.headers.get('content-encoding')).toBe('compress'); -}); - -test('a damaged compressed answer fails the read', async () => { - const { origin } = await serveWith((_req, res) => { - res.writeHead(200, { 'content-encoding': 'gzip' }).end('not gzip'); - }); - - await expect((await send(origin)).text()).rejects.toThrow(); -}); - -test('an abort during a compressed answer fails the read with its reason', async () => { - const { origin, closed } = await serveWith((_req, res) => { - res.writeHead(200, { 'content-encoding': 'gzip' }); - res.write(zlib.gzipSync(PLAIN).subarray(0, 20)); - }); - const controller = new AbortController(); - const reason = new Error('caller gave up'); - const pending = (await send(origin, { signal: controller.signal })).text(); - - controller.abort(reason); - - await expect(pending).rejects.toBe(reason); - await closed; -}); - -test('a CoreDevice tunnel request goes to the bracketed address through node:http', async () => { - const seen: string[] = []; - const standIn = await serveWith((req, res) => { - seen.push(`${req.method} ${req.url} ${req.headers.host} ${req.headers['content-length']}`); - res.end('{}'); - }); - const options: http.RequestOptions[] = []; - const request = http.request; - // No machine holds the tunnel address, so the connection is the stand-in's; the rest of the - // request is what `node:http` was given. - vi.spyOn(http, 'request').mockImplementation((( - asked: http.RequestOptions, - callback: (res: http.IncomingMessage) => void, - ) => { - options.push(asked); - return request( - { - ...asked, - agent: undefined, - createConnection: () => net.connect(Number(new URL(standIn.origin).port), '127.0.0.1'), - }, - callback, - ); - }) as typeof http.request); - - const response = await send( - 'http://[fd00::1]:8100/command', - { method: 'POST', body: 'tap' }, - { coreDeviceTunnel: true }, - ); - - expect(response.status).toBe(200); - expect(options).toMatchObject([{ host: 'fd00::1', port: '8100', path: '/command' }]); - expect(options[0]!.agent).toBe(await loadDirectHttpAgent()); - expect(seen).toEqual(['POST /command [fd00::1]:8100 3']); -}); diff --git a/packages/host-kit/src/direct-http.ts b/packages/host-kit/src/direct-http.ts deleted file mode 100644 index 5b4ac42716..0000000000 --- a/packages/host-kit/src/direct-http.ts +++ /dev/null @@ -1,355 +0,0 @@ -import type { LookupAddress } from 'node:dns'; -import type { Agent, IncomingMessage } from 'node:http'; -import type { LookupFunction } from 'node:net'; -import type { Duplex, Transform } from 'node:stream'; -import type { ReadableStream as WebReadableStream } from 'node:stream/web'; -import { - assertSecureCredentialTransport, - credentialTransportRefusal, - type CredentialTransportExceptions, -} from '@agent-device/contracts/credential-transport'; -import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; -import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; - -// The one way a credential leaves this process over HTTP: `fetchWithCredential`, and the agent and -// lookup it shares with the `node:http` and WebSocket senders. Loaded at send time by the code that -// sends a credential, never at module scope. - -/** - * Resolves a name to loopback addresses only. `localhost` is the one name a plain-http credential - * may name, and a resolver is free to answer it with any address. - */ -export const lookupLoopbackOnly: LookupFunction = (hostname, options, callback) => { - void import('node:dns').then(({ default: dns }) => { - dns.lookup(hostname, { ...options, all: true }, (error, addresses: LookupAddress[]) => { - if (error) return callback(error, []); - const loopback = addresses.filter(({ address }) => isLoopbackHostname(address)); - const [first] = loopback; - if (!first) { - const refusal = credentialTransportRefusal( - 'localhost resolves to no loopback address, so no credential is sent to it.', - ); - return callback(refusal, []); - } - if (options.all) callback(null, loopback); - else callback(null, first.address, first.family); - }); - }); -}; - -let directHttpAgent: Agent | undefined; - -/** - * The agent for a plain-http request that carries a credential: a direct connection that never - * routes through an environment proxy (`NODE_USE_ENV_PROXY` with `HTTP_PROXY`), which would read - * the credential in cleartext, and that connects a name only to a loopback address. A `fresh` agent - * opens its own connection instead of reusing a pooled one. - */ -export async function loadDirectHttpAgent(fresh = false): Promise { - const http = (await import('node:http')).default; - const options = { lookup: lookupLoopbackOnly }; - if (fresh) return new http.Agent(options); - directHttpAgent ??= new http.Agent({ - ...options, - keepAlive: true, - scheduling: 'lifo', - timeout: 5_000, - }); - return directHttpAgent; -} - -export const NULL_BODY_STATUSES: ReadonlySet = new Set([204, 205, 304]); - -export function isRedirectStatus(status: number): boolean { - return [301, 302, 303, 307, 308].includes(status); -} - -/** A `node:http` response's headers as Fetch `Headers`, repeated values kept in order. */ -export function responseHeadersOf(res: IncomingMessage): Headers { - const headers = new Headers(); - for (const [name, value] of Object.entries(res.headers)) { - if (value === undefined) continue; - for (const item of Array.isArray(value) ? value : [value]) headers.append(name, item); - } - return headers; -} - -// The silence `fetch` allows while it waits for response headers or the next body bytes. It -// replaces the agent's 5 s timeout, which is for pooled sockets and would end a long command. -const IDLE_TIMEOUT_MS = 300_000; - -const DIRECT_HTTP_REASONS = { - // A plain-http exchange with a loopback peer stayed silent for `details.timeoutMs`. - idleTimeout: { reason: 'direct_http_idle_timeout' }, -} as const satisfies ReasonTable<'remote connection'>; - -type Decoding = { - zlib: typeof import('node:zlib'); - Transform: typeof import('node:stream').Transform; -}; - -/** The decoders `fetch` applies for a `Content-Encoding`, or none when it names another coding. */ -function contentDecoders(decoding: Decoding, encoding: string | null): Transform[] { - const { zlib } = decoding; - // Flushes what has arrived, so a streamed answer is readable as it comes. - const options = { flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH }; - const codings = (encoding ?? '').toLowerCase().split(','); - const decoders = codings.reverse().map((coding) => { - switch (coding.trim()) { - case 'gzip': - case 'x-gzip': - return zlib.createGunzip(options); - case 'deflate': - return createDeflateDecoder(decoding, options); - case 'br': - return zlib.createBrotliDecompress({ flush: zlib.constants.BROTLI_OPERATION_FLUSH }); - default: - return undefined; - } - }); - return decoders.every((decoder) => decoder !== undefined) ? decoders : []; -} - -/** `deflate` is zlib-wrapped by the standard and raw from some servers; the first byte tells. */ -function createDeflateDecoder( - { zlib, Transform }: Decoding, - options: import('node:zlib').ZlibOptions, -): Transform { - let inflate: import('node:zlib').Inflate | undefined; - const decoder: Transform = new Transform({ - transform(chunk: Buffer, _encoding, done) { - if (!inflate) { - const wrapped = (chunk[0]! & 0x0f) === 0x08; - inflate = wrapped ? zlib.createInflate(options) : zlib.createInflateRaw(options); - inflate.on('data', (decoded) => decoder.push(decoded)); - inflate.on('error', (error) => decoder.destroy(error)); - } - inflate.write(chunk, () => done()); - }, - flush(done) { - if (!inflate) return done(); - inflate.once('end', () => done()); - inflate.end(); - }, - }); - return decoder; -} - -/** - * Sends one request over `node:http` with the direct agent. It never follows a redirect: a 3xx is - * returned as is, or fails the request that asks for `redirect: 'error'`. As with `fetch`, a gzip, - * deflate or br body is decoded, and a failed exchange rejects with `TypeError('fetch failed')` - * carrying the cause, except a typed refusal, which rejects as itself. An abort ends the exchange - * with the signal's reason, and five silent minutes end it with a `direct_http_idle_timeout` error: - * the call rejects with it, or after the response, the body read does. - * - * `request`'s own body is read whole, so the request declares its length. A `streamedBody` is piped - * instead, as it arrives, with the length the headers declare or else chunked. - */ -async function fetchOverDirectHttp( - request: Request, - streamedBody?: AsyncIterable, -): Promise { - const url = new URL(request.url); - // The module object itself, so a stubbed `request` is the one called. - const [{ default: http }, agent, { Readable, Transform, pipeline }, zlib] = await Promise.all([ - import('node:http'), - loadDirectHttpAgent(), - import('node:stream'), - import('node:zlib'), - ]); - // Taken over before anything can end the exchange, so that every way it fails releases it. A - // stream is destroyed or cancelled even while a read is pending, which the return of an async - // iterator over it would wait for. - const source = - streamedBody === undefined || streamedBody instanceof Readable - ? streamedBody - : streamedBody instanceof ReadableStream - ? Readable.fromWeb(streamedBody as WebReadableStream) - : Readable.from(streamedBody, { objectMode: false }); - source?.on('error', () => undefined); - const exchange = () => - new Promise((resolve, reject) => { - let response: IncomingMessage | undefined; - const fail = (cause: unknown) => - reject(cause instanceof AppError ? cause : new TypeError('fetch failed', { cause })); - const end = (reason: Error) => { - reject(reason); - response?.destroy(reason); - req.destroy(); - }; - const req = http.request( - { - host: url.hostname.replace(/^\[(.*)\]$/, '$1'), - port: url.port, - path: `${url.pathname}${url.search}`, - method: request.method, - headers: Object.fromEntries(request.headers), - agent, - timeout: IDLE_TIMEOUT_MS, - }, - (res) => { - response = res; - // The body stream reports an error to its reader; an unread body has no other listener. - res.on('error', () => undefined); - const status = res.statusCode ?? 502; - if (request.redirect === 'error' && isRedirectStatus(status)) { - res.destroy(); - fail(new Error('unexpected redirect')); - return; - } - const nullBody = request.method === 'HEAD' || NULL_BODY_STATUSES.has(status); - if (nullBody) res.resume(); - const headers = responseHeadersOf(res); - const decoders = nullBody - ? [] - : contentDecoders({ zlib, Transform }, headers.get('content-encoding')); - let body: IncomingMessage | Duplex = res; - if (decoders.length > 0) { - headers.delete('content-encoding'); - headers.delete('content-length'); - body = decoders.at(-1)!; - // Carries a failure or a cancellation between the socket and the reader. - pipeline([res, ...decoders], () => undefined); - } - resolve( - new Response(nullBody ? null : (Readable.toWeb(body) as ReadableStream), { - status, - statusText: res.statusMessage, - headers, - }), - ); - }, - ); - req.on('timeout', () => { - end( - new AppError('COMMAND_FAILED', 'Plain-http request timed out waiting for the peer', { - reason: DIRECT_HTTP_REASONS.idleTimeout.reason, - timeoutMs: IDLE_TIMEOUT_MS, - }), - ); - }); - const abort = () => end(request.signal.reason as Error); - request.signal.addEventListener('abort', abort, { once: true }); - // This listener also keeps `request` reachable while the exchange lives: its signal follows - // the caller's only that long. - req.once('close', () => request.signal.removeEventListener('abort', abort)); - req.on('error', fail); - if (source) { - source.on('error', (error) => { - fail(error); - req.destroy(); - }); - // Releases the source, and the file behind it, when the exchange ends first. - req.once('close', () => source.destroy()); - source.pipe(req); - return; - } - if (!request.body) { - req.end(); - return; - } - request.arrayBuffer().then( - (body) => req.end(Buffer.from(body)), - (error: unknown) => { - fail(error); - req.destroy(); - }, - ); - }); - try { - request.signal.throwIfAborted(); - return await exchange(); - } catch (error) { - source?.destroy(); - throw error; - } -} - -/** How many same-origin redirects a credential-bearing request follows. */ -const MAX_FOLLOWED_REDIRECTS = 3; - -export type CredentialSend = CredentialTransportExceptions & { - /** Names the setting a refusal is about. */ - subject: string; - /** The caller's own transport, which carries every request the rule admits. */ - send?: typeof fetch; -}; - -/** - * Sends a request that carries a credential, and is the only way to send one with Fetch semantics. - * Every URL it sends to meets the credential transport rule first. Plain http goes direct over - * `node:http`, never through an environment proxy; https goes through global `fetch`; an injected - * `send` replaces both. - * - * It never follows a redirect off the origin. A URL with `redirect: 'follow'`, the default, follows - * up to three redirects on the same origin, keeping method and body on a 307 or 308; any other - * redirect is returned as the answer. A `Request` is sent once. - */ -export async function fetchWithCredential( - input: string | URL | Request, - init: RequestInit, - { subject, send, ...exceptions }: CredentialSend, -): Promise { - const redirect = init.redirect ?? (input instanceof Request ? input.redirect : 'follow'); - let target = input; - let hop = init; - for (let followed = 0; ; followed += 1) { - const url = assertSecureCredentialTransport( - target instanceof Request ? target.url : target, - subject, - exceptions, - ); - const next = { ...hop, redirect: redirect === 'error' ? redirect : ('manual' as const) }; - const response = await sendOnce(target, next, send); - if (redirect !== 'follow' || target instanceof Request) return response; - const followedTo = - followed < MAX_FOLLOWED_REDIRECTS ? sameOriginHop(response, url, hop) : undefined; - if (!followedTo) return response; - await response.body?.cancel().catch(() => undefined); - [target, hop] = followedTo; - } -} - -async function sendOnce( - input: string | URL | Request, - init: RequestInit, - send: typeof fetch | undefined, -): Promise { - if (send) return await send(input, init); - const url = new URL(input instanceof Request ? input.url : input); - if (url.protocol !== 'http:') return await fetch(input, init); - const { body } = init; - if (!isStreamedBody(body)) return await fetchOverDirectHttp(new Request(input, init)); - return await fetchOverDirectHttp(new Request(input, { ...init, body: null }), body); -} - -/** - * The URL and request a redirect on the same origin leads to, as `fetch` would send it, or - * `undefined` for any other answer. A streamed body cannot be sent twice. - */ -function sameOriginHop( - response: Response, - from: URL, - init: RequestInit, -): [URL, RequestInit] | undefined { - if (!isRedirectStatus(response.status)) return undefined; - const location = response.headers.get('location'); - if (location === null) return undefined; - const url = URL.parse(location, from); - if (!url || url.origin !== from.origin || url.username || url.password) return undefined; - const method = (init.method ?? 'GET').toUpperCase(); - const becomesGet = - response.status === 303 - ? method !== 'GET' && method !== 'HEAD' - : response.status < 303 && method === 'POST'; - if (!becomesGet) return isStreamedBody(init.body) ? undefined : [url, init]; - const headers = new Headers(init.headers); - for (const name of ['content-type', 'content-length', 'content-encoding']) headers.delete(name); - return [url, { ...init, method: 'GET', body: null, headers }]; -} - -/** A body that arrives in pieces: a web or Node stream, or any other async iterable. */ -function isStreamedBody(body: unknown): body is AsyncIterable { - return typeof body === 'object' && body !== null && Symbol.asyncIterator in body; -} diff --git a/packages/host-kit/src/internal/transport.test.ts b/packages/host-kit/src/internal/transport.test.ts index baec8612f3..51dfd5420b 100644 --- a/packages/host-kit/src/internal/transport.test.ts +++ b/packages/host-kit/src/internal/transport.test.ts @@ -24,20 +24,9 @@ test('consumeTextLines trims complete lines and retains a partial line', () => { assert.equal(second.buffer, ''); }); -test.each(['http://10.0.0.7:4310', 'http://[fd00::1]:4310'])( - 'loadNodeHttpRequester refuses a credential to %s', - async (url) => { - await assert.rejects( - () => loadNodeHttpRequester(new URL(url), { subject: 'Test URL' }), - (error: unknown) => - error instanceof AppError && error.details?.reason === 'insecure_credential_transport', - ); - }, -); - test('loadNodeHttpRequester selects the protocol module and keeps request mutable', async () => { - const httpRequester = await loadNodeHttpRequester(new URL('http://127.0.0.1')); - const httpsRequester = await loadNodeHttpRequester(new URL('https://remote.example')); + const httpRequester = await loadNodeHttpRequester('http:'); + const httpsRequester = await loadNodeHttpRequester('https:'); assert.equal(httpRequester, http); assert.equal(httpsRequester, https); diff --git a/packages/host-kit/src/internal/transport.ts b/packages/host-kit/src/internal/transport.ts index bc06b4b800..99ba9455d2 100644 --- a/packages/host-kit/src/internal/transport.ts +++ b/packages/host-kit/src/internal/transport.ts @@ -1,6 +1,6 @@ import crypto from 'node:crypto'; import { types } from 'node:util'; -import type { ClientRequest, IncomingMessage, RequestOptions } from 'node:http'; +import type { ClientRequest, IncomingMessage } from 'node:http'; import type { Socket } from 'node:net'; import { AppError } from '@agent-device/kernel/errors'; @@ -37,34 +37,11 @@ export type NodeHttpRequester = Pick; * Resolves `.default`, not the namespace, so callers get the very same module * object a static `import http from 'node:http'` yields -- its `request` * property is mutable, which the transport tests rely on to stub requests. - * - * Pass `credential` for a request that carries one. `url` then meets the credential transport rule, - * and plain http connects directly, never through an environment proxy, and to `localhost` only at a - * loopback address. That requester is called as `request(options, callback)`, its only form, with - * the options of `url`. Its direct agent always replaces an `agent` among them, since another agent - * could send the credential through a proxy; `agent: false` asks for a connection of its own. It - * still calls the module's `request` at send time. */ -export async function loadNodeHttpRequester( - url: URL, - credential?: { subject: string }, -): Promise { - if (credential) { - const rule = await import('@agent-device/contracts/credential-transport'); - rule.assertSecureCredentialTransport(url, credential.subject); - } - if (url.protocol === 'https:') return (await import('node:https')).default; - const http = (await import('node:http')).default; - if (!credential) return http; - const { loadDirectHttpAgent } = await import('../direct-http.ts'); - const [pooled, fresh] = [await loadDirectHttpAgent(), await loadDirectHttpAgent(true)]; - return { - request: ((options: RequestOptions, callback?: (res: IncomingMessage) => void) => - http.request( - { ...options, agent: options.agent === false ? fresh : pooled }, - callback, - )) as NodeHttpRequester['request'], - }; +export async function loadNodeHttpRequester(protocol: string): Promise { + return protocol === 'https:' + ? (await import('node:https')).default + : (await import('node:http')).default; } export function readNodeHttpResponseBody( diff --git a/packages/platform-apple/src/core/runner-host.ts b/packages/platform-apple/src/core/runner-host.ts index 1bd046939f..72efa662ff 100644 --- a/packages/platform-apple/src/core/runner-host.ts +++ b/packages/platform-apple/src/core/runner-host.ts @@ -89,8 +89,6 @@ export const appleRunnerHost: AppleRunnerHost = { shellQuote, emitDiagnostic, withDiagnosticTimer, - fetchWithCredential: async (...args) => - await (await import('@agent-device/host-kit/direct-http')).fetchWithCredential(...args), retryWithPolicy, isEnvTruthy, deadlineFromTimeoutMs: (timeoutMs, nowMs) => Deadline.fromTimeoutMs(timeoutMs, nowMs), diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index 105cf40f43..673cb86700 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -1,8 +1,5 @@ import assert from 'node:assert/strict'; -import fs from 'node:fs/promises'; -import http from 'node:http'; -import type { AddressInfo } from 'node:net'; -import { test, vi } from 'vitest'; +import { test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; import { createRevylClient, @@ -25,49 +22,8 @@ test('uses the public Revyl backend when no URL is configured', () => { assert.equal(client.backendUrl, REVYL_DEFAULT_BACKEND_URL); }); -test('a loopback backend and upload URL are reached directly, never through global fetch', async () => { - const received: string[] = []; - const lengths: Array = []; - const server = http.createServer((req, res) => { - received.push(`${req.method} ${req.url} ${req.headers.authorization ?? ''}`.trim()); - if (req.method === 'PUT') lengths.push(req.headers['content-length']); - req.resume(); - req.on('end', () => res.end('{}')); - }); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); - const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; - const proxied = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); - try { - const client = createRevylClient({ - apiKey: 'test-key', - backendUrl: origin, - clientVersion: '0.0.0-test', - }); - await client.verifyCredentials(); - const { size } = await fs.stat(import.meta.filename); - await client.uploadSessionArtifact( - `${origin}/upload?signature=signed`, - { filePath: import.meta.filename, size }, - 'application/zip', - ); - // A presigned PUT declares its length even though the file is streamed. - assert.deepEqual(lengths, [String(size)]); - - assert.deepEqual(received, [ - 'GET /api/v1/entity/users/get_user_uuid Bearer test-key', - 'PUT /upload?signature=signed', - ]); - assert.equal(proxied.mock.calls.length, 0); - } finally { - proxied.mockRestore(); - server.closeAllConnections(); - await new Promise((resolve) => server.close(() => resolve())); - } -}); - test('a presigned upload URL over plain http off loopback receives nothing', async () => { - const sent: unknown[] = []; - const requestSpy = vi.spyOn(http, 'request'); + const sent: string[] = []; const client = createRevylClient({ apiKey: 'test-key', clientVersion: '0.0.0-test', @@ -76,22 +32,18 @@ test('a presigned upload URL over plain http off loopback receives nothing', asy return jsonResponse({}); }), }); - try { - 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, []); - assert.equal(requestSpy.mock.calls.length, 0); - } finally { - requestSpy.mockRestore(); - } + + 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', () => { diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index 84bcc94a0a..59f0c8b1e2 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -96,9 +96,6 @@ type RevylProviderReason = */ type RevylRoute = 'session' | 'general'; -/** Sends one request that carries the API key or a presigned URL. */ -type RevylTransmit = (url: string | URL, init: RequestInit) => Promise; - type RevylRequest = Readonly<{ method: 'GET' | 'POST'; path: string; @@ -179,10 +176,7 @@ export type RevylClient = Readonly<{ export function createRevylClient(options: RevylClientOptions): RevylClient { const backendUrl = resolveRevylBackendUrl(options.backendUrl ?? REVYL_DEFAULT_BACKEND_URL); - const transmit: RevylTransmit = async (url, init) => { - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); - return await fetchWithCredential(url, init, { subject: 'Revyl URL', send: options.fetch }); - }; + const fetchImpl = options.fetch ?? fetch; const baseHeaders = { Authorization: `Bearer ${options.apiKey}`, Accept: 'application/json', @@ -194,7 +188,7 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { const retry = request.retry ?? request.method === 'GET'; const attempts = retry ? RETRY_DELAYS_MS.length + 1 : 1; for (let attempt = 1; ; attempt += 1) { - const outcome = await sendOnce(backendUrl, transmit, baseHeaders, request); + const outcome = await sendOnce(backendUrl, fetchImpl, baseHeaders, request); if (!isRetryable(request, outcome) || attempt >= attempts || request.signal?.aborted) { if (outcome instanceof Error) throw outcome; return outcome; @@ -322,7 +316,7 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { }; let response: Response; try { - response = await transmit(uploadUrl, init); + response = await fetchImpl(uploadUrl, init); } catch (error) { throw new AppError( 'COMMAND_FAILED', @@ -369,7 +363,7 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { async function sendOnce( backendUrl: string, - transmit: RevylTransmit, + fetchImpl: typeof fetch, baseHeaders: Record, request: RevylRequest, ): Promise { @@ -379,7 +373,7 @@ async function sendOnce( if (request.workerAction) headers['X-Revyl-Agent'] = REVYL_ATTRIBUTION; if (request.body !== undefined) headers['Content-Type'] = 'application/json'; try { - const response = await transmit(new URL(request.path, backendUrl), { + const response = await fetchImpl(new URL(request.path, backendUrl), { method: request.method, headers, body: request.body === undefined ? undefined : JSON.stringify(request.body), diff --git a/packages/proxy/README.md b/packages/proxy/README.md index 9fadbf31f1..a48860d4a0 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -128,14 +128,14 @@ On these routes: Supply `upstreamFetch` if you need those Fetch behaviors or your own routing. -A plain-http upstream is loopback, and the default transport reaches it directly over `node:http` -on every route. An environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY=1`) never sees the -upstream token. As with `fetch`, such a request ends after five minutes of silence from the daemon -(transfer routes keep their own limits above). An https upstream follows your runtime's -environment-proxy settings: Node 26.11.1 uses them when `NODE_USE_ENV_PROXY=1`, and Bun 1.4.2 Fetch -uses them without that opt-in. +Environment-proxy routing depends on your runtime. In loopback checks, Node 22.12 ignores +`HTTP_PROXY` and `HTTPS_PROXY` for both transports. Node 26.11.1 uses them when +`NODE_USE_ENV_PROXY=1`. Bun 1.4.2 Fetch uses them without that opt-in, while the default transfer +transport requires it. On Node 26.11.1 and Bun 1.4.2, `NO_PROXY=127.0.0.1` bypasses the proxy. +If your Bun deployment needs proxy routing for transfers, set `NODE_USE_ENV_PROXY=1` or supply +`upstreamFetch`. -By default, `/rpc`, `/health` and request diagnostics to an https upstream use global `fetch`. +By default, `/rpc`, `/health` and request diagnostics use global `fetch`. ### Reach the daemon over your own transport @@ -229,7 +229,7 @@ authenticate: async (request) => { | `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`. | -| `upstreamFetch` | none | Sends one request to the daemon. Without it, transfer routes use `node:http(s)`, a plain-http upstream uses `node:http` on every route, and other routes use the global `fetch`. | +| `upstreamFetch` | none | Sends one request to the daemon. Without it, transfer routes use `node:http(s)` and every other route uses the global `fetch`. | | `maxRpcBodyBytes` | 64 MiB, the daemon's own request limit | Larger `/rpc` bodies get a 400 response. | | `upstreamTimeoutMs` | none | Independent cap on one daemon request, including its body. `/health` keeps its separate five-second limit. Without this option, other requests last as long as the client waits, bounded by the client's command timeout and, on transfer routes, the 600-second forwarding aggregate. | diff --git a/packages/proxy/src/checked-rpc-admission.ts b/packages/proxy/src/checked-rpc-admission.ts index ad738b9694..4e2b9f7028 100644 --- a/packages/proxy/src/checked-rpc-admission.ts +++ b/packages/proxy/src/checked-rpc-admission.ts @@ -13,7 +13,6 @@ import { DAEMON_HTTP_RPC_PROTOCOL_HEADER, DAEMON_RPC_PROTOCOL_VERSION, } from '@agent-device/contracts/daemon-http'; -import { isRedirectAnswer } from './upstream-response-relay.ts'; /** The most of an upstream refusal body the proxy reads for its bounded diagnostic values. */ const UPSTREAM_REFUSAL_MAX_BYTES = 64 * 1024; @@ -52,7 +51,10 @@ export async function localCheckedRpcRefusal( request: Request, rpcId: unknown, ): Promise { - if (isRedirectAnswer(upstreamResponse)) { + if ( + upstreamResponse.redirected || + (upstreamResponse.status >= 300 && upstreamResponse.status < 400) + ) { await upstreamResponse.body?.cancel(); throw new AppError('COMMAND_FAILED', 'The daemon answered a checked call with a redirect', { hint: 'The proxy never follows a redirect on the checked route. Point upstreamBaseUrl at the daemon itself.', diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts index d7f6422396..e0072965c0 100644 --- a/packages/proxy/src/daemon-proxy-cancellation.test.ts +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -243,93 +243,3 @@ test('aborting the client request after a garbage collection aborts a pending au await authenticateAborted.promise; expect((await response).status).toBe(500); }); - -/** - * A loopback daemon that takes a request and then stays quiet, after half an answer when `answers`. - * `closed` resolves when the proxy ends the exchange. - */ -async function quietDaemon(answers: 'nothing' | 'half') { - const received = signalled(); - const closed = signalled(); - const server = http.createServer((req, res) => { - res.on('close', closed.resolve); - req.resume().on('end', () => { - if (answers === 'half') res.writeHead(200).write('half'); - received.resolve(); - }); - }); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); - onTestFinished(async () => { - server.closeAllConnections(); - await new Promise((resolve) => server.close(() => resolve())); - }); - return { - url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, - received: received.promise, - closed: closed.promise, - }; -} - -/** A proxy that reaches `upstreamBaseUrl` with its own transport, over plain http. */ -function proxyOverPlainHttp(upstreamBaseUrl: string, upstreamTimeoutMs?: number) { - return createDaemonProxy({ - upstreamBaseUrl, - upstreamToken: 'daemon-secret', - clientToken: 'client-secret', - ...(upstreamTimeoutMs === undefined ? {} : { upstreamTimeoutMs }), - }); -} - -const plainRoutes = { - rpc: (signal?: AbortSignal) => - rpcRequest({ jsonrpc: '2.0', id: 3, method: 'agent-device.command' }, { signal }), - health: (signal?: AbortSignal) => new Request(`${PROXY_ORIGIN}/agent-device/health`, { signal }), - diagnostics: (signal?: AbortSignal) => - new Request(`${PROXY_ORIGIN}/agent-device/sessions/default/requests/ref-1/diagnostics`, { - headers: { authorization: 'Bearer client-secret' }, - signal, - }), -}; - -test.each([ - ['rpc', 'nothing'], - ['rpc', 'half'], - ['health', 'nothing'], - ['diagnostics', 'nothing'], - ['diagnostics', 'half'], -] as const)( - 'aborting the client %s request ends its plain-http exchange, with %s answered', - async (route, answers) => { - const daemon = await quietDaemon(answers); - const client = new AbortController(); - // Like an embedder, the test keeps its request while the proxy answers it. - const clientRequest = plainRoutes[route](client.signal); - const response = proxyOverPlainHttp(daemon.url).handle(clientRequest); - await daemon.received; - await collectGarbage(); - client.abort(); - - await daemon.closed; - await (await response).body?.cancel().catch(() => undefined); - }, -); - -// The health probe keeps its own five-second bound instead of `upstreamTimeoutMs`. -test.each([ - ['rpc', 'nothing'], - ['rpc', 'half'], - ['diagnostics', 'nothing'], - ['diagnostics', 'half'], -] as const)( - 'upstreamTimeoutMs ends a quiet plain-http %s exchange, with %s answered', - async (route, answers) => { - const daemon = await quietDaemon(answers); - const clientRequest = plainRoutes[route](); - const response = proxyOverPlainHttp(daemon.url, 50).handle(clientRequest); - await daemon.received; - await collectGarbage(); - - await daemon.closed; - await (await response).body?.cancel().catch(() => undefined); - }, -); diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index 72f7e2918e..6e880f01cc 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -2,7 +2,6 @@ // loopback, whatever transport carries it, and not to wherever an upstream redirect points. import { afterEach, expect, test, vi } from 'vitest'; -import dns from 'node:dns'; import http from 'node:http'; import https from 'node:https'; import type { AddressInfo } from 'node:net'; @@ -59,6 +58,12 @@ test.each([ 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) => { @@ -117,39 +122,30 @@ test.each([ }, ); -test('an upstream redirect is relayed, never followed, so its target receives no token', async () => { +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} ${req.headers['x-agent-device-token'] ?? ''}`); - req.resume(); + reached.push(`${req.method} ${req.url}`); res.end('{}'); }); const daemon = await serve((req, res) => { req.resume(); - res.statusCode = 307; - res.setHeader('location', `${target}/redirected`); - res.end(); + res.writeHead(307, { location: `${target}/redirected` }).end(); }); - // A logical https URL a transport routes internally: here, global fetch to a loopback daemon, - // with the forwarded request's method, headers, body, and redirect mode. const proxy = createDaemonProxy({ - upstreamBaseUrl: 'https://daemon.example.test', + upstreamBaseUrl: daemon, upstreamToken: 'daemon-secret', clientToken: 'client-secret', - upstreamFetch: async (request) => - await fetch(`${daemon}${new URL(request.url).pathname}`, { - method: request.method, - headers: request.headers, - redirect: request.redirect, - ...(request.method === 'GET' ? {} : { body: await request.text() }), - }), }); + const read = (path: string) => + new Request(`https://gateway.example.test/agent-device/${path}`, { + headers: { authorization: 'Bearer client-secret' }, + }); - const health = await proxy.handle( - new Request('https://gateway.example.test/agent-device/health'), - ); - expect(health.status).toBe(500); 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([]); }); @@ -182,7 +178,10 @@ test.each([ upstreamBaseUrl: 'https://daemon.example.test', upstreamToken: 'daemon-secret', clientToken: 'client-secret', - upstreamFetch: async () => new Response(null, { status: 307, headers: { location } }), + upstreamFetch: async (request) => { + expect(request.redirect).toBe('manual'); + return new Response(null, { status: 307, headers: { location } }); + }, }); for (const request of [ @@ -198,28 +197,6 @@ test.each([ }, ); -test.each([ - 'http://operator@daemon.example.test', - 'http://operator:hunter2@127.0.0.1:4310', - 'https://operator:hunter2@daemon.example.test', -])('%s is refused for its username whatever its scheme', async (upstreamBaseUrl) => { - const upstreamFetch = vi.fn(async () => Response.json({})); - const proxy = createDaemonProxy({ - upstreamBaseUrl, - upstreamToken: 'daemon-secret', - clientToken: 'client-secret', - upstreamFetch, - }); - - const response = await proxy.handle(rpc()); - - expect(response.status).toBe(400); - const refusal = await response.text(); - expect(refusal).toContain('proxy_upstream_userinfo'); - expect(refusal).not.toMatch(/operator|hunter2/); - expect(upstreamFetch).not.toHaveBeenCalled(); -}); - test('a relayed Location is dropped when its path holds the upstream token as written', async () => { // A token that reads differently once decoded: `a%2Fb` decodes to `a/b`. const proxy = createDaemonProxy({ @@ -236,36 +213,6 @@ test('a relayed Location is dropped when its path holds the upstream token as wr expect(response.headers.get('location')).toBe(null); }); -test('the default transports relay a daemon redirect with its target on every route', async () => { - const daemon = await serve((req, res) => { - req.resume(); - res.statusCode = 307; - res.setHeader('location', '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/artifacts/moved'); - res.end(); - }); - const proxy = createDaemonProxy({ - upstreamBaseUrl: daemon, - upstreamToken: 'daemon-secret', - clientToken: 'client-secret', - }); - - const transfer = await proxy.handle( - new Request('https://gateway.example.test/agent-device/artifacts/build', { - headers: { authorization: 'Bearer client-secret' }, - }), - ); - const command = await proxy.handle(rpc()); - - expect(transfer.status).toBe(307); - expect(transfer.headers.get('location')).toBe( - 'https://gateway.example.test/agent-device/artifacts/moved', - ); - expect(command.status).toBe(307); - expect(command.headers.get('location')).toBe( - 'https://gateway.example.test/agent-device/artifacts/moved', - ); -}); - test.each([ ['a 302 whose body claims health', () => Response.json({ ok: true }, { status: 302 })], [ @@ -287,38 +234,3 @@ test.each([ expect(response.status).toBe(500); expect(await response.json()).toMatchObject({ ok: false, code: 'COMMAND_FAILED' }); }); - -test('a default upstream on a localhost that resolves off loopback receives nothing', async () => { - const reached: string[] = []; - const daemon = await serve((req, res) => { - reached.push(`${req.method} ${req.url}`); - res.end('{}'); - }); - // `0.0.0.0` reaches this machine's listener and is not a loopback address. - vi.spyOn(dns, 'lookup').mockImplementation((( - _hostname: string, - options: dns.LookupOptions, - callback: (...answer: unknown[]) => void, - ) => { - if (options.all) callback(null, [{ address: '0.0.0.0', family: 4 }]); - else callback(null, '0.0.0.0', 4); - }) as typeof dns.lookup); - const proxy = createDaemonProxy({ - upstreamBaseUrl: daemon.replace('127.0.0.1', 'localhost'), - upstreamToken: 'daemon-secret', - clientToken: 'client-secret', - }); - - for (const request of [ - new Request('https://gateway.example.test/agent-device/health'), - new Request('https://gateway.example.test/agent-device/artifacts/build', { - headers: { authorization: 'Bearer client-secret' }, - }), - ]) { - const response = await proxy.handle(request); - expect(await response.json(), request.url).toMatchObject({ - reason: 'insecure_credential_transport', - }); - } - expect(reached).toEqual([]); -}); diff --git a/packages/proxy/src/daemon-proxy-transfer.test.ts b/packages/proxy/src/daemon-proxy-transfer.test.ts index 13429d7e4e..cf1a170978 100644 --- a/packages/proxy/src/daemon-proxy-transfer.test.ts +++ b/packages/proxy/src/daemon-proxy-transfer.test.ts @@ -285,9 +285,7 @@ test('a custom transport receives every route family including transfers', async ).toBe(true); }); -// A plain-http upstream is loopback, and it goes direct over Node on every route, so neither a -// patched global fetch nor an environment proxy sees its token. -test('a plain-http upstream takes Node on every admitted route, never the global fetch', async () => { +test('admitted transfers use Node while RPC and diagnostics use Fetch', async () => { const daemon = await listen( http.createServer((req, res) => { req.resume(); @@ -333,8 +331,8 @@ test('a plain-http upstream takes Node on every admitted route, never the global ); expect(response.status, path).toBe(200); await response.text(); - expect(node.mock.calls.length, `${path} transfer=${transfer}`).toBe(1); - expect(fetch.mock.calls.length, path).toBe(0); + expect(node.mock.calls.length, path).toBe(transfer ? 1 : 0); + expect(fetch.mock.calls.length, path).toBe(transfer ? 0 : 1); } for (const [method, path] of [ ['GET', '/upload'], diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 38ad92df79..e6cb4169d2 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -32,13 +32,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; plain http goes direct, never through an environment - * proxy. Supply your own to reach the daemon over another 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 to its client, which applies its own redirect rules. - * 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. + * `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. 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 to its + * client, which applies its own redirect rules. 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. * On transfer routes, the proxy bounds its own response and body waits, even if the transport @@ -369,8 +369,8 @@ async function readUpstreamHealth( signal, }), ); - const { isRedirectAnswer } = await import('./upstream-response-relay.ts'); - if (isRedirectAnswer(response)) { + // 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.', @@ -583,13 +583,8 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti (upstreamAdmission ??= import('./upstream-admission.ts').then(({ assertAdmittedUpstream }) => { assertAdmittedUpstream(upstreamBaseUrl); })); + const upstreamFetch = options.upstreamFetch ?? ((request) => fetch(request)); const customUpstreamFetch = options.upstreamFetch; - const upstreamFetch: DaemonProxyUpstreamFetch = - customUpstreamFetch ?? - (async (request) => { - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); - return await fetchWithCredential(request, {}, { subject: 'Proxy upstreamBaseUrl' }); - }); return { upstreamBaseUrl, publicOrigin: diff --git a/packages/proxy/src/transfer-transport.ts b/packages/proxy/src/transfer-transport.ts index 1df1635812..cd29348c5f 100644 --- a/packages/proxy/src/transfer-transport.ts +++ b/packages/proxy/src/transfer-transport.ts @@ -11,7 +11,6 @@ import { TRANSFER_RESPONSE_HEADER_TIMEOUT_MS, type TransferPhaseWatchdog, } from '@agent-device/host-kit/transport'; -import { NULL_BODY_STATUSES, responseHeadersOf } from '@agent-device/host-kit/direct-http'; const PROXY_TRANSFER_AGGREGATE_MS = 600_000; @@ -24,8 +23,9 @@ const TRANSFER_FORWARDING_REASONS = { // The upstream daemon closed the connection before it answered, or during a write. upstreamClosed: { reason: 'transfer_upstream_closed' }, } as const satisfies ReasonTable<'proxy'>; +const NULL_BODY_STATUSES = new Set([204, 205, 304]); -/** Forwards one exchange over `node:http(s)`, without redirects or retries; plain http goes direct. */ +/** Forwards one exchange over the runtime's default global Node agent, without redirects or retries. */ export function createNodeTransferFetch(): (request: Request) => Promise { return async (request) => { const exchange = openExchange(request.signal); @@ -141,10 +141,7 @@ async function exchangeOverNodeHttp( ): Promise { const url = new URL(request.url); const [transport, { urlToHttpOptions }] = await untilAborted(exchange.signal, () => - Promise.all([ - loadNodeHttpRequester(url, { subject: 'Proxy upstreamBaseUrl' }), - import('node:url'), - ]), + Promise.all([loadNodeHttpRequester(url.protocol), import('node:url')]), ); exchange.signal.throwIfAborted(); const { auth: _auth, ...target } = urlToHttpOptions(url); @@ -208,7 +205,11 @@ async function exchangeOverNodeHttp( answered = true; outgoingStopped.abort(); exchange.watchdog.suspend(); - const headers = responseHeadersOf(res); + const headers = new Headers(); + for (const [name, value] of Object.entries(res.headers)) { + if (value === undefined) continue; + for (const item of Array.isArray(value) ? value : [value]) headers.append(name, item); + } if (request.method === 'HEAD' || NULL_BODY_STATUSES.has(status)) { res.resume(); void responseClosed.then(finish); diff --git a/packages/proxy/src/upstream-response-relay.ts b/packages/proxy/src/upstream-response-relay.ts index 19dff84ab2..26d4aa1ee7 100644 --- a/packages/proxy/src/upstream-response-relay.ts +++ b/packages/proxy/src/upstream-response-relay.ts @@ -28,11 +28,6 @@ export type RelayedResponse = { publicOrigin: string | undefined; }; -/** Whether the upstream answered with a redirect, or its transport reports that it followed one. */ -export function isRedirectAnswer(response: Response): boolean { - return response.redirected || (response.status >= 300 && response.status < 400); -} - /** The headers a proxied response carries: the allowlist, the request id, and a safe `Location`. */ export function relayedResponseHeaders(relay: RelayedResponse): Headers { const headers = new Headers(); diff --git a/packages/react-native/package.json b/packages/react-native/package.json index 127fa39687..e2a2bae199 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -17,7 +17,6 @@ } }, "devDependencies": { - "@agent-device/test-kit": "workspace:*", - "undici": "7.30.1" + "@agent-device/test-kit": "workspace:*" } } diff --git a/packages/react-native/src/companion/client-companion-local-relay.ts b/packages/react-native/src/companion/client-companion-local-relay.ts index a99a8de7df..75aca04f3d 100644 --- a/packages/react-native/src/companion/client-companion-local-relay.ts +++ b/packages/react-native/src/companion/client-companion-local-relay.ts @@ -1,11 +1,8 @@ -import net from 'node:net'; -import { isSecureCredentialDestination } from '@agent-device/contracts/credential-transport'; -import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; +import { fetchWithCredential } 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, -// and the sockets it opens itself. +// 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 = [ @@ -28,48 +25,9 @@ export function relayTarget(localBaseUrl: string, requestPath: string): URL { return target; } -/** - * Sends one request the bridge relays to the local dev server. One that carries a credential, or - * goes where a credential may, goes through `fetchWithCredential`: every URL checked, loopback - * direct, redirects on the same origin only. Any other uses global `fetch`. - */ +/** Sends one relayed request. One that carries a credential meets the credential transport rule. */ export async function fetchRelayedRequest(target: URL, init: RequestInit): Promise { const headers = new Headers(init.headers); - const credentialed = CREDENTIAL_HEADERS.some((name) => headers.has(name)); - if (!credentialed && !isSecureCredentialDestination(target)) return await fetch(target, init); - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); + if (!CREDENTIAL_HEADERS.some((name) => headers.has(name))) return await fetch(target, init); return await fetchWithCredential(target, init, { subject: 'Metro companion local base URL' }); } - -/** - * Opens the companion's sockets. A plain socket to loopback connects directly, because the global - * `WebSocket` hands its URL to an environment proxy, and to `localhost` only at a loopback address. - * Every other socket is the global `WebSocket`. - */ -export async function createCompanionSocketDialer() { - const [{ Agent, WebSocket: DirectWebSocket }, { lookupLoopbackOnly }] = await Promise.all([ - import('undici'), - import('@agent-device/host-kit/direct-http'), - ]); - const agent = new Agent({ connect: { lookup: lookupLoopbackOnly } }); - const plainLoopback = (url: URL) => - (url.protocol === 'ws:' || url.protocol === 'http:') && isLoopbackHostname(url.hostname); - return { - /** Refuses a name that resolves off this machine here, where the refusal stays typed. */ - async verify(url: string): Promise { - const destination = new URL(url); - const host = destination.hostname.replace(/^\[(.*)\]$/, '$1'); - if (!plainLoopback(destination) || net.isIP(host)) return; - await new Promise((resolve, reject) => { - lookupLoopbackOnly(host, { all: true }, (error) => (error ? reject(error) : resolve())); - }); - }, - open(url: string): WebSocket { - if (!plainLoopback(new URL(url))) return new WebSocket(url); - return new DirectWebSocket(url, { dispatcher: agent }) as unknown as WebSocket; - }, - close: async (): Promise => await agent.destroy(), - }; -} - -export type CompanionSocketDialer = Awaited>; 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 index 65db60381e..684615e08c 100644 --- 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 @@ -1,9 +1,8 @@ -// The companion's bearer token and its bridge socket URL never leave this machine in cleartext: not -// to a plain destination off loopback, and not through an environment proxy. +// 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 dns from 'node:dns'; import { once } from 'node:events'; import fs from 'node:fs'; import http from 'node:http'; @@ -65,25 +64,18 @@ function startWorker(serverBaseUrl: string, localBaseUrl = 'http://127.0.0.1:1') } /** - * A socket taken from an HTTP server on `upgrade` or `connect` 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. + * 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); } -/** Where a registration path moved: a constant, never a value taken from the request. */ -function movedTo(path: string | undefined): string | undefined { - if (path === REGISTER_PATH) return `${REGISTER_PATH}/moved`; - if (path === UNREGISTER_PATH) return `${UNREGISTER_PATH}/moved`; - return undefined; -} - /** * A loopback bridge whose registration answers `wsUrl(port)`, recording what reaches it and what - * the companion sends on the socket. `moved` redirects each registration path once. + * the companion sends on the socket. */ -async function listenBridge(wsUrl: (port: number) => string, moved = false) { +async function listenBridge(wsUrl: (port: number) => string) { const received: string[] = []; let upgrade!: (socket: Duplex) => void; const upgraded = new Promise((resolve) => (upgrade = resolve)); @@ -93,11 +85,6 @@ async function listenBridge(wsUrl: (port: number) => string, moved = false) { const server = http.createServer((req, res) => { received.push(`${req.url} ${req.headers.authorization}`); req.resume(); - const location = moved ? movedTo(req.url) : undefined; - if (location) { - res.writeHead(307, { location }).end(); - return; - } res.end(JSON.stringify({ ok: true, data: { ws_url: wsUrl(port) } })); }); server.on('upgrade', (req, socket) => { @@ -125,38 +112,19 @@ 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', 'http:', 'https://', 'https:'])( +test.for(['http://bridge.invalid', 'https://'])( 'the worker never sends its bearer token to %s and exits', async (serverBaseUrl) => { - const sent: unknown[] = []; - vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { - sent.push(input); - return new Response(null, { status: 401 }); - }); - vi.spyOn(http, 'request').mockImplementation(((target: unknown) => { - sent.push(target); - throw new Error('nothing may be sent'); - }) as typeof http.request); + const send = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValue(new Response(null, { status: 401 })); await assert.rejects(startWorker(serverBaseUrl).done, isCredentialTransportRefusal); - assert.deepEqual(sent, []); + assert.equal(send.mock.calls.length, 0); }, ); -test('the worker reaches a loopback bridge directly, never through global fetch', async () => { - const bridge = await listenBridge((port) => `ws://127.0.0.1:${port}/bridge`); - const proxied = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); - const worker = startWorker(bridge.origin); - - (await bridge.upgraded).destroy(); - await worker.stop(); - - assert.equal(bridge.received[0], registered); - assert.ok(bridge.received.includes(unregistered), `${bridge.received}`); - assert.equal(proxied.mock.calls.length, 0); -}); - /** A TCP listener that records every connection, whatever protocol its caller speaks. */ async function listenSink() { const connections: unknown[] = []; @@ -170,13 +138,11 @@ async function listenSink() { } // `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` or `https` on loopback, which a -// `WebSocket` accepts. +// 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) => `ws://0.0.0.0:${port}/bridge`, (port: number) => `http://127.0.0.1:${port}/bridge?ticket=secret`, - (port: number) => `https://127.0.0.1:${port}/bridge`, ])('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)); @@ -187,9 +153,9 @@ test.for([ assert.deepEqual(bridge.received, [registered, unregistered]); }); -/** Runs the worker as its own process against `origin`, with `env` over this one's. */ -function spawnWorker(origin: string, env: NodeJS.ProcessEnv = {}) { - const child = spawn( +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', @@ -199,99 +165,29 @@ function spawnWorker(origin: string, env: NodeJS.ProcessEnv = {}) { { env: { ...process.env, - [ENV_COMPANION_TUNNEL_SERVER_BASE_URL]: origin, + [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', - ...env, }, stdio: 'ignore', }, ); - const exited = once(child, 'exit'); + const exited = once(worker, 'exit'); cleanupTasks.push(async () => { - child.kill('SIGKILL'); + worker.kill('SIGKILL'); await exited; }); - return exited; -} - -test('the worker opens a loopback socket around an environment proxy', async () => { - const proxied: string[] = []; - const proxy = http.createServer((req, res) => { - proxied.push(`${req.method} ${req.url}`); - res.writeHead(502).end(); - }); - for (const event of ['upgrade', 'connect'] as const) { - proxy.on(event, (req: http.IncomingMessage, socket: Duplex) => { - tolerateReset(socket); - proxied.push(`${event} ${req.url}`); - socket.destroy(); - }); - } - cleanupTasks.push(() => closeLoopbackServer(proxy)); - const proxyUrl = `http://127.0.0.1:${await listenOnLoopback(proxy)}`; - const bridge = await listenBridge((port) => `ws://127.0.0.1:${port}/bridge?ticket=secret`); - - // Node reads `NODE_USE_ENV_PROXY` at startup, so this worker runs as its own process. - const exited = spawnWorker(bridge.origin, { - NODE_USE_ENV_PROXY: '1', - HTTP_PROXY: proxyUrl, - http_proxy: proxyUrl, - NO_PROXY: '', - no_proxy: '', - }); - - await Promise.race([ - bridge.upgraded, - exited.then(() => assert.fail('the worker exited before it opened the bridge socket')), - ]); - assert.deepEqual(bridge.received, [registered, 'UPGRADE /bridge?ticket=secret']); - assert.deepEqual(proxied, []); -}); - -test('a refused socket URL ends the worker process as failed', async () => { - const bridge = await listenBridge(() => 'ws://0.0.0.0:1/bridge'); - - const [exitCode] = await spawnWorker(bridge.origin); + const [exitCode] = await exited; assert.equal(exitCode, 1); assert.deepEqual(bridge.received, [registered]); }); -test('a bridge socket on a localhost that resolves off loopback never opens', async () => { - const bridge = await listenBridge((port) => `ws://localhost:${port}/bridge?ticket=secret`); - // `0.0.0.0` reaches this machine's listener and is not a loopback address. - vi.spyOn(dns, 'lookup').mockImplementation((( - _hostname: string, - options: dns.LookupOptions, - callback: (...answer: unknown[]) => void, - ) => { - if (options.all) callback(null, [{ address: '0.0.0.0', family: 4 }]); - else callback(null, '0.0.0.0', 4); - }) as typeof dns.lookup); - - await assert.rejects(startWorker(bridge.origin).done, isCredentialTransportRefusal); - - assert.deepEqual(bridge.received, [registered, unregistered]); -}); - -test('registration and unregistration follow a same-origin redirect with the token', async () => { - const bridge = await listenBridge((port) => `ws://127.0.0.1:${port}/bridge`, true); - const worker = startWorker(bridge.origin); - - (await bridge.upgraded).destroy(); - await worker.stop(); - - for (const path of [REGISTER_PATH, UNREGISTER_PATH]) { - assert.ok(bridge.received.includes(`${path}/moved Bearer test-token`), `${bridge.received}`); - } -}); - /** A server recording the credential headers of each request that reaches it. */ async function listenLocalServer(location?: () => string) { const received: string[] = []; @@ -353,18 +249,14 @@ test.each([ assert.deepEqual(local.received, ['/index.bundle -']); }); -test('a relayed credential reaches loopback directly and stays on its origin', async () => { +test('a relayed credential stays on the origin of the local base URL', async () => { const other = await listenLocalServer(); - const local = await listenLocalServer(() => `http://0.0.0.0:${other.port}/redirected`); + const local = await listenLocalServer(() => `${other.origin}/redirected`); const bridge = await relayingBridge(local.origin); - const proxied = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); - const direct = await bridge.relay(httpRequest('/secret', { cookie: 'session=app' })); const redirected = await bridge.relay(httpRequest('/redirect', { cookie: 'session=app' })); - assert.equal(direct.status, 200); assert.equal(redirected.status, 307); - assert.deepEqual(local.received, ['/secret session=app', '/redirect session=app']); + assert.deepEqual(local.received, ['/redirect session=app']); assert.deepEqual(other.received, []); - assert.equal(proxied.mock.calls.length, 0); }); 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 a8d1be5b8f..8cfe43b8f9 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.ts @@ -26,14 +26,10 @@ import { normalizeBaseUrl } from '../metro/base-url.ts'; import { assertSecureCredentialSocket, assertSecureCredentialTransport, + fetchWithCredential, isCredentialTransportRefusal, } from '@agent-device/contracts/credential-transport'; -import { - createCompanionSocketDialer, - fetchRelayedRequest, - relayTarget, - type CompanionSocketDialer, -} from './client-companion-local-relay.ts'; +import { fetchRelayedRequest, relayTarget } from './client-companion-local-relay.ts'; const COMPANION_REGISTER_TIMEOUT_MS = 5_000; const BRIDGE_URL_SUBJECT = 'Metro companion bridge URL'; @@ -94,7 +90,6 @@ async function registerCompanion( ): Promise<{ wsUrl: string }> { const registerPath = resolveRegisterPath(options); const registerUrl = bearerDestination(options.serverBaseUrl, registerPath); - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); let response: Response; try { response = await fetchWithCredential( @@ -206,7 +201,6 @@ async function unregisterCompanion(options: CompanionTunnelWorkerOptions): Promi if (!unregisterPath) return; try { const unregisterUrl = bearerDestination(options.serverBaseUrl, unregisterPath); - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); await fetchWithCredential( unregisterUrl, { @@ -354,7 +348,6 @@ async function handleBridgeWebSocketOpen( message: Extract, options: CompanionTunnelWorkerOptions, upstreamSockets: Map, - dialer: CompanionSocketDialer, ): Promise { const refuse = (error: unknown) => sendJson(bridgeSocket, { @@ -365,7 +358,7 @@ async function handleBridgeWebSocketOpen( }); let upstreamSocket: WebSocket; try { - upstreamSocket = dialer.open(toUpstreamWebSocketUrl(options.localBaseUrl, message.path)); + upstreamSocket = new WebSocket(toUpstreamWebSocketUrl(options.localBaseUrl, message.path)); } catch (error) { refuse(error); return; @@ -447,7 +440,6 @@ async function handleBridgeMessage( message: MetroCompanionRequest, options: CompanionTunnelWorkerOptions, upstreamSockets: Map, - dialer: CompanionSocketDialer, ): Promise { switch (message.type) { case 'ping': { @@ -459,7 +451,7 @@ async function handleBridgeMessage( return; } case 'ws-open': { - await handleBridgeWebSocketOpen(bridgeSocket, message, options, upstreamSockets, dialer); + await handleBridgeWebSocketOpen(bridgeSocket, message, options, upstreamSockets); return; } case 'ws-frame': { @@ -527,7 +519,6 @@ export async function runCompanionTunnelWorker( }, runtime.leaseCheckIntervalMs ?? COMPANION_TUNNEL_LEASE_CHECK_INTERVAL_MS); lifetimeHandle.unref(); let registerRetryDelayMs = runtime.reconnectDelayMs ?? COMPANION_TUNNEL_RECONNECT_DELAY_MS; - const dialer = await createCompanionSocketDialer(); try { while (!shutdownRequested && shouldKeepWorkerRunning(options)) { let registered = false; @@ -540,13 +531,12 @@ export async function runCompanionTunnelWorker( activeRegistrationComplete = true; // The registered URL is what admits this companion to the bridge. assertSecureCredentialSocket(registration.wsUrl, 'Metro companion bridge socket URL'); - await dialer.verify(registration.wsUrl); if (shutdownRequested || !shouldKeepWorkerRunning(options)) { await unregisterActiveRegistration(); registered = false; break; } - const bridgeSocket = dialer.open(registration.wsUrl); + const bridgeSocket = new WebSocket(registration.wsUrl); activeBridgeSocket = bridgeSocket; bridgeSocket.binaryType = 'arraybuffer'; try { @@ -554,7 +544,7 @@ export async function runCompanionTunnelWorker( bridgeSocket.addEventListener('message', (event) => { void (async () => { const message = await parseBridgeMessage(event); - await handleBridgeMessage(bridgeSocket, message, options, upstreamSockets, dialer); + await handleBridgeMessage(bridgeSocket, message, options, upstreamSockets); })().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); }); @@ -601,7 +591,6 @@ export async function runCompanionTunnelWorker( process.off('SIGTERM', requestShutdown); process.off('SIGINT', requestShutdown); } - await dialer.close(); } } diff --git a/packages/react-native/src/index-metro.test.ts b/packages/react-native/src/index-metro.test.ts index 717ec756f1..fa64379eeb 100644 --- a/packages/react-native/src/index-metro.test.ts +++ b/packages/react-native/src/index-metro.test.ts @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { once } from 'node:events'; import { createHash } from 'node:crypto'; import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import http, { createServer } from 'node:http'; +import { createServer } from 'node:http'; import path from 'node:path'; import { prepareMetroRuntime, reloadMetro } from './index.ts'; import { AppError } from '@agent-device/kernel/errors'; @@ -426,7 +426,6 @@ test.for(['http://proxy.example.test', 'http:'])( 'prepareMetroRuntime never sends a bridge bearer token to %s', async (proxyBaseUrl) => { const fetchSpy = vi.spyOn(globalThis, 'fetch'); - const requestSpy = vi.spyOn(http, 'request'); try { await assert.rejects( () => @@ -442,10 +441,8 @@ test.for(['http://proxy.example.test', 'http:'])( error instanceof AppError && error.details?.reason === 'insecure_credential_transport', ); assert.equal(fetchSpy.mock.calls.length, 0); - assert.equal(requestSpy.mock.calls.length, 0); } finally { fetchSpy.mockRestore(); - requestSpy.mockRestore(); } }, ); 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 d5c7d5c5fd..33bbb9aa84 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,6 @@ import { afterEach, test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; -import http from 'node:http'; -import type { AddressInfo } from 'node:net'; import path from 'node:path'; import { mkdtempForTestSync, createTestHostEnvironment } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; @@ -552,61 +550,3 @@ test('prepareMetroRuntime retries malformed retryable bridge responses after com fs.rmSync(tempRoot, { recursive: true, force: true }); } }); - -test('a loopback bridge gets the bearer token directly, never through global fetch', async () => { - const projectRoot = mkdtempForTestSync('agent-device-metro-direct-bridge-'); - fs.mkdirSync(path.join(projectRoot, 'node_modules')); - fs.writeFileSync( - path.join(projectRoot, 'package.json'), - JSON.stringify({ name: 'direct-bridge', dependencies: { 'react-native': '0.0.0-test' } }), - ); - const received: string[] = []; - const bridge = http.createServer((req, res) => { - let body = ''; - req.on('data', (chunk) => (body += String(chunk))); - req.on('end', () => { - received.push( - `${req.method} ${req.url} ${req.headers.authorization} ${JSON.parse(body).tenantId}`, - ); - // The bridge moved its route: the POST follows on the same origin, with body and bearer. - if (req.url === '/api/metro/bridge') { - res.writeHead(307, { location: '/api/metro/bridge/v2' }).end(); - return; - } - res.writeHead(401).end('{"ok":false}'); - }); - }); - await new Promise((resolve) => bridge.listen(0, '127.0.0.1', resolve)); - // The dev server probe carries no credential and stays on global fetch. - const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => { - return new Response('packager-status:running'); - }); - vi.stubGlobal('fetch', fetchMock); - - try { - await assert.rejects(() => - prepareMetroRuntime( - { - projectRoot, - proxyBaseUrl: `http://127.0.0.1:${(bridge.address() as AddressInfo).port}`, - proxyBearerToken: 'shared-token', - bridgeScope: TEST_BRIDGE_SCOPE, - metroPort: 8081, - reuseExisting: true, - installDependenciesIfNeeded: false, - }, - createTestHostEnvironment(), - ), - ); - - assert.deepEqual(received, [ - 'POST /api/metro/bridge Bearer shared-token tenant-1', - 'POST /api/metro/bridge/v2 Bearer shared-token tenant-1', - ]); - assert.equal(JSON.stringify(fetchMock.mock.calls).includes('shared-token'), false); - } finally { - vi.unstubAllGlobals(); - bridge.closeAllConnections(); - await new Promise((resolve) => bridge.close(() => resolve())); - } -}); diff --git a/packages/react-native/src/metro/client-metro.ts b/packages/react-native/src/metro/client-metro.ts index 382a8bec9b..27882ca527 100644 --- a/packages/react-native/src/metro/client-metro.ts +++ b/packages/react-native/src/metro/client-metro.ts @@ -23,7 +23,7 @@ import { import { sleep } from '@agent-device/host-kit/retry'; import { assertSecureCredentialTransport, - isCredentialTransportRefusal, + fetchWithCredential, } from '@agent-device/contracts/credential-transport'; import { ensureMetroCompanion } from '../companion/client-metro-companion.ts'; import type { @@ -458,7 +458,6 @@ function isRetryableBridgeError(error: unknown): boolean { async function configureMetroBridge(input: ProxyBridgeRequestOptions): Promise { const bridgeUrl = `${input.baseUrl}/api/metro/bridge`; - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); let response: Response; try { @@ -477,7 +476,6 @@ async function configureMetroBridge(input: ProxyBridgeRequestOptions): Promise ({ - send: undefined as ((request: Request) => Promise) | undefined, -})); -vi.mock('@agent-device/host-kit/direct-http', async (importOriginal) => { - const actual = await importOriginal(); - const fetchWithCredential: typeof actual.fetchWithCredential = async (input, init, options) => - directHttp.send - ? await directHttp.send(new Request(input, init)) - : await actual.fetchWithCredential(input, init, options); - return { ...actual, fetchWithCredential: vi.fn(fetchWithCredential) }; -}); - const TEST_TOKEN = 'agent-device-upload-cancel-token'; const tempDirs: string[] = []; afterEach(async () => { - directHttp.send = undefined; vi.restoreAllMocks(); vi.useRealTimers(); for (const dir of tempDirs) { @@ -52,8 +37,6 @@ test('cancellation refuses preparation before it reads a missing artifact', asyn const reason = new Error('request owner stopped'); control.abort(reason); const fetch = vi.spyOn(globalThis, 'fetch'); - const direct = vi.fn(async () => new Response(null, { status: 500 })); - directHttp.send = direct; await assert.rejects( uploadArtifact({ env: process.env, @@ -65,7 +48,6 @@ test('cancellation refuses preparation before it reads a missing artifact', asyn (error: unknown) => error === reason, ); assert.equal(fetch.mock.calls.length, 0); - assert.equal(direct.mock.calls.length, 0); }); test('a standalone upload expires its preparation aggregate during hashing without starting a request', async () => { @@ -74,8 +56,6 @@ test('a standalone upload expires its preparation aggregate during hashing witho const hashSource = new PassThrough(); vi.spyOn(fs, 'createReadStream').mockReturnValue(hashSource as unknown as fs.ReadStream); const fetch = vi.spyOn(globalThis, 'fetch'); - const direct = vi.fn(async () => new Response(null, { status: 500 })); - directHttp.send = direct; const outcome = uploadArtifact({ env: process.env, localPath: artifactPath, @@ -93,8 +73,6 @@ test('a standalone upload expires its preparation aggregate during hashing witho }); assert.equal(hashSource.destroyed, true); assert.equal(fetch.mock.calls.length, 0); - assert.equal(direct.mock.calls.length, 0); - assert.equal(direct.mock.calls.length, 0); } finally { hashSource.destroy(); await outcome; @@ -138,13 +116,12 @@ test.each([ let stalledSignal: AbortSignal | undefined; let preflights = 0; let refuseStall: ((error: Error) => void) | undefined; - let controlRequests = 0; - directHttp.send = async (request) => { - controlRequests += 1; - const route = new URL(request.url).pathname; + const fetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + const route = new URL(String(input)).pathname; if (route.endsWith('/preflight')) preflights += 1; if (route.endsWith('/' + phase) && (!retry || preflights === 2)) { - const signal = request.signal; + const signal = init?.signal; + assert.ok(signal); stalledSignal = signal; entered(); if (prose) throw new Error(`Artifact transfer ${phase} timed out`); @@ -158,7 +135,7 @@ test.each([ uploadId: 'control-upload', upload: { url: `${server.baseUrl}/ticket`, headers: {} }, }); - }; + }); const outcome = observeOutcome( uploadArtifact({ env: process.env, @@ -204,7 +181,7 @@ test.each([ routes, Array.from({ length: expectedTicketLegs }, () => 'PUT /ticket'), ); - assert.equal(controlRequests, 1 + expectedTicketLegs); + assert.equal(fetch.mock.calls.length, 1 + expectedTicketLegs); } finally { caller.abort(new Error('fixture cleanup')); refuseStall?.(new Error('fixture cleanup')); diff --git a/packages/remote/src/artifact-download.ts b/packages/remote/src/artifact-download.ts index 3e41f13fed..9d33ac57e1 100644 --- a/packages/remote/src/artifact-download.ts +++ b/packages/remote/src/artifact-download.ts @@ -159,9 +159,7 @@ async function requestRemoteArtifact( materialize(res: http.IncomingMessage, signal: AbortSignal): Promise; }, ): Promise { - const transport = await loadNodeHttpRequester(params.artifactUrl, { - subject: 'Artifact download URL', - }); + const transport = await loadNodeHttpRequester(params.artifactUrl.protocol); await destination.prepare(); return await new Promise((resolve, reject) => { let settled = false; diff --git a/packages/remote/src/remote-request-diagnostics.ts b/packages/remote/src/remote-request-diagnostics.ts index 29d2b25ceb..076c9535ce 100644 --- a/packages/remote/src/remote-request-diagnostics.ts +++ b/packages/remote/src/remote-request-diagnostics.ts @@ -146,7 +146,7 @@ async function fetchRemoteRequestDiagnostics(params: { return 'daemon base URL is not a valid URL'; } try { - const transport = await loadNodeHttpRequester(url, { subject: 'Remote daemon base URL' }); + const transport = await loadNodeHttpRequester(url.protocol); await fs.promises.mkdir(path.dirname(destinationPath), { recursive: true }); return await new Promise((resolve) => { let settled = false; diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index 8e1290be2b..69c8e5338a 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -338,13 +338,13 @@ async function requestUploadControl( watchdog.signal.throwIfAborted(); watchdog.arm(phase, UPLOAD_CONTROL_PLANE_TIMEOUT_MS); try { - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); // Redirects could forward the daemon token, so these control requests never follow them. - const response = await fetchWithCredential( - url, - { ...init, method: 'POST', redirect: 'error', signal: watchdog.signal }, - { subject: 'Upload URL' }, - ); + const response = await fetch(url, { + ...init, + method: 'POST', + redirect: 'error', + signal: watchdog.signal, + }); const body: unknown = response.ok ? await response.json().catch(() => undefined) : undefined; watchdog.signal.throwIfAborted(); return { response, body }; diff --git a/packages/remote/src/upload-stream.ts b/packages/remote/src/upload-stream.ts index 04bfcc102a..6b116d7111 100644 --- a/packages/remote/src/upload-stream.ts +++ b/packages/remote/src/upload-stream.ts @@ -108,7 +108,7 @@ async function streamFileToHttpRequestAttempt(options: { // This module sits in the CLI's eager import closure via the remote-artifact // upload client, but only a remote daemon ever uploads, so the HTTP stack // loads here rather than at import time. - const transport = await loadNodeHttpRequester(options.url, { subject: 'Upload URL' }); + const transport = await loadNodeHttpRequester(options.url.protocol); const payloadSize = fs.statSync(options.payloadPath).size; const headers = buildUploadRequestHeaders(options.headers, options.startOffset, payloadSize); emitUploadAttemptStarted(options.progress, options.startOffset, payloadSize); @@ -151,8 +151,6 @@ async function streamFileToHttpRequestAttempt(options: { req.on('error', (err) => { if (phases.responseStarted) return; - // A typed refusal says why nothing was sent. - if (err instanceof AppError) return fail(err); fail( new AppError( 'COMMAND_FAILED', diff --git a/packages/test-kit/src/host-kit-capabilities.ts b/packages/test-kit/src/host-kit-capabilities.ts index 400e11a718..a2f82efce8 100644 --- a/packages/test-kit/src/host-kit-capabilities.ts +++ b/packages/test-kit/src/host-kit-capabilities.ts @@ -8,27 +8,17 @@ * import of every capability would make those mocks incomplete. */ export async function loadRealHostKitCapabilities() { - const [ - command, - diagnostics, - directHttp, - file, - processModule, - request, - retry, - runtimeSlots, - version, - ] = await Promise.all([ - import('@agent-device/host-kit/command'), - import('@agent-device/host-kit/diagnostics'), - import('@agent-device/host-kit/direct-http'), - import('@agent-device/host-kit/file'), - import('@agent-device/host-kit/process'), - import('@agent-device/host-kit/request'), - import('@agent-device/host-kit/retry'), - import('@agent-device/host-kit/runtime-slots'), - import('@agent-device/host-kit/version'), - ]); + const [command, diagnostics, file, processModule, request, retry, runtimeSlots, version] = + await Promise.all([ + import('@agent-device/host-kit/command'), + import('@agent-device/host-kit/diagnostics'), + import('@agent-device/host-kit/file'), + import('@agent-device/host-kit/process'), + import('@agent-device/host-kit/request'), + import('@agent-device/host-kit/retry'), + import('@agent-device/host-kit/runtime-slots'), + import('@agent-device/host-kit/version'), + ]); return { runCmdStreaming: command.runCmdStreaming, runCmdBackground: command.runCmdBackground, @@ -37,7 +27,6 @@ export async function loadRealHostKitCapabilities() { commandDeveloperDir: command.commandDeveloperDir, emitDiagnostic: diagnostics.emitDiagnostic, withDiagnosticTimer: diagnostics.withDiagnosticTimer, - fetchWithCredential: directHttp.fetchWithCredential, retryWithPolicy: retry.retryWithPolicy, isEnvTruthy: retry.isEnvTruthy, deadlineFromTimeoutMs: (timeoutMs: number, nowMs?: number) => diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be7f3994ad..311e223d79 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1087,9 +1087,6 @@ importers: '@agent-device/test-kit': specifier: workspace:* version: link:../test-kit - undici: - specifier: 7.30.1 - version: 7.30.1 packages/remote: dependencies: diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index 72eaf37fdf..cb6a890b37 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -612,8 +612,6 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/host-kit/code-signature-cache', '@agent-device/host-kit/command', '@agent-device/host-kit/diagnostics', - // Loaded at send time: a direct connection for credential-bearing plain-http requests. - '@agent-device/host-kit/direct-http', '@agent-device/host-kit/doctor-lines', '@agent-device/host-kit/file', '@agent-device/host-kit/gzip-tar', diff --git a/src/cli/__tests__/cloud-auth-request.test.ts b/src/cli/__tests__/cloud-auth-request.test.ts index b211e0604c..54dcc02f8d 100644 --- a/src/cli/__tests__/cloud-auth-request.test.ts +++ b/src/cli/__tests__/cloud-auth-request.test.ts @@ -1,11 +1,11 @@ -import { afterEach, expect, test, vi } from 'vitest'; +import { afterEach, expect, test } from 'vitest'; import http from 'node:http'; import type { AddressInfo } from 'node:net'; import { normalizeError } from '@agent-device/kernel/errors'; import { postCloudAuthJson } from '../cloud-auth-request.ts'; -// These tests send over the real transport to loopback servers, so they prove that the transport -// follows no redirect itself and that a refused target never receives a request. +// These tests use Node's own fetch against loopback servers, so they prove that no redirect is +// followed by fetch itself and that a refused target never receives a request. type Received = { method?: string; path?: string; body: string; contentType?: string }; /** A canned response. Routes are data, so no handler is ever chosen by the request path. */ @@ -14,7 +14,6 @@ type Route = { status: number; headers: Record; body: string }; const servers: http.Server[] = []; afterEach(async () => { - vi.restoreAllMocks(); await Promise.all( servers.splice(0).map( (server) => @@ -180,13 +179,3 @@ test('a cloud base URL over plain http off loopback is refused before anything i expect(refusal).toMatchObject({ details: { reason: 'insecure_credential_transport' } }); expect(sent).toBe(0); }); - -test('a loopback cloud is reached directly, never through global fetch and its proxy', async () => { - const cloud = await listen(); - cloud.routes.set('/start', answer); - const proxied = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); - - expect(await post(cloud.origin)).toEqual({ accessToken: 'adc_agent' }); - expect(cloud.received).toEqual([posted('/start')]); - expect(proxied).not.toHaveBeenCalled(); -}); diff --git a/src/cli/cloud-auth-request.ts b/src/cli/cloud-auth-request.ts index a0eee1cf5f..84fc7a891a 100644 --- a/src/cli/cloud-auth-request.ts +++ b/src/cli/cloud-auth-request.ts @@ -1,3 +1,7 @@ +import { + fetchWithCredential, + isRedirectStatus, +} from '@agent-device/contracts/credential-transport'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { readCloudJsonResponse } from './cloud-response.ts'; @@ -53,8 +57,6 @@ export async function fetchCloudOnOneOrigin( // di-seam-approved: the same fetch-global seam as postCloudAuthJson's fetchImpl. fetchImpl?: typeof fetch, ): Promise { - const { fetchWithCredential, isRedirectStatus } = - await import('@agent-device/host-kit/direct-http'); const response = await fetchWithCredential( requestUrl, // One timeout covers the whole redirect chain. diff --git a/src/cli/connection/cloud-profile-transport.test.ts b/src/cli/connection/cloud-profile-transport.test.ts index 3bb67e4211..cc0b8d89ce 100644 --- a/src/cli/connection/cloud-profile-transport.test.ts +++ b/src/cli/connection/cloud-profile-transport.test.ts @@ -1,10 +1,8 @@ -// `connect cloud` sends its bearer token to the cloud profile endpoint only over https (or plain -// http to loopback), and never follows a redirect to another origin. +// `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 { 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 { connectCommand } from '../commands/connection.ts'; import { resolveCloudAccessForConnect } from '../auth-session.ts'; @@ -24,71 +22,29 @@ vi.mock('../auth-session.ts', async (importOriginal) => ({ resolveCloudAccessForConnect: vi.fn(), })); -afterEach(() => { - vi.restoreAllMocks(); - vi.clearAllMocks(); - vi.unstubAllGlobals(); -}); - -async function connectCloud(stateDir: string): Promise { - const stdoutCapture = beginStdoutCapture(); - try { - await connectCommand({ - host: createTestHostEnvironment(), - positionals: [], - flags: { json: true, help: false, version: false, stateDir }, - client: {} as AgentDeviceClient, - }); - } finally { - stdoutCapture.restore(); - } -} - -async function connectCloudAt( - cloudBaseUrl: string, - answer: () => Response, -): Promise<{ reason: unknown; urls: string[] }> { - const tempRoot = mkdtempForTestSync('agent-device-connect-cloud-transport-'); +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, + cloudBaseUrl: 'http://cloud.example', }); - const urls: string[] = []; - vi.stubGlobal( - 'fetch', - vi.fn(async (input: string | URL | Request) => { - urls.push(String(input instanceof Request ? input.url : input)); - return answer(); - }), - ); - vi.spyOn(http, 'request').mockImplementation(((target: unknown) => { - urls.push(JSON.stringify(target)); - throw new Error('nothing may be sent over plain http'); - }) as typeof http.request); + const send = vi.spyOn(globalThis, 'fetch'); + const stdoutCapture = beginStdoutCapture(); + try { - const refusal = await connectCloud(path.join(tempRoot, '.state')).then( - () => assert.fail('expected connect cloud to be refused'), - (error: unknown) => error, + await assert.rejects( + async () => + await connectCommand({ + host: createTestHostEnvironment(), + positionals: [], + flags: { json: true, help: false, version: false, stateDir }, + client: {} as AgentDeviceClient, + }), + (error: unknown) => normalizeError(error).details?.reason === 'insecure_credential_transport', ); - return { reason: normalizeError(refusal).details?.reason, urls }; + assert.equal(send.mock.calls.length, 0); } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); + stdoutCapture.restore(); + send.mockRestore(); } -} - -test('connect cloud never sends its bearer token to a plain http cloud off loopback', async () => { - const { reason, urls } = await connectCloudAt('http://cloud.example', () => new Response('{}')); - - assert.equal(reason, 'insecure_credential_transport'); - assert.deepEqual(urls, []); -}); - -test('connect cloud refuses a profile redirect to another origin before sending to it', async () => { - const { reason, urls } = await connectCloudAt( - 'https://cloud.example', - () => new Response(null, { status: 302, headers: { location: 'http://other.example/x' } }), - ); - - assert.equal(reason, 'cloud_auth_redirect_refused'); - assert.deepEqual(urls, ['https://cloud.example/api/control-plane/connection-profile']); }); diff --git a/src/core/interactors/limrun-ios-files.test.ts b/src/core/interactors/limrun-ios-files.test.ts index 2228ca5e3e..d3015aef8a 100644 --- a/src/core/interactors/limrun-ios-files.test.ts +++ b/src/core/interactors/limrun-ios-files.test.ts @@ -4,7 +4,6 @@ import { createLimrunAppleToolProvider } from './limrun-ios-tools.ts'; import { withAppleToolProvider } from '@agent-device/platform-apple/tool-provider'; import { resolveIosSimulatorDeepLinkBundleId } from '@agent-device/platform-apple/app-resolution'; import { promises as fs } from 'node:fs'; -import http from 'node:http'; import path from 'node:path'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; @@ -381,7 +380,6 @@ test('a provider API URL over plain http off loopback never receives the instanc const local = path.join(f.directory, 'push.apns'); await fs.writeFile(local, '{}'); const fetchSpy = vi.spyOn(globalThis, 'fetch'); - const requestSpy = vi.spyOn(http, 'request'); try { const session = { ...f.session, apiUrl: 'http://limrun.invalid/v1/ios_test/api' }; const tools = createLimrunAppleToolProvider(session, new AbortController().signal); @@ -389,33 +387,6 @@ test('a provider API URL over plain http off loopback never receives the instanc details: { reason: 'insecure_credential_transport' }, }); expect(fetchSpy).not.toHaveBeenCalled(); - expect(requestSpy).not.toHaveBeenCalled(); - } finally { - fetchSpy.mockRestore(); - requestSpy.mockRestore(); - } -}); - -test('loopback file requests and downloads never go through global fetch', async () => { - const f = await fixture({ - containers: { 'com.example.app': { app: { 'Info.plist': plist('exp+example') } } }, - }); - const local = path.join(f.directory, 'push.apns'); - await fs.writeFile(local, '{}'); - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); - try { - const tools = createLimrunAppleToolProvider(f.session, new AbortController().signal); - await (await tools.simulatorFiles.stageFile(local))[Symbol.asyncDispose](); - await expect( - tools.simulatorApps.readInfoPlist({ - device: f.device, - bundleId: 'com.example.app', - timeoutMs: 5_000, - }), - ).resolves.toMatchObject({ CFBundleExecutable: 'Example' }); - - expect(f.storage.calls.map((call) => call.method)).toEqual(['PUT', 'DELETE', 'GET']); - 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 0d4d1d2962..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,21 +64,17 @@ export function createLimrunSimulatorFiles( }; const request = async (method: string, url: URL, signal: AbortSignal, body?: Uint8Array) => { signal.throwIfAborted(); - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); - const response = await fetchWithCredential( - url, - { - method, - headers: { - Authorization: `Bearer ${session.token}`, - ...(body ? { 'Content-Type': 'application/octet-stream' } : {}), - }, - body: body as BodyInit | undefined, - signal, - redirect: 'error', + assertSecureCredentialTransport(url, 'Limrun API URL'); + const response = await fetch(url, { + method, + headers: { + Authorization: `Bearer ${session.token}`, + ...(body ? { 'Content-Type': 'application/octet-stream' } : {}), }, - { subject: 'Limrun API URL' }, - ); + body: body as BodyInit | undefined, + signal, + redirect: 'error', + }); if (!response.ok) { await response.body?.cancel(); throw new AppError('COMMAND_FAILED', `Limrun file ${method} failed (${response.status})`, { diff --git a/src/core/interactors/limrun-ios-runner-products.ts b/src/core/interactors/limrun-ios-runner-products.ts index c57f28adc4..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,26 +247,22 @@ export async function uploadLimrunRunnerProducts( for (const file of payloads) yield* createReadStream(path.join(directory, file.path), { signal }); } - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); + assertSecureCredentialTransport(apiUrl, 'Limrun API URL'); const stream = createGzip(); const compression = pipeline(Readable.from(body()), stream, { signal }).catch(() => {}); try { - const response = await fetchWithCredential( - `${apiUrl}/sync`, - { - method: 'POST', - headers: { - Authorization: `Bearer ${token}`, - 'Content-Type': 'application/octet-stream', - 'Content-Encoding': 'gzip', - }, - body: Readable.toWeb(stream) as ReadableStream, - duplex: 'half', - signal, - redirect: 'error', - } as RequestInit & { duplex: 'half' }, - { subject: 'Limrun API URL' }, - ); + const response = await fetch(`${apiUrl}/sync`, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/octet-stream', + 'Content-Encoding': 'gzip', + }, + body: Readable.toWeb(stream) as ReadableStream, + duplex: 'half', + signal, + redirect: 'error', + } as RequestInit & { duplex: 'half' }); if (!response.ok) { await response.body?.cancel(); throw limrunRunnerError( diff --git a/src/core/interactors/limrun-ios-runner.test.ts b/src/core/interactors/limrun-ios-runner.test.ts index 336d2f50d0..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,17 +50,19 @@ test('stages a token-authenticated runner once and presents forwarded XCTest sna ).rejects.toThrow(); }); -test('a loopback instance gets sync, launch and runner calls without global fetch', async () => { - const f = await fixture(); - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('proxied')); +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 f.runner.createInteractor().snapshot({ appBundleId: 'com.apple.Preferences' }); - - expect(f.uploads.length).toBeGreaterThan(0); - expect(f.requests.filter((url) => url.endsWith('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/xctest/run'))).toHaveLength(1); - expect(f.command).toMatchObject({ command: 'snapshot' }); + 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(); - await f.runner.dispose(); } finally { fetchSpy.mockRestore(); } diff --git a/src/core/interactors/limrun-ios-runner.ts b/src/core/interactors/limrun-ios-runner.ts index e7f89c180f..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,25 +164,21 @@ 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)]); - const { fetchWithCredential } = await import('@agent-device/host-kit/direct-http'); + assertSecureCredentialTransport(apiUrl, 'Limrun API URL'); response = await retryWithPolicy( async () => { runRequested = true; const result = await awaitWithSignal( - fetchWithCredential( - `${apiUrl}/xctest/run`, - { - method: 'POST', - headers: { ...headers, 'Content-Type': 'application/json' }, - body: JSON.stringify({ - root: path.basename(directory), - xctestrun: 'Runner.xctestrun', - }), - signal, - redirect: 'error', - }, - { subject: 'Limrun API URL' }, - ), + fetch(`${apiUrl}/xctest/run`, { + method: 'POST', + headers: { ...headers, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + root: path.basename(directory), + xctestrun: 'Runner.xctestrun', + }), + signal, + redirect: 'error', + }), launchSignal, ); if (!result.ok) { diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index 7c1dd9bde5..459e7b2ecf 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -202,87 +202,40 @@ test.each(['default', 'typed', 'deadline'] as const)( }, ); -async function download(url: string): Promise { +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'); - await downloadLimrunFile({ - url, - headers: { Authorization: 'Bearer instance-token' }, - destinationPath, - timeoutMs: 5_000, - }); - return destinationPath; -} - -const insecure = { details: { reason: 'insecure_credential_transport' } }; -const refusedRedirect = { details: { reason: 'limrun_download_redirect_refused' } }; -const redirectTo = (location: string) => new Response(null, { status: 302, headers: { location } }); - -const downloadHeaders: Array> = [ - { Authorization: 'Bearer instance-token' }, - {}, -]; - -test.each(downloadHeaders)( - 'a provider download URL over plain http off loopback is never requested, with headers %j', - async (headers) => { - const fetchSpy = vi.spyOn(globalThis, 'fetch'); - const requestSpy = vi.spyOn(http, 'request'); - - await expect( - downloadLimrunFile({ - url: 'http://limrun.invalid/files?signature=signed', - headers, - destinationPath: path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'), - timeoutMs: 5_000, - }), - ).rejects.toMatchObject(insecure); - - expect(fetchSpy).not.toHaveBeenCalled(); - expect(requestSpy).not.toHaveBeenCalled(); - }, -); - -test('an https download redirected to plain http off loopback sends nothing there', async () => { - const sent: string[] = []; - vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { - sent.push(`${String(input)} ${init?.redirect}`); - return redirectTo('http://limrun.invalid/files?signature=signed'); - }); - const requestSpy = vi.spyOn(http, 'request'); - - await expect(download('https://limrun.example/files')).rejects.toMatchObject(refusedRedirect); - - expect(sent).toEqual(['https://limrun.example/files manual']); - expect(requestSpy).not.toHaveBeenCalled(); -}); + fs.writeFileSync(destinationPath, 'earlier download'); + const fetchSpy = vi.spyOn(globalThis, 'fetch'); -test('a redirect off https to another origin is refused before its target is contacted', async () => { - const reached: string[] = []; - const target = new URL( - await serve((request, response) => { - reached.push(request.url ?? ''); - response.end('payload'); + await expect( + downloadLimrunFile({ + url: 'http://limrun.invalid/files?signature=signed', + headers: {}, + destinationPath, + timeoutMs: 5_000, }), - ); - const origin = await serve((_request, response) => { - response.writeHead(307, { location: target.href }).end(); - }); + ).rejects.toMatchObject({ details: { reason: 'insecure_credential_transport' } }); - await expect(download(origin)).rejects.toMatchObject(refusedRedirect); - - expect(reached).toEqual([]); + 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')]); - return sent.length === 1 - ? redirectTo('https://storage.example/clip?signature=signed') - : new Response('payload'); + 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'); - const destinationPath = await download('https://limrun.example/files'); + 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([ @@ -290,39 +243,3 @@ test('an https redirect to another origin is followed without the caller headers ['https://storage.example/clip?signature=signed', null], ]); }); - -test('a same-origin redirect is followed with the headers, at most five times', async () => { - const seen: string[] = []; - const url = await serve((request, response) => { - seen.push(`${request.url} ${request.headers.authorization}`); - if (seen.length === 1) response.writeHead(302, { location: '/clip' }).end(); - else response.end('payload'); - }); - - expect(fs.readFileSync(await download(url), 'utf8')).toBe('payload'); - expect(seen.at(-1)).toBe('/clip Bearer instance-token'); - - let hops = 0; - const loop = await serve((_request, response) => { - hops += 1; - response.writeHead(302, { location: '/again' }).end(); - }); - await expect(download(loop)).rejects.toMatchObject(refusedRedirect); - expect(hops).toBe(6); -}); - -test('a refused download URL leaves an existing file at the destination untouched', async () => { - const destinationPath = path.join(await mkdtempForTest('limrun-download-'), 'clip.mp4'); - fs.writeFileSync(destinationPath, 'earlier download'); - - await expect( - downloadLimrunFile({ - url: 'http://limrun.invalid/files?signature=signed', - headers: {}, - destinationPath, - timeoutMs: 5_000, - }), - ).rejects.toMatchObject(insecure); - - expect(fs.readFileSync(destinationPath, 'utf8')).toBe('earlier download'); -}); diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index c66fa8aaf3..212918bd24 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -9,10 +9,12 @@ import { type ReasonTable, } from '@agent-device/kernel/errors'; import type { LimrunFileDownload } from '@agent-device/provider-limrun'; -import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; +import { + assertSecureCredentialTransport, + fetchWithCredential, +} from '@agent-device/contracts/credential-transport'; const RESPONSE_BODY_PREVIEW_BYTES = 500; -const MAX_DOWNLOAD_REDIRECTS = 5; // 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 @@ -24,9 +26,6 @@ const LIMRUN_DOWNLOAD_REASONS = { timeout: { reason: 'limrun_download_timeout' }, // The transfer broke for a reason the service never answered with, kept in `details.cause`. failed: { reason: 'limrun_download_failed' }, - // The download got a redirect it does not follow: off https to another origin, to a URL with a - // username or password or one that does not parse, or past the fifth hop. Nothing was sent there. - redirectRefused: { reason: 'limrun_download_redirect_refused' }, } as const satisfies ReasonTable<'limrun'>; /** @@ -41,7 +40,12 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise { - const { fetchWithCredential, isRedirectStatus } = - await import('@agent-device/host-kit/direct-http'); - let url = from; - let headers = initialHeaders; - for (let redirects = 0; ; redirects += 1) { - const response = await fetchWithCredential( - url.href, - { method: 'GET', headers, redirect: 'manual', signal }, - { subject: 'Limrun download URL' }, - ); - const location = response.headers.get('location'); - if (!isRedirectStatus(response.status) || location === null) return response; - await response.body?.cancel().catch(() => undefined); - const target = URL.parse(location, url); - if (!target || !isFollowedRedirect(url, target) || redirects >= MAX_DOWNLOAD_REDIRECTS) { - throw new AppError('COMMAND_FAILED', 'Limrun download answered with a refused redirect', { - reason: LIMRUN_DOWNLOAD_REASONS.redirectRefused.reason, - statusCode: response.status, - }); - } - if (target.origin !== url.origin) headers = {}; - url = target; - } -} - -function isFollowedRedirect(from: URL, to: URL): boolean { - if (to.username || to.password) return false; - return (from.protocol === 'https:' && to.protocol === 'https:') || to.origin === from.origin; -} - 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/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts b/test/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts index 5ff42dc42a..51eb05e329 100644 --- a/test/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts +++ b/test/integration/provider-scenarios/remote-proxy-request-diagnostics.test.ts @@ -4,7 +4,6 @@ import http from 'node:http'; import path from 'node:path'; import { test, vi } from 'vitest'; import { localizeRemoteDaemonError } from '@agent-device/remote/remote-request-diagnostics'; -import { loadDirectHttpAgent } from '@agent-device/host-kit/direct-http'; import type { DaemonError } from '@agent-device/kernel/errors'; import { mkdtempForTestSync, skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; import { createProviderScenarioHarness } from './harness.ts'; @@ -103,13 +102,9 @@ test('Provider-backed integration local proxy serves the daemon diagnostics reco method?: string; path?: string; headers?: Record; - agent?: http.Agent; }; assert.equal(directRequestSpy.mock.calls.length, 1); - // The token travels over plain http to loopback, so the request takes the direct agent that - // never routes through an environment proxy. assert.deepEqual(directOptions, { - agent: await loadDirectHttpAgent(), protocol: 'http:', host: '127.0.0.1', port: String(daemon.httpPort), diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 35e479f4e9..03e95df3b4 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,7 +71,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealth": "sha256:1ff542dadff6d92233c464b7d09052d809f36186bb60acdb572c48bfc1eb5c1f", "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealthLink": "sha256:96a79a8ff5a078916ee7bffed1d9624d0ba9c0dcbd8e2c55f9abf37fccfef744", "packages/daemon-client/src/daemon-client-transport.ts#isHealthService": "sha256:ffd2c774e0efca5e5d2b01f9d37fe9b76aaf5e7569e07d9208fe667473771c10", - "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth": "sha256:a22237c62f5f413c0c1f3ec1e3b5603c89e25ed3bb6317d30ececfb4b04506f7", + "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth": "sha256:6ce1f9be1e6a977130d0875003ac22da2de5e90b514a3b22b30b9347e63d81c7", "packages/daemon-client/src/daemon-client-transport.ts#readHealthLink": "sha256:c4f638b4df43f572e105b6f8df578fe90ebf64cb56002e4d029a109bdbc167d1", "packages/daemon-client/src/daemon-client-transport.ts#readHealthPayload": "sha256:4e85ffc3e35e02379c393e9312344757e003cf1f0ad9eb8d1f77d90c81c861f1", "packages/daemon-client/src/daemon-client-transport.ts#readHealthVersion": "sha256:856bd74aa8b2f205b6b30855755f16391015bffc1b6a323f618b51c26e749bfd", @@ -165,7 +165,7 @@ "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint": "sha256:c1d5fe2fe90c425502cf8b7c87d6606374d6af65b4e9faf942a416f683930bdc", "packages/remote/src/remote-request-diagnostics.ts#buildRemoteRequestDiagnosticsUrl": "sha256:30a1a9bf0df24d3564a616699916a3bb4360c2b4d21c4ad0562fb0c1e738d0a9", - "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics": "sha256:a2e04f82f6aca33bad8dc84eaa2581d910a4eb5012bb6b48757d735a9895daed", + "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics": "sha256:6f68c317e4c0fe5de008ec1fe5e7e030a9d298ad4a7dfd561db933d22e12ae9e", "packages/remote/src/remote-request-diagnostics.ts#localizeRemoteDaemonError": "sha256:35cfa186ad64663ae4dbb4e102d49238532cd7e3b75e8337edcc3d1fd77f92d5", "packages/remote/src/upload-client-artifact.ts#PreparedUploadArtifact": "sha256:5c40027d47feda3c946e836372b9f08ad866ab1612708b0d506551545f931ea4", "packages/remote/src/upload-client.ts#ARTIFACT_HASH_ALGORITHM": "sha256:328c135ea5f9d89fd2c142b440d5402a61d19f9044bf0504dfc2c525e58c1909", @@ -175,7 +175,7 @@ "packages/remote/src/upload-client.ts#finalizeDirectUpload": "sha256:ca3fa667ab2a60fb8af095bddeacb4875dcd2d12db783585a0fb045db35da212", "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:4b1e2bf81db43907bd61934aafb36090f2f7503f6180d6f21dacd137da6d5f28", + "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:5689da0c0cd18d0293e5bb05ddc0d8a07d1bca9ab1d94f8ca185b03bc5b8d758", "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", @@ -190,7 +190,7 @@ "packages/remote/src/upload-stream.ts#parseNonNegativeIntegerHeader": "sha256:5cbe9c6994459d673d988a51407e65556e28175b187ce0a9d27cbb6331962834", "packages/remote/src/upload-stream.ts#parseUploadResumeOffset": "sha256:297184ea22a6dc1cda9aee17034122ae0ea2f43d0355647f6fcf02f3f4b5ca0e", "packages/remote/src/upload-stream.ts#streamFileToHttpRequest": "sha256:c2b5e1369c8b1c9420036e23163d21e43fa2ac8b889c6a8f028cc6095055a16f", - "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt": "sha256:3286664cab72bc809a49e497507fc423c2340250e63bec0bf9d2037db9ad34e1", + "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt": "sha256:53ea451d23e3c260177368080b8989715f915f85a2c7d907bcc59c72248c8db8", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_INSTANCE_HEADER": "sha256:d2bb3f4846470188a0fc1724271da0f0bcbdf2337bd6bf331508142cadcb65d8", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER": "sha256:4564c2ce437d30d7a823e3326f4375c0750ba8d42bec22b4d02e8eb7f7db2973", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_INSTANCE_MISMATCH_HEADER": "sha256:a197edaf7f9fa94a6aab269856aa852da3204cc586f5fd23198689eb11908b61", @@ -208,7 +208,7 @@ "packages/daemon/src/server/http/http-checked-rpc.ts#refuseCheckedRpcCredential": "sha256:5594a47e90079eaf31eeb335c709451f8e60616511a4ec84d7248722a37b93ea", "packages/daemon/src/server/http/http-checked-rpc.ts#withUnregisteredTrackingId": "sha256:fffc54ad047879605f532801118868fd0aed1db38b74d671b65325551cc8fe0a", "packages/daemon/src/server/http/http-checked-rpc.ts#readFrameParams": "sha256:8ccdb4a3b91a585be7c1518d198f34f608905c62b8eba9aad12b62a4107f5f31", - "packages/proxy/src/checked-rpc-admission.ts#localCheckedRpcRefusal": "sha256:05188deadff5a2a1e09faaeb2a500af5499dafc8183d18e4290d88f23a24d408", + "packages/proxy/src/checked-rpc-admission.ts#localCheckedRpcRefusal": "sha256:017a05ac5b415d33030a30c99529a9dd58bb19aeae5649d15a6e00740fe84d95", "packages/proxy/src/checked-rpc-admission.ts#refusalResponse": "sha256:10872cc1096a6c3262de9a2dccfb1fa447b67107322894a7289116575de9b4b7", "packages/proxy/src/checked-rpc-admission.ts#localRequestId": "sha256:1bd486b7d70c727c2cab6330fc78f65e1922126be2e38d615f39c1b36acf9eb4", "packages/proxy/src/checked-rpc-admission.ts#readUpstreamRefusalDetails": "sha256:4789d8cffbee31ce2c3c33184751bd11498365aa72e7b37e3b46c432e941920c", @@ -256,7 +256,7 @@ "packages/remote/src/artifact-download.ts#RemoteArtifactRequest": "sha256:6cce66499f34bb18139917df592e554395936964025089024d6c6f67e4fa4b98", "packages/remote/src/artifact-download.ts#RemoteArtifactFetch": "sha256:e83939ec48a66917df9ec84becf53b6ca3c8115cfdada10731046381ac9e32c1", "packages/remote/src/artifact-download.ts#fetchRemoteArtifactFromUrl": "sha256:de6e71abdc758f760beffba0dc260473f88a8c60b13540b9c14d39f1a3d5e3a1", - "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:85890c420579d6055b54caa37736c3d7627852f12bc243677a658cdbdf7c0ea7", + "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:cafb5fd5838819719b2fac62c5e108276dd800a58b4614462d138cf1ed2f7d6e", "packages/daemon-client/src/daemon-client-checked-rpc.ts#isCheckedRpcOutcomeResponse": "sha256:75fb9f3444a3f8f4a762811ba7cbe02d92a39ed4e55483ea0cf7f029e5720a3e", "packages/daemon-client/src/daemon-client-checked-rpc.ts#CheckedRpcOutcome": "sha256:8aa7e58307417460bb54938f6bbbd340254e14ffbbaf2093272996909592f7be", "packages/daemon-client/src/daemon-client-checked-rpc.ts#ReadHealthLink": "sha256:86a9e6f1ebdaecca3ddaa16081c221321c01c684b70197961ecd71a3f54a464f", @@ -464,8 +464,8 @@ }, { "declaration": "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth", - "digest": "sha256:a22237c62f5f413c0c1f3ec1e3b5603c89e25ed3bb6317d30ececfb4b04506f7", - "rationale": "The health-probe budget includes requester loading and response completion. The caller AbortSignal joins the probe timer only in-process; caller cancellation remains distinct from probe expiry. No signal, timedOut flag, request route, auth header or accepted health payload field changes on the wire, so released daemons and proxies parse and respond as before (ADR 0006). #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request. The sender is now loaded with the request URL and applies the credential rule itself: a refused destination, or a localhost that resolves off loopback, ends as a typed refusal before anything is sent. Method, path, headers, and body are unchanged." + "digest": "sha256:6ce1f9be1e6a977130d0875003ac22da2de5e90b514a3b22b30b9347e63d81c7", + "rationale": "The health-probe budget includes requester loading and response completion. The caller AbortSignal joins the probe timer only in-process; caller cancellation remains distinct from probe expiry. No signal, timedOut flag, request route, auth header or accepted health payload field changes on the wire, so released daemons and proxies parse and respond as before (ADR 0006)." }, { "declaration": "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint", @@ -474,8 +474,8 @@ }, { "declaration": "packages/remote/src/remote-request-diagnostics.ts#fetchRemoteRequestDiagnostics", - "digest": "sha256:a2e04f82f6aca33bad8dc84eaa2581d910a4eb5012bb6b48757d735a9895daed", - "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request. The sender is now loaded with the request URL and applies the credential rule itself: a refused destination, or a localhost that resolves off loopback, ends as a typed refusal before anything is sent. Method, path, headers, and body are unchanged." + "digest": "sha256:6f68c317e4c0fe5de008ec1fe5e7e030a9d298ad4a7dfd561db933d22e12ae9e", + "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006)." }, { "declaration": "packages/remote/src/upload-client.ts#uploadDirectArtifact", @@ -534,8 +534,8 @@ }, { "declaration": "packages/remote/src/upload-stream.ts#streamFileToHttpRequestAttempt", - "digest": "sha256:3286664cab72bc809a49e497507fc423c2340250e63bec0bf9d2037db9ad34e1", - "rationale": "#4441 keeps each attempt under its sequential phase watchdog and corrects its transport lifecycle: the connect ceiling now ends at actual socket or TLS-handshake establishment, body progress counts only transport writes, and an early response reads the accepted answer to its end, then destroys and joins the owned file/request pipeline and retires this attempt's phase watchdog before resolving or starting the redirect/resume attempt, so a completed hop's timers never reach the next hop. The outgoing-request phase observation now comes from @agent-device/host-kit/transport's observeClientRequestPhases, which listens to the same socket, TLS-handshake and finish events and is removed when the attempt settles. Bytes on the wire are unchanged: same route, method, headers, body framing, resume-offset handling and redirect limit. Only this client's own sequencing and deadlines moved, so a protocol-2 peer parses exactly what it parsed before. Request-body progress is now each non-empty request write that completes without an error, which Node reports once the bytes reach the local kernel, instead of drain, which fires only after a write returned false. The write wrapper passes every argument and the backpressure result through, so the bytes and framing on the wire do not change. That completed-write observer is host-kit's transport owner, which also stops reporting after the response starts, the signal aborts or the request is destroyed; no request changes. The attempt composes that write owner with the phase observer once per request and disposes both when it settles. Duplicate success disposal and abort-reason mapping are consolidated without changing precedence. The sole response-path pipeline join remains before outcome or next hop; URL, method, authentication, payloads and framing remain unchanged. Its two refusal errors now read details.reason from UPLOAD_TRANSFER_REASONS instead of literals in this declaration, so only the identifier expressions moved; the values published are the identical strings and nothing a peer sends or parses moves. #5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request. The sender is now loaded with the request URL and applies the credential rule itself: a refused destination, or a localhost that resolves off loopback, ends as a typed refusal before anything is sent. Method, path, headers, and body are unchanged." + "digest": "sha256:53ea451d23e3c260177368080b8989715f915f85a2c7d907bcc59c72248c8db8", + "rationale": "#4441 keeps each attempt under its sequential phase watchdog and corrects its transport lifecycle: the connect ceiling now ends at actual socket or TLS-handshake establishment, body progress counts only transport writes, and an early response reads the accepted answer to its end, then destroys and joins the owned file/request pipeline and retires this attempt's phase watchdog before resolving or starting the redirect/resume attempt, so a completed hop's timers never reach the next hop. The outgoing-request phase observation now comes from @agent-device/host-kit/transport's observeClientRequestPhases, which listens to the same socket, TLS-handshake and finish events and is removed when the attempt settles. Bytes on the wire are unchanged: same route, method, headers, body framing, resume-offset handling and redirect limit. Only this client's own sequencing and deadlines moved, so a protocol-2 peer parses exactly what it parsed before. Request-body progress is now each non-empty request write that completes without an error, which Node reports once the bytes reach the local kernel, instead of drain, which fires only after a write returned false. The write wrapper passes every argument and the backpressure result through, so the bytes and framing on the wire do not change. That completed-write observer is host-kit's transport owner, which also stops reporting after the response starts, the signal aborts or the request is destroyed; no request changes. The attempt composes that write owner with the phase observer once per request and disposes both when it settles. Duplicate success disposal and abort-reason mapping are consolidated without changing precedence. The sole response-path pipeline join remains before outcome or next hop; URL, method, authentication, payloads and framing remain unchanged. Its two refusal errors now read details.reason from UPLOAD_TRANSFER_REASONS instead of literals in this declaration, so only the identifier expressions moved; the values published are the identical strings and nothing a peer sends or parses moves." }, { "declaration": "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath", @@ -549,8 +549,8 @@ }, { "declaration": "packages/remote/src/upload-client.ts#requestUploadControl", - "digest": "sha256:4b1e2bf81db43907bd61934aafb36090f2f7503f6180d6f21dacd137da6d5f28", - "rationale": "Lists the shared control Fetch/JSON owner so changes to method, headers, body or redirect forwarding remain wire-gated. Existing preflight/finalize routes and protocol-2 payloads are preserved; the original 30-second ceiling now retains typed local phase expiry and stops later legs. Non-success status handling is unchanged. #5150 sends a plain-http (loopback) control request over node:http with a direct agent instead of global fetch. It still follows no redirect, and method, headers, and JSON body are unchanged. The sender is now loaded with the request URL and applies the credential rule itself: a refused destination, or a localhost that resolves off loopback, ends as a typed refusal before anything is sent. Method, path, headers, and body are unchanged." + "digest": "sha256:5689da0c0cd18d0293e5bb05ddc0d8a07d1bca9ab1d94f8ca185b03bc5b8d758", + "rationale": "Lists the shared control Fetch/JSON owner so changes to method, headers, body or redirect forwarding remain wire-gated. Existing preflight/finalize routes and protocol-2 payloads are preserved; the original 30-second ceiling now retains typed local phase expiry and stops later legs. Non-success status handling is unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#requestUploadPreflight", @@ -701,11 +701,6 @@ "declaration": "packages/remote/src/session-script-destination.ts#RemoteEndpoint", "digest": "sha256:2fbcaa03bc0675fef8d19fd0a163d5d01a2162031745a41ff5c1db8a982cc2b6", "rationale": "Adds the client-local checkedRpc flag, set when the open goes on the checked RPC route. Nothing on the wire reads it; the open request and its response fields are unchanged." - }, - { - "declaration": "packages/remote/src/artifact-download.ts#requestRemoteArtifact", - "digest": "sha256:85890c420579d6055b54caa37736c3d7627852f12bc243677a658cdbdf7c0ea7", - "rationale": "#5150 changes only how the request reaches the daemon: a plain-http (loopback) destination takes a direct node:http agent that bypasses environment proxies. Method, path, headers, and body are unchanged, so a protocol-3 peer receives the same request. The sender is now loaded with the request URL and applies the credential rule itself: a refused destination, or a localhost that resolves off loopback, ends as a typed refusal before anything is sent. Method, path, headers, and body are unchanged." } ] } diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 1b9f446b3f..e1dd4ddcf8 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -819,7 +819,6 @@ These reasons can come from more than one command. | `limrun_download_http_error` | The service answered the download with an error status; `details.statusCode` and `details.body` carry its reply. | | `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`. | -| `limrun_download_redirect_refused` | The download got a redirect it does not follow: off https to another origin, to a URL with a username or password or one that does not parse, or past the fifth hop. Nothing was sent there. | ### Limrun provider @@ -901,12 +900,11 @@ 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 `localhost` that resolves to no loopback address, 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. | +| `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. | | `remote_checked_rpc_unsupported` | The connection sets `daemonRpc: checked`, but the remote does not serve checked RPC: `connect` found no `checked-rpc` capability in its `/health`, or a command got the route answered as unknown. A command is never resent, because an ingress may have answered for one that ran. Update the remote daemon or proxy, or remove `daemonRpc` from the connection. | -| `direct_http_idle_timeout` | A plain-http exchange with a loopback peer stayed silent for `details.timeoutMs`. | | `REMOTE_SESSION_REQUIRED` | A command on a leased remote connection, or one that would lease one, named no session. | | `CONNECTION_DEVICE_CONFLICT` | The connection is bound to another device, or its lease was allocated by another device spec; `details.keys` names the disagreeing keys, and is present only for a device-spec mismatch. | | `CONNECTION_PLATFORM_CONFLICT` | The connection is bound to another platform, or the request names one its lease backend does not rent. | diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 3c6bcaf10e..639681d9bc 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -46,7 +46,7 @@ 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 a `localhost` that resolves to one of them). 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`. +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. diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 8da3caf47c..f715405005 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -23,8 +23,7 @@ CLI commands run through a per-user background daemon: 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. -- `localhost` counts only when it resolves to a loopback address. -- A credential-bearing request to plain http on loopback connects directly and never goes through an environment proxy (`HTTP_PROXY` with `NODE_USE_ENV_PROXY`). +- 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 is followed only on the same origin, except by a Limrun download, which also follows https to https and drops its headers when it leaves the origin. The proxy follows no upstream redirect; it relays the redirect response to its client. - The Metro companion opens the host bridge's socket only over `wss`, or `ws` to loopback. A request the bridge relays to your dev server with an `Authorization` or `Cookie` header follows the same rule. - 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. From 071e33c9c7199e27608aeb26a81ed6d165852b88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 18:13:21 +0100 Subject: [PATCH 18/22] fix(react-native): relay an absolute path on the local base origin The companion refused every absolute relayed path, including one on the local base origin that it served before. Compare the resolved origin only, which still refuses another origin, absolute or scheme-relative. Co-Authored-By: Claude Sonnet 5.5 --- .../src/companion/client-companion-local-relay.ts | 4 ++-- ...ompanion-tunnel-worker-credential-transport.test.ts | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/react-native/src/companion/client-companion-local-relay.ts b/packages/react-native/src/companion/client-companion-local-relay.ts index 75aca04f3d..22fbbe14af 100644 --- a/packages/react-native/src/companion/client-companion-local-relay.ts +++ b/packages/react-native/src/companion/client-companion-local-relay.ts @@ -12,11 +12,11 @@ const CREDENTIAL_HEADERS = [ 'x-agent-device-token', ]; -/** The URL a relayed request goes to: a path on the local base's origin, and nothing else. */ +/** 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 (URL.canParse(requestPath) || target?.origin !== base.origin) { + if (!target || target.origin !== base.origin) { throw new AppError( 'INVALID_ARGS', 'The Metro companion refuses a relayed path that leaves the local base URL.', 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 index 684615e08c..019920684b 100644 --- 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 @@ -233,6 +233,16 @@ test('a relayed path that leaves the local base URL is refused, over HTTP and so 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'], From 8a7acf1c6afde564f04acc9d766ffb5f7fa9f040 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 28 Nov 2026 11:15:35 +0100 Subject: [PATCH 19/22] fix(remote): use fetch redirect modes and check relayed sockets - Report a Limrun download redirect that is not followed with its status only: no URL, Location or body. - Give Limrun downloads their own 20-hop limit, the one fetch applies. Fetch's own follow is not used there: it follows https to plain http. - Check every relayed Metro WebSocket URL before the socket is built. - Delete fetchWithCredential. Cloud profile and Metro bridge requests use fetch's redirect follow, which drops Authorization on another origin. Cloud auth keeps its same-origin loop because a 307 resends the body. The companion follows no redirect on relayed requests because custom headers survive a cross-origin follow. - Delete the proxy's relayed Location. The daemon sends none. Co-Authored-By: Claude Sonnet 5.5 --- .../src/credential-transport.test.ts | 86 +-------------- .../contracts/src/credential-transport.ts | 60 ---------- packages/proxy/README.md | 13 +-- .../daemon-proxy-credential-transport.test.ts | 73 +++---------- packages/proxy/src/daemon-proxy.ts | 51 ++++++--- packages/proxy/src/upstream-response-relay.ts | 94 ---------------- .../companion/client-companion-local-relay.ts | 14 ++- ...tunnel-worker-credential-transport.test.ts | 66 +++++++++-- .../client-companion-tunnel-worker.ts | 44 ++++---- .../metro/client-metro-auto-companion.test.ts | 57 +++++++++- .../react-native/src/metro/client-metro.ts | 30 ++--- src/cli/cloud-auth-request.ts | 103 +++++++++--------- .../cloud-profile-transport.test.ts | 55 ++++++++-- src/cli/connection/cloud-profile.ts | 15 ++- src/core/limrun-download-file.test.ts | 71 +++++++++++- src/core/limrun-download-file.ts | 58 ++++++++-- website/docs/docs/error-reasons.md | 2 +- website/docs/docs/security-trust.md | 8 +- 18 files changed, 442 insertions(+), 458 deletions(-) delete mode 100644 packages/proxy/src/upstream-response-relay.ts diff --git a/packages/contracts/src/credential-transport.test.ts b/packages/contracts/src/credential-transport.test.ts index 08a07287c3..ceedf5c772 100644 --- a/packages/contracts/src/credential-transport.test.ts +++ b/packages/contracts/src/credential-transport.test.ts @@ -1,9 +1,8 @@ -import { expect, test, vi } from 'vitest'; +import { expect, test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; import { assertSecureCredentialSocket, assertSecureCredentialTransport, - fetchWithCredential, } from './credential-transport.ts'; import { isLoopbackHostname } from './loopback-host.ts'; @@ -96,86 +95,3 @@ test.each([ assertSecureCredentialTransport(url, 'Runner URL', { coreDeviceTunnel: true }), ).toThrow(); }); - -/** Sends through a transport that answers each URL in `redirects` with that redirect. */ -async function followRedirects( - url: string, - redirects: Record, - followHttpsOffOrigin = false, -) { - const sent: string[] = []; - const response = await fetchWithCredential( - url, - { - method: 'POST', - headers: { authorization: 'Bearer secret', 'content-type': 'application/json' }, - body: 'payload', - }, - { - subject: 'Test URL', - followHttpsOffOrigin, - send: async (input, init) => { - const headers = new Headers(init?.headers); - const parts = [init?.method, String(input), init?.redirect, init?.body ?? '-']; - sent.push( - [...parts, headers.get('authorization') ?? '-', headers.get('content-type') ?? '-'].join( - ' ', - ), - ); - const redirect = redirects[String(input)]; - if (!redirect) return new Response('done'); - return new Response(null, { status: redirect[0], headers: { location: redirect[1] } }); - }, - }, - ); - return { status: response.status, sent }; -} - -const A = 'https://a.example/start'; -const first = `POST ${A} manual payload Bearer secret application/json`; - -test.each([307, 308])('a same-origin %s resends the method, body and headers', async (status) => { - expect(await followRedirects(A, { [A]: [status, '/moved'] })).toEqual({ - status: 200, - sent: [first, 'POST https://a.example/moved manual payload Bearer secret application/json'], - }); -}); - -test.each([301, 302, 303])('a same-origin %s turns a POST into a GET', async (status) => { - expect((await followRedirects(A, { [A]: [status, '/moved'] })).sent).toEqual([ - first, - 'GET https://a.example/moved manual - Bearer secret -', - ]); -}); - -test.each([ - ['another origin', 'https://b.example/start'], - ['plain http on the same host', 'http://a.example/start'], - ['a URL with a username', 'https://operator@a.example/start'], -])('a redirect to %s is returned, never followed', async (_label, location) => { - expect(await followRedirects(A, { [A]: [307, location] })).toEqual({ - status: 307, - sent: [first], - }); -}); - -test('three same-origin redirects are followed and the fourth is returned', async () => { - const { status, sent } = await followRedirects(A, { [A]: [307, A] }); - expect(status).toBe(307); - expect(sent).toHaveLength(4); -}); - -test('a download follows https off the origin without headers, and never to plain http', async () => { - const b = 'https://b.example/file'; - expect( - await followRedirects(A, { [A]: [307, b], [b]: [307, 'http://b.example/file'] }, true), - ).toEqual({ status: 307, sent: [first, `POST ${b} manual payload - -`] }); -}); - -test('a destination the rule refuses is never sent to', async () => { - const send = vi.fn(); - await expect( - fetchWithCredential('http://a.example', {}, { subject: 'Test URL', send }), - ).rejects.toMatchObject({ details: { reason: 'insecure_credential_transport' } }); - expect(send).not.toHaveBeenCalled(); -}); diff --git a/packages/contracts/src/credential-transport.ts b/packages/contracts/src/credential-transport.ts index a964c9479e..1e634d9b3f 100644 --- a/packages/contracts/src/credential-transport.ts +++ b/packages/contracts/src/credential-transport.ts @@ -88,63 +88,3 @@ export function isCredentialTransportRefusal(error: unknown): error is AppError error.details?.reason === CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason ); } - -const MAX_FOLLOWED_REDIRECTS = 3; - -export function isRedirectStatus(status: number): boolean { - return [301, 302, 303, 307, 308].includes(status); -} - -export type CredentialFetch = { - /** Names the setting a refusal is about. */ - subject: string; - /** The caller's transport; global `fetch` by default. */ - send?: typeof fetch; - /** For a download: also follows https to https on another origin, without the request headers. */ - followHttpsOffOrigin?: boolean; -}; - -/** - * `fetch` for a request that carries a credential and may be redirected. Every URL it sends to - * meets the credential transport rule. It follows up to three redirects itself, on the same origin, - * keeping the method and body on a 307 or 308. Any other redirect is returned as the answer. - */ -export async function fetchWithCredential( - url: string | URL, - init: RequestInit, - { subject, send = fetch, followHttpsOffOrigin = false }: CredentialFetch, -): Promise { - let target = assertSecureCredentialTransport(url, subject); - let request: RequestInit = { ...init, redirect: 'manual' }; - for (let followed = 0; ; followed += 1) { - const response = await send(target.href, request); - const next = followedTarget(response, target, followHttpsOffOrigin); - if (!next || followed === MAX_FOLLOWED_REDIRECTS) return response; - await response.body?.cancel().catch(() => undefined); - request = redirectedRequest(request, response.status); - if (next.origin !== target.origin) request = { ...request, headers: undefined }; - target = assertSecureCredentialTransport(next, subject); - } -} - -/** Where a redirect leads, when it is one `fetchWithCredential` follows. */ -function followedTarget(response: Response, from: URL, offOrigin: boolean): URL | undefined { - if (!isRedirectStatus(response.status)) return undefined; - const location = response.headers.get('location'); - if (location === null) return undefined; - const to = URL.parse(location, from); - if (!to || to.username || to.password) return undefined; - if (to.origin === from.origin) return to; - return offOrigin && from.protocol === 'https:' && to.protocol === 'https:' ? to : undefined; -} - -/** The request a followed redirect sends, with the change to GET that `fetch` makes. */ -function redirectedRequest(request: RequestInit, status: number): RequestInit { - const method = request.method?.toUpperCase() ?? 'GET'; - const becomesGet = - status === 303 ? method !== 'HEAD' : (status === 301 || status === 302) && method === 'POST'; - if (!becomesGet) return request; - const headers = new Headers(request.headers); - headers.delete('content-type'); - return { ...request, method: 'GET', body: undefined, headers }; -} diff --git a/packages/proxy/README.md b/packages/proxy/README.md index a48860d4a0..1e409e0aaa 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -154,14 +154,11 @@ 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. 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, such as the daemon's `308` resume response, to its client. It relays a -`Location` only when it targets the daemon itself, as a path on the proxy's client-facing origin -without its query or fragment. It drops one that points elsewhere, has userinfo, or has the -upstream token in its path, written or percent-decoded. 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`. +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 diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index 6e880f01cc..527731fe7e 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -150,67 +150,28 @@ test('the default transports relay an upstream redirect and never follow it', as expect(reached).toEqual([]); }); -test.each([ - ['a foreign origin', 'http://attacker.example/x?signature=secret', null], - ['userinfo', 'https://user:pass@daemon.example.test/artifacts/x', null], - ['the upstream token in its path', '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/artifacts/daemon-secret', null], - ['the percent-encoded upstream token in its path', '/artifacts/daemon%2Dsecret', null], - ['a malformed path escape', '/artifacts/%E0%A4%A', null], - [ - 'the percent-encoded upstream token in its query', - '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/artifacts/other?token=daemon%2Dsecret', - 'https://gateway.example.test/agent-device/artifacts/other', - ], - [ - 'the upstream token in its fragment', - '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/artifacts/other#daemon%2Dsecret', - 'https://gateway.example.test/agent-device/artifacts/other', - ], - [ - 'the upstream daemon', - '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/artifacts/other', - 'https://gateway.example.test/agent-device/artifacts/other', - ], -] as const)( - 'a relayed Location that names %s is relayed only on the daemon itself', - async (_label, location, relayed) => { - 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(relayed); - } - }, -); - -test('a relayed Location is dropped when its path holds the upstream token as written', async () => { - // A token that reads differently once decoded: `a%2Fb` decodes to `a/b`. +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: 'a%2Fb', + upstreamToken: 'daemon-secret', clientToken: 'client-secret', - upstreamFetch: async () => - new Response(null, { status: 307, headers: { location: '/artifacts/a%2Fb' } }), + upstreamFetch: async (request) => { + expect(request.redirect).toBe('manual'); + return new Response(null, { status: 307, headers: { location } }); + }, }); - const response = await proxy.handle(rpc()); - - expect(response.status).toBe(307); - expect(response.headers.get('location')).toBe(null); + 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([ diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index e6cb4169d2..959cfcf7aa 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -35,10 +35,9 @@ import { * `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. 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 to its - * client, which applies its own redirect rules. 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. + * 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. * On transfer routes, the proxy bounds its own response and body waits, even if the transport @@ -149,6 +148,14 @@ const FORWARDED_REQUEST_HEADERS = [ 'x-artifact-hash-algorithm', DAEMON_HTTP_TENANT_HEADER, ]; +const FORWARDED_RESPONSE_HEADERS = [ + 'content-type', + 'content-disposition', + 'x-request-id', + DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, +]; +const FORWARDED_UPLOAD_CHUNK_RESPONSE_HEADERS = ['range', 'x-upload-offset']; +const FORWARDED_ARTIFACT_DOWNLOAD_RESPONSE_HEADERS = ['content-length']; export function createDaemonProxy(options: DaemonProxyOptions): DaemonProxy { const normalized = normalizeProxyOptions(options); @@ -395,10 +402,9 @@ async function forwardProxyRequest(params: { await options.admitUpstream(); const body = resolveUpstreamBody(request, route, rpcBody, options.upstreamToken, caller.tenantId); const checked = route === DAEMON_HTTP_CHECKED_RPC_ROUTE; - const upstreamUrl = buildUpstreamUrl(options.upstreamBaseUrl, route, request.url); const upstreamResponse = await options.upstreamTransport( route, - forwardedRequest(request, upstreamUrl, { + forwardedRequest(request, buildUpstreamUrl(options.upstreamBaseUrl, route, request.url), { method: request.method, headers: buildUpstreamHeaders(request.headers, options.upstreamToken, route, caller.tenantId), signal: upstreamSignal(request, options), @@ -411,17 +417,7 @@ async function forwardProxyRequest(params: { if (refusal) return refusal; } - const { relayedResponseHeaders } = await import('./upstream-response-relay.ts'); - const headers = relayedResponseHeaders({ - upstreamResponse, - upstreamUrl, - requestUrl: request.url, - requestId: resolveRequestId(request), - route, - upstreamBaseUrl: options.upstreamBaseUrl, - upstreamToken: options.upstreamToken, - publicOrigin: options.publicOrigin, - }); + const headers = copyProxyResponseHeaders(upstreamResponse, request, route); if (isUploadPreflightRoute(route)) { return await rewrittenUploadPreflightResponse({ request, @@ -462,6 +458,27 @@ function upstreamSignal(request: Request, options: NormalizedProxyOptions): Abor return AbortSignal.any([request.signal, AbortSignal.timeout(options.upstreamTimeoutMs)]); } +function copyProxyResponseHeaders( + upstreamResponse: Response, + request: Request, + route: string, +): Headers { + const headers = new Headers(); + for (const name of [...FORWARDED_RESPONSE_HEADERS, ...routeResponseHeaders(route)]) { + const value = upstreamResponse.headers.get(name); + if (value) headers.set(name, value); + } + if (!headers.has('x-request-id')) headers.set('x-request-id', resolveRequestId(request)); + return headers; +} + +/** `content-length` stays off the preflight route because the proxy rewrites that body. */ +function routeResponseHeaders(route: string): readonly string[] { + if (route.startsWith('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/upload/direct/')) return FORWARDED_UPLOAD_CHUNK_RESPONSE_HEADERS; + if (route.startsWith('/artifacts/')) return FORWARDED_ARTIFACT_DOWNLOAD_RESPONSE_HEADERS; + return []; +} + async function rewrittenUploadPreflightResponse(params: { request: Request; upstreamResponse: Response; diff --git a/packages/proxy/src/upstream-response-relay.ts b/packages/proxy/src/upstream-response-relay.ts deleted file mode 100644 index 26d4aa1ee7..0000000000 --- a/packages/proxy/src/upstream-response-relay.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { - DAEMON_HTTP_BASE_PATH, - DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, -} from '@agent-device/contracts/daemon-http'; - -// Which upstream response headers a proxied response carries, the same on every route and -// transport. Loaded with the first forwarded response, never at module scope. - -const FORWARDED_RESPONSE_HEADERS = [ - 'content-type', - 'content-disposition', - 'x-request-id', - DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, -]; -const FORWARDED_UPLOAD_CHUNK_RESPONSE_HEADERS = ['range', 'x-upload-offset']; -const FORWARDED_ARTIFACT_DOWNLOAD_RESPONSE_HEADERS = ['content-length']; - -export type RelayedResponse = { - upstreamResponse: Response; - /** The URL the upstream request went to; a relative `Location` resolves against it. */ - upstreamUrl: URL; - /** The client request's URL: its origin and base path are where a relayed target points. */ - requestUrl: string; - requestId: string; - route: string; - upstreamBaseUrl: string; - upstreamToken: string; - publicOrigin: string | undefined; -}; - -/** The headers a proxied response carries: the allowlist, the request id, and a safe `Location`. */ -export function relayedResponseHeaders(relay: RelayedResponse): Headers { - const headers = new Headers(); - for (const name of [...FORWARDED_RESPONSE_HEADERS, ...routeResponseHeaders(relay.route)]) { - const value = relay.upstreamResponse.headers.get(name); - if (value) headers.set(name, value); - } - if (!headers.has('x-request-id')) headers.set('x-request-id', relay.requestId); - const location = relayedLocation(relay); - if (location) headers.set('location', location); - return headers; -} - -/** `content-length` stays off the preflight route because the proxy rewrites that body. */ -function routeResponseHeaders(route: string): readonly string[] { - if (route.startsWith('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/upload/direct/')) return FORWARDED_UPLOAD_CHUNK_RESPONSE_HEADERS; - if (route.startsWith('/artifacts/')) return FORWARDED_ARTIFACT_DOWNLOAD_RESPONSE_HEADERS; - return []; -} - -/** - * The `Location` of a relayed upstream 3xx, as the client must see it. Only a target on the - * upstream daemon itself is relayed, as a path moved onto the client-facing origin and base path - * the request came in on. Its query and fragment are dropped: the daemon redirects with neither, - * and both can carry a credential. A target elsewhere, with userinfo, or whose path holds the - * upstream token, as serialized or decoded, is dropped whole: the proxy never hands a client a - * credential or a foreign destination. - */ -function relayedLocation(relay: RelayedResponse): string | undefined { - const raw = relay.upstreamResponse.headers.get('location'); - if (!raw) return undefined; - const target = URL.parse(raw, relay.upstreamUrl); - const upstreamBase = new URL(relay.upstreamBaseUrl); - if (!target || target.origin !== upstreamBase.origin || target.username || target.password) { - return undefined; - } - const decoded = decodedPath(target); - if ( - decoded === undefined || - [target.pathname, decoded].some((path) => path.includes(relay.upstreamToken)) - ) { - return undefined; - } - const basePath = upstreamBase.pathname.replace(/\/+$/, ''); - if (basePath && target.pathname !== basePath && !target.pathname.startsWith(`${basePath}/`)) { - return undefined; - } - const requestUrl = new URL(relay.requestUrl); - const prefix = requestUrl.pathname.startsWith(`${DAEMON_HTTP_BASE_PATH}/`) - ? DAEMON_HTTP_BASE_PATH - : ''; - const relayed = new URL(relay.publicOrigin ?? requestUrl.origin); - relayed.pathname = `${prefix}${target.pathname.slice(basePath.length) || '/'}`; - return relayed.toString(); -} - -/** The path as the daemon would read it, or `undefined` for one with a malformed escape. */ -function decodedPath(url: URL): string | undefined { - try { - return decodeURIComponent(url.pathname); - } catch { - return undefined; - } -} diff --git a/packages/react-native/src/companion/client-companion-local-relay.ts b/packages/react-native/src/companion/client-companion-local-relay.ts index 22fbbe14af..492763108e 100644 --- a/packages/react-native/src/companion/client-companion-local-relay.ts +++ b/packages/react-native/src/companion/client-companion-local-relay.ts @@ -1,4 +1,4 @@ -import { fetchWithCredential } from '@agent-device/contracts/credential-transport'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { AppError } from '@agent-device/kernel/errors'; import { normalizeBaseUrl } from '../metro/base-url.ts'; @@ -25,9 +25,15 @@ export function relayTarget(localBaseUrl: string, requestPath: string): URL { return target; } -/** Sends one relayed request. One that carries a credential meets the credential transport rule. */ +/** + * 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))) return await fetch(target, init); - return await fetchWithCredential(target, init, { subject: 'Metro companion local base URL' }); + 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 index 019920684b..7e67a9b20b 100644 --- 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 @@ -189,12 +189,13 @@ test('a refused socket URL ends the worker process as failed', async () => { }); /** A server recording the credential headers of each request that reaches it. */ -async function listenLocalServer(location?: () => string) { +async function listenLocalServer(location?: () => string, redirectPath = '/redirect') { const received: string[] = []; const server = http.createServer((req, res) => { - received.push(`${req.url} ${req.headers.authorization ?? req.headers.cookie ?? '-'}`); + const { authorization, cookie, 'x-app-secret': custom } = req.headers; + received.push(`${req.url} ${authorization ?? cookie ?? custom ?? '-'}`); req.resume(); - if (location && req.url === '/redirect') res.writeHead(307, { location: location() }).end(); + if (location && req.url === redirectPath) res.writeHead(307, { location: location() }).end(); else res.end('bundle'); }); cleanupTasks.push(() => closeLoopbackServer(server)); @@ -259,14 +260,57 @@ test.each([ assert.deepEqual(local.received, ['/index.bundle -']); }); -test('a relayed credential stays on the origin of the local base URL', async () => { - const other = await listenLocalServer(); - const local = await listenLocalServer(() => `${other.origin}/redirected`); - const bridge = await relayingBridge(local.origin); +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, []); + }, +); - const redirected = await bridge.relay(httpRequest('/redirect', { cookie: 'session=app' })); +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(redirected.status, 307); - assert.deepEqual(local.received, ['/redirect session=app']); - assert.deepEqual(other.received, []); + 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 reaches another origin without the bearer token', 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, [undefined]); }); 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 8cfe43b8f9..ac44f81778 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.ts @@ -26,7 +26,6 @@ import { normalizeBaseUrl } from '../metro/base-url.ts'; import { assertSecureCredentialSocket, assertSecureCredentialTransport, - fetchWithCredential, isCredentialTransportRefusal, } from '@agent-device/contracts/credential-transport'; import { fetchRelayedRequest, relayTarget } from './client-companion-local-relay.ts'; @@ -92,16 +91,12 @@ async function registerCompanion( const registerUrl = bearerDestination(options.serverBaseUrl, registerPath); let response: Response; try { - response = await fetchWithCredential( - registerUrl, - { - method: 'POST', - headers: createHeaders(options.serverBaseUrl, options.bearerToken), - body: JSON.stringify(buildCompanionPayload(options)), - signal: AbortSignal.timeout(COMPANION_REGISTER_TIMEOUT_MS), - }, - { subject: BRIDGE_URL_SUBJECT }, - ); + response = await fetch(registerUrl, { + method: 'POST', + headers: createHeaders(options.serverBaseUrl, options.bearerToken), + body: JSON.stringify(buildCompanionPayload(options)), + signal: AbortSignal.timeout(COMPANION_REGISTER_TIMEOUT_MS), + }); } catch (error) { if (error instanceof Error && error.name === 'TimeoutError') { throw new Error( @@ -174,11 +169,13 @@ function clampRetryDelay(delayMs: number): number { /** * 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/...`). + * give a host to a base without one (`https://` becomes `https://api/...`). The request keeps + * `fetch`'s redirect handling, which drops `authorization` on another origin. */ -function bearerDestination(serverBaseUrl: string, path: string): string { +function bearerDestination(serverBaseUrl: string, path: string): URL { assertSecureCredentialTransport(serverBaseUrl, BRIDGE_URL_SUBJECT); - return `${normalizeBaseUrl(serverBaseUrl)}${path}`; + const url = `${normalizeBaseUrl(serverBaseUrl)}${path}`; + return assertSecureCredentialTransport(url, BRIDGE_URL_SUBJECT); } /** @@ -201,16 +198,12 @@ async function unregisterCompanion(options: CompanionTunnelWorkerOptions): Promi if (!unregisterPath) return; try { const unregisterUrl = bearerDestination(options.serverBaseUrl, unregisterPath); - await fetchWithCredential( - unregisterUrl, - { - method: 'POST', - headers: createHeaders(options.serverBaseUrl, options.bearerToken), - body: JSON.stringify(buildCompanionPayload(options)), - signal: AbortSignal.timeout(2_000), - }, - { subject: BRIDGE_URL_SUBJECT }, - ); + await fetch(unregisterUrl, { + method: 'POST', + headers: createHeaders(options.serverBaseUrl, options.bearerToken), + body: JSON.stringify(buildCompanionPayload(options)), + signal: AbortSignal.timeout(2_000), + }); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); } @@ -236,7 +229,8 @@ async function parseBridgeMessage(event: MessageEvent): Promise ({ @@ -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,51 @@ test('prepareMetroRuntime retries malformed retryable bridge responses after com fs.rmSync(tempRoot, { recursive: true, force: true }); } }); + +test('a redirected bridge request reaches another origin without the bearer token', 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'], + ['/moved', undefined], + ]); + } 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 27882ca527..629a85c4e8 100644 --- a/packages/react-native/src/metro/client-metro.ts +++ b/packages/react-native/src/metro/client-metro.ts @@ -21,10 +21,7 @@ import { type ConfirmedProcessStop, } from '@agent-device/host-kit/process'; import { sleep } from '@agent-device/host-kit/retry'; -import { - assertSecureCredentialTransport, - fetchWithCredential, -} from '@agent-device/contracts/credential-transport'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { ensureMetroCompanion } from '../companion/client-metro-companion.ts'; import type { MetroBridgeDescriptor, @@ -457,24 +454,19 @@ function isRetryableBridgeError(error: unknown): boolean { } async function configureMetroBridge(input: ProxyBridgeRequestOptions): Promise { - const bridgeUrl = `${input.baseUrl}/api/metro/bridge`; let response: Response; try { - response = await fetchWithCredential( - bridgeUrl, - { - method: 'POST', - headers: createProxyHeaders(input.baseUrl, input.bearerToken), - body: JSON.stringify({ - ...input.scope, - ...(input.runtime ? { ios_runtime: input.runtime } : {}), - timeout_ms: input.timeoutMs, - }), - signal: AbortSignal.timeout(input.timeoutMs), - }, - { subject: 'Metro bridge URL' }, - ); + response = await fetch(`${input.baseUrl}/api/metro/bridge`, { + method: 'POST', + headers: createProxyHeaders(input.baseUrl, input.bearerToken), + body: JSON.stringify({ + ...input.scope, + ...(input.runtime ? { ios_runtime: input.runtime } : {}), + timeout_ms: input.timeoutMs, + }), + signal: AbortSignal.timeout(input.timeoutMs), + }); } catch (error) { if (error instanceof Error && error.name === 'TimeoutError') { throw createMetroBridgeRequestError( diff --git a/src/cli/cloud-auth-request.ts b/src/cli/cloud-auth-request.ts index 84fc7a891a..c54e441d64 100644 --- a/src/cli/cloud-auth-request.ts +++ b/src/cli/cloud-auth-request.ts @@ -1,11 +1,12 @@ -import { - fetchWithCredential, - isRedirectStatus, -} from '@agent-device/contracts/credential-transport'; +import { assertSecureCredentialTransport } from '@agent-device/contracts/credential-transport'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { readCloudJsonResponse } from './cloud-response.ts'; const HTTP_TIMEOUT_MS = 15_000; +const MAX_CLOUD_AUTH_REDIRECTS = 3; +const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); +// Fetch turns a POST into a GET without a body on these. A 307 or 308 keeps the method and body. +const GET_REDIRECT_STATUSES = new Set([301, 302, 303]); const CLOUD_AUTH_REQUEST_REASONS = { // A cloud auth request got a redirect it does not follow: to another origin, past the third hop, @@ -29,64 +30,62 @@ export async function postCloudAuthJson(options: { // Passed to the response reader, which calls it on a status it would otherwise reject generically. classifyRejectedBody?: (parsed: unknown) => AppError | undefined; }): Promise { - const response = await fetchCloudOnOneOrigin( + const fetchImpl = options.fetchImpl ?? fetch; + // Every followed hop stays on this origin, so one check covers the chain. + const requestUrl = assertSecureCredentialTransport( new URL(options.pathName, options.baseUrl), - { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify(options.body), - }, - options.fetchImpl, + 'Cloud base URL', ); - return await readCloudJsonResponse(response, { - invalidJsonMessage: `Cloud auth endpoint returned invalid JSON (${response.status}).`, - rejectedMessage: 'Cloud auth endpoint rejected the request.', - classifyRejectedBody: options.classifyRejectedBody, - }); + const post: RequestInit = { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(options.body), + }; + // One timeout covers the whole redirect chain. + const signal = AbortSignal.timeout(HTTP_TIMEOUT_MS); + let url = requestUrl; + let init = post; + for (let redirects = 0; ; redirects += 1) { + const response = await fetchImpl(url, { ...init, redirect: 'manual', signal }); + if (!REDIRECT_STATUSES.has(response.status)) { + return await readCloudJsonResponse(response, { + invalidJsonMessage: `Cloud auth endpoint returned invalid JSON (${response.status}).`, + rejectedMessage: 'Cloud auth endpoint rejected the request.', + classifyRejectedBody: options.classifyRejectedBody, + }); + } + await response.body?.cancel().catch(() => undefined); + url = readRedirectTarget(response, url, requestUrl, redirects); + if (GET_REDIRECT_STATUSES.has(response.status)) init = { method: 'GET' }; + } } -/** - * Sends one credential-bearing cloud request and returns the final answer. The URL must be https, - * or plain http to loopback. A redirect is followed only to the same origin, at most three times, - * and never to a target with a username or password. A 301, 302 or 303 turns a POST into a GET - * without its body; a GET keeps its headers on the same origin. - */ -export async function fetchCloudOnOneOrigin( +function readRedirectTarget( + response: Response, + current: URL, requestUrl: URL, - request: RequestInit, - // di-seam-approved: the same fetch-global seam as postCloudAuthJson's fetchImpl. - fetchImpl?: typeof fetch, -): Promise { - const response = await fetchWithCredential( - requestUrl, - // One timeout covers the whole redirect chain. - { ...request, signal: AbortSignal.timeout(HTTP_TIMEOUT_MS) }, - { subject: 'Cloud base URL', send: fetchImpl }, - ); - if (!isRedirectStatus(response.status)) return response; - await response.body?.cancel().catch(() => undefined); - throw redirectRefused(response, requestUrl); -} - -/** Why a redirect the send did not follow ends the request. */ -function redirectRefused(response: Response, requestUrl: URL): AppError { + redirects: number, +): URL { const location = response.headers.get('location'); - const target = location === null ? null : URL.parse(location, requestUrl); - return new AppError( - 'COMMAND_FAILED', - `Cloud auth endpoint answered with ${describeRefusedRedirect(target, requestUrl)}.`, - { - reason: CLOUD_AUTH_REQUEST_REASONS.redirectRefused.reason, - status: response.status, - hint: `Cloud auth requests stay on ${requestUrl.origin}. Check that it is the cloud API origin.`, - }, - ); + const target = location === null ? null : URL.parse(location, current); + const refusal = describeRefusedRedirect(target, requestUrl, redirects); + if (target && !refusal) return target; + throw new AppError('COMMAND_FAILED', `Cloud auth endpoint answered with ${refusal}.`, { + reason: CLOUD_AUTH_REQUEST_REASONS.redirectRefused.reason, + status: response.status, + hint: `Cloud auth requests stay on ${requestUrl.origin}. Check that it is the cloud API origin.`, + }); } -function describeRefusedRedirect(target: URL | null, requestUrl: URL): string { +function describeRefusedRedirect( + target: URL | null, + requestUrl: URL, + redirects: number, +): string | undefined { if (!target) return 'a redirect that has no readable Location'; // Fetch rejects such a URL with an error that quotes it, and the target can echo a credential. if (target.username || target.password) return 'a redirect to a URL with a username or password'; if (target.origin !== requestUrl.origin) return 'a redirect to another origin'; - return 'more than three redirects'; + if (redirects >= MAX_CLOUD_AUTH_REDIRECTS) return 'more than three redirects'; + return undefined; } diff --git a/src/cli/connection/cloud-profile-transport.test.ts b/src/cli/connection/cloud-profile-transport.test.ts index cc0b8d89ce..22e1bb7e7b 100644 --- a/src/cli/connection/cloud-profile-transport.test.ts +++ b/src/cli/connection/cloud-profile-transport.test.ts @@ -1,8 +1,9 @@ // `connect cloud` sends its bearer token to the cloud profile endpoint only over https, or plain // http to loopback. -import { test, vi } from 'vitest'; +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'; @@ -11,17 +12,44 @@ 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({ @@ -33,13 +61,7 @@ test('connect cloud never sends its bearer token to a plain http cloud off loopb try { await assert.rejects( - async () => - await connectCommand({ - host: createTestHostEnvironment(), - positionals: [], - flags: { json: true, help: false, version: false, stateDir }, - client: {} as AgentDeviceClient, - }), + async () => await connectCloud(stateDir), (error: unknown) => normalizeError(error).details?.reason === 'insecure_credential_transport', ); assert.equal(send.mock.calls.length, 0); @@ -48,3 +70,20 @@ test('connect cloud never sends its bearer token to a plain http cloud off loopb send.mockRestore(); } }); + +test('a redirected profile request reaches another origin without the bearer token', 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, [undefined]); +}); diff --git a/src/cli/connection/cloud-profile.ts b/src/cli/connection/cloud-profile.ts index 2eda7117ec..1a29107650 100644 --- a/src/cli/connection/cloud-profile.ts +++ b/src/cli/connection/cloud-profile.ts @@ -1,15 +1,16 @@ 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'; -import { fetchCloudOnOneOrigin } from '../cloud-auth-request.ts'; import { readCloudJsonResponse } from '../cloud-response.ts'; import { persistAndResolveGeneratedProfile } from './generated-config.ts'; import { buildConnectClientId } from './client-id.ts'; const CONNECTION_PROFILE_PATH = '/api/control-plane/connection-profile'; +const HTTP_TIMEOUT_MS = 15_000; type CloudConnectionProfileResponse = { connection?: { @@ -71,11 +72,17 @@ async function fetchConnectionProfile(options: { // on the request itself. fetchImpl?: typeof fetch; }): Promise { - const response = await fetchCloudOnOneOrigin( + const fetchImpl = options.fetchImpl ?? fetch; + const profileUrl = assertSecureCredentialTransport( new URL(CONNECTION_PROFILE_PATH, options.cloudBaseUrl), - { method: 'GET', headers: { authorization: `Bearer ${options.accessToken}` } }, - options.fetchImpl, + 'Cloud base URL', ); + // `fetch` drops `authorization` on a redirect to another origin. + const response = await fetchImpl(profileUrl, { + method: 'GET', + headers: { authorization: `Bearer ${options.accessToken}` }, + signal: AbortSignal.timeout(HTTP_TIMEOUT_MS), + }); const parsed = await readCloudJsonResponse(response, { invalidJsonMessage: `Cloud connection profile endpoint returned invalid JSON (${response.status}).`, rejectedMessage: 'Cloud connection profile endpoint rejected the request.', diff --git a/src/core/limrun-download-file.test.ts b/src/core/limrun-download-file.test.ts index 459e7b2ecf..dcff1f8997 100644 --- a/src/core/limrun-download-file.test.ts +++ b/src/core/limrun-download-file.test.ts @@ -3,7 +3,7 @@ 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'; @@ -243,3 +243,72 @@ test('an https redirect to another origin is followed without the caller headers ['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 212918bd24..aa90c964da 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -9,18 +9,18 @@ import { type ReasonTable, } from '@agent-device/kernel/errors'; import type { LimrunFileDownload } from '@agent-device/provider-limrun'; -import { - assertSecureCredentialTransport, - fetchWithCredential, -} from '@agent-device/contracts/credential-transport'; +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. 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' }, @@ -41,11 +41,8 @@ export async function downloadLimrunFile(options: LimrunFileDownload): Promise= 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', { @@ -63,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, { 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/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index e1dd4ddcf8..8e3a736d34 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -816,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`. | diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index f715405005..19c60f440b 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -24,8 +24,12 @@ CLI commands run through a per-user background daemon: 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 is followed only on the same origin, except by a Limrun download, which also follows https to https and drops its headers when it leaves the origin. The proxy follows no upstream redirect; it relays the redirect response to its client. -- The Metro companion opens the host bridge's socket only over `wss`, or `ws` to loopback. A request the bridge relays to your dev server with an `Authorization` or `Cookie` header follows the same rule. +- A redirect never takes a token or key to another origin: + - Cloud sign-in follows redirects only on the same origin. + - Cloud profile requests, and Metro host bridge setup and companion registration, use the standard `fetch` redirect handling. It drops `Authorization` on another origin. The request body, which names the tenant, run, lease, and Metro URLs, can still follow a bridge redirect there. + - 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. From e6b07ffd9467af1bdd267eb8ad19d8bab5f0f296 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 28 Nov 2026 11:18:37 +0100 Subject: [PATCH 20/22] fix(remote): follow no redirect on credentialed bridge and profile requests A followed redirect forwarded the bridge body cross-origin and accepted an https-to-http hop. redirect: 'manual' turns a redirect into the existing non-retryable HTTP failure. Co-Authored-By: Claude Opus 5.5 --- ...nt-companion-tunnel-worker-credential-transport.test.ts | 4 ++-- .../src/companion/client-companion-tunnel-worker.ts | 5 +++-- .../src/metro/client-metro-auto-companion.test.ts | 7 ++----- packages/react-native/src/metro/client-metro.ts | 1 + src/cli/connection/cloud-profile.ts | 2 +- website/docs/docs/security-trust.md | 2 +- 6 files changed, 10 insertions(+), 11 deletions(-) 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 index 7e67a9b20b..682a69c89f 100644 --- 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 @@ -295,7 +295,7 @@ test('a relayed socket never opens over plain ws off loopback', async () => { assert.deepEqual(sink.connections, []); }); -test('a redirected registration reaches another origin without the bearer token', async () => { +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); @@ -312,5 +312,5 @@ test('a redirected registration reaches another origin without the bearer token' await startWorker(bridge.origin).done; assert.deepEqual(bridge.received, [registered]); - assert.deepEqual(received, [undefined]); + 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 ac44f81778..a09ec1e783 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.ts @@ -95,6 +95,7 @@ async function registerCompanion( method: 'POST', headers: createHeaders(options.serverBaseUrl, options.bearerToken), body: JSON.stringify(buildCompanionPayload(options)), + redirect: 'manual', signal: AbortSignal.timeout(COMPANION_REGISTER_TIMEOUT_MS), }); } catch (error) { @@ -169,8 +170,7 @@ function clampRetryDelay(delayMs: number): number { /** * 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/...`). The request keeps - * `fetch`'s redirect handling, which drops `authorization` on another origin. + * give a host to a base without one (`https://` becomes `https://api/...`). */ function bearerDestination(serverBaseUrl: string, path: string): URL { assertSecureCredentialTransport(serverBaseUrl, BRIDGE_URL_SUBJECT); @@ -202,6 +202,7 @@ async function unregisterCompanion(options: CompanionTunnelWorkerOptions): Promi method: 'POST', headers: createHeaders(options.serverBaseUrl, options.bearerToken), body: JSON.stringify(buildCompanionPayload(options)), + redirect: 'manual', signal: AbortSignal.timeout(2_000), }); } catch (error) { 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 c604a949c7..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 @@ -558,7 +558,7 @@ test('prepareMetroRuntime retries malformed retryable bridge responses after com } }); -test('a redirected bridge request reaches another origin without the bearer token', async () => { +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( @@ -596,10 +596,7 @@ test('a redirected bridge request reaches another origin without the bearer toke ), ); - assert.deepEqual(received, [ - ['/api/metro/bridge', 'Bearer shared-token'], - ['/moved', undefined], - ]); + 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 629a85c4e8..0d9554901e 100644 --- a/packages/react-native/src/metro/client-metro.ts +++ b/packages/react-native/src/metro/client-metro.ts @@ -459,6 +459,7 @@ async function configureMetroBridge(input: ProxyBridgeRequestOptions): Promise Date: Sat, 28 Nov 2026 11:20:20 +0100 Subject: [PATCH 21/22] fix(limrun): pass the download URL to fetch as a string Co-Authored-By: Claude Opus 5.5 --- src/core/limrun-download-file.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/limrun-download-file.ts b/src/core/limrun-download-file.ts index aa90c964da..6b04e35c74 100644 --- a/src/core/limrun-download-file.ts +++ b/src/core/limrun-download-file.ts @@ -73,7 +73,7 @@ async function fetchDownload( let target = url; let sent: LimrunFileDownload['headers'] | undefined = headers; for (let followed = 0; ; followed += 1) { - const response = await fetch(target, { headers: sent, signal, redirect: 'manual' }); + 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); From 98a5c0932fe4512376f7187c06b7b5258b0c4110 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 28 Nov 2026 11:24:15 +0100 Subject: [PATCH 22/22] test: expect a redirected cloud profile request to fail Co-Authored-By: Claude Opus 5.5 --- src/cli/connection/cloud-profile-transport.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cli/connection/cloud-profile-transport.test.ts b/src/cli/connection/cloud-profile-transport.test.ts index 22e1bb7e7b..ab9c4fc430 100644 --- a/src/cli/connection/cloud-profile-transport.test.ts +++ b/src/cli/connection/cloud-profile-transport.test.ts @@ -71,7 +71,7 @@ test('connect cloud never sends its bearer token to a plain http cloud off loopb } }); -test('a redirected profile request reaches another origin without the bearer token', async () => { +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(), @@ -85,5 +85,5 @@ test('a redirected profile request reaches another origin without the bearer tok await assert.rejects(async () => await connectCloud(stateDir)); assert.deepEqual(cloud.received, ['Bearer adc_agent_cloud']); - assert.deepEqual(other.received, [undefined]); + assert.deepEqual(other.received, []); });