diff --git a/packages/daemon-client/src/__tests__/daemon-client-ensuring.test.ts b/packages/daemon-client/src/__tests__/daemon-client-ensuring.test.ts index b6427cc4d81..f9045b18ddb 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-ensuring.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-ensuring.test.ts @@ -1,9 +1,11 @@ +import { createServer } from 'node:http'; import { setImmediate } from 'node:timers/promises'; import assert from 'node:assert/strict'; import { afterEach, test, vi } from 'vitest'; import { closeLoopbackServer, createTestHostEnvironment, + listenOnLoopback, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; @@ -225,11 +227,12 @@ test('a daemon that disappears between requests is ensured again before the next test('a registered daemon that answers nothing is replaced and reported as unreachable', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const { stateDir, paths } = stateDirAndPaths(); - // Both are bound before the dead one is closed, so the fresh daemon cannot be handed its port. - const closed = await startScriptedDaemon(okResult({})); + const stale = createServer((req) => req.socket.destroy()); + const stalePort = await listenOnLoopback(stale); + t.onTestFinished(() => closeLoopbackServer(stale)); const fresh = await startScriptedDaemon(okResult({})); - await closeLoopbackServer(closed.server); - const { child } = await registerDaemon(paths, { httpPort: closed.port }); + t.onTestFinished(() => closeLoopbackServer(fresh.server)); + const { child } = await registerDaemon(paths, { httpPort: stalePort }); launchesFreshDaemonAt(spawn, paths, fresh.port); const { transport } = recordingTransport(); const replaced: string[] = []; @@ -237,13 +240,9 @@ test('a registered daemon that answers nothing is replaced and reported as unrea onReplaced: (event) => replaced.push(`${event.reason}:${event.previous.pid}`), }); - try { - await ensuring(request('devices', { stateDir, daemonTransport: 'http' })); + await ensuring(request('devices', { stateDir, daemonTransport: 'http' })); - assert.deepEqual(replaced, [`unreachable:${child.pid}`]); - } finally { - await closeLoopbackServer(fresh.server); - } + assert.deepEqual(replaced, [`unreachable:${child.pid}`]); }); test('a failed ensure is retried by the next request instead of being remembered', async (t) => { diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index 28a61fce14a..3307b85b28e 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -23,6 +23,7 @@ function proxyFor(upstreamBaseUrl: string, upstreamFetch?: DaemonProxyOptions['u test('the default upstream refuses non-loopback http even with the client override', async () => { vi.stubEnv('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT', '1'); const fetch = vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ ok: true })); + const setHeader = vi.spyOn(Headers.prototype, 'set'); const response = await proxyFor('http://upstream.example.test:4310').handle(health()); @@ -30,10 +31,42 @@ test('the default upstream refuses non-loopback http even with the client overri expect(await response.json()).toEqual({ ok: false, code: 'INVALID_ARGS', - error: 'Refusing to send a credential in cleartext to http://upstream.example.test:4310.', + error: 'Refusing insecure credential transport.', details: { reason: 'insecure_credential_transport' }, hint: 'Use https, a loopback upstream, or your own upstreamFetch.', }); + expect(setHeader).not.toHaveBeenCalledWith('authorization', 'Bearer daemon-secret'); + expect(fetch).not.toHaveBeenCalled(); +}); + +test('rpc refuses before building upstream credentials and masks the origin', async () => { + const fetch = vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ ok: true })); + const setHeader = vi.spyOn(Headers.prototype, 'set'); + const proxy = proxyFor('http://upstream.example.test:4310'); + const response = await proxy.handle( + 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: 7, method: 'execute', params: {} }), + }), + ); + + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ + jsonrpc: '2.0', + id: 7, + error: { + code: -32602, + message: 'Refusing insecure credential transport.', + data: { + code: 'INVALID_ARGS', + message: 'Refusing insecure credential transport.', + details: { reason: 'insecure_credential_transport' }, + hint: 'Use https, a loopback upstream, or your own upstreamFetch.', + }, + }, + }); + expect(setHeader).not.toHaveBeenCalledWith('authorization', 'Bearer daemon-secret'); expect(fetch).not.toHaveBeenCalled(); }); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 6a2bce01429..6ab4e8788d5 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -121,6 +121,7 @@ type NormalizedProxyOptions = { authenticate: DaemonProxyAuthenticate | undefined; maxRpcBodyBytes: number; upstreamTimeoutMs: number | undefined; + upstreamAdmission: Promise | undefined; upstreamFetch: DaemonProxyUpstreamFetch; upstreamTransport: (route: string, request: Request) => Promise; }; @@ -134,6 +135,7 @@ const DEFAULT_UPLOAD_CREDENTIAL_HEADERS = Object.keys(buildDaemonHttpAuthHeaders const DEFAULT_MAX_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; /** `/health` answers quickly or not at all; its probe never waits on `upstreamTimeoutMs`. */ const UPSTREAM_HEALTH_TIMEOUT_MS = 5_000; +const INSECURE_UPSTREAM_HINT = 'Use https, a loopback upstream, or your own upstreamFetch.'; const DAEMON_PROXY_PREFIX = `${DAEMON_HTTP_BASE_PATH}/`; const FORWARDED_REQUEST_HEADERS = [ 'content-type', @@ -363,6 +365,7 @@ async function readUpstreamHealth( request: Request, options: NormalizedProxyOptions, ): Promise { + if (options.upstreamAdmission) await options.upstreamAdmission; const response = await options.upstreamFetch( forwardedRequest(request, buildDaemonHttpUrl(options.upstreamBaseUrl, 'health'), { method: 'GET', @@ -386,6 +389,7 @@ async function forwardProxyRequest(params: { caller: ProxyCaller; }): Promise { const { request, route, options, rpcBody, caller } = params; + if (options.upstreamAdmission) await options.upstreamAdmission; const body = resolveUpstreamBody(request, route, rpcBody, options.upstreamToken, caller.tenantId); const checked = route === DAEMON_HTTP_CHECKED_RPC_ROUTE; const upstreamResponse = await options.upstreamTransport( @@ -580,26 +584,16 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti ? undefined : normalizeToken(options.clientToken ?? '', 'clientToken'); const customUpstreamFetch = options.upstreamFetch; - // Judged once, here, and only for the default transport: a custom one owns its route. The module - // loads outside the proxy entry, so the default transport waits for the verdict before it sends. - const admission = customUpstreamFetch + // Judge the default upstream once. Wait for the verdict before building any upstream request. + const upstreamAdmission = customUpstreamFetch ? undefined : import('@agent-device/host-kit/credential-admission').then((module) => // No environment overrides the rule here: an embedder that needs another route owns it. - module.admitCredentialDestination( - upstreamBaseUrl, - {}, - 'Use https, a loopback upstream, or your own upstreamFetch.', - ), + module.admitCredentialDestination(upstreamBaseUrl, {}, INSECURE_UPSTREAM_HINT), ); // A refusal reaches every request that waits for the verdict. - admission?.catch(() => {}); - const upstreamFetch: DaemonProxyUpstreamFetch = - customUpstreamFetch ?? - (async (request) => { - await admission; - return fetch(request); - }); + upstreamAdmission?.catch(() => {}); + const upstreamFetch = customUpstreamFetch ?? ((request: Request) => fetch(request)); return { upstreamBaseUrl, publicOrigin: @@ -611,6 +605,7 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti authenticate: options.authenticate, maxRpcBodyBytes: options.maxRpcBodyBytes ?? DEFAULT_MAX_RPC_BODY_BYTES, upstreamTimeoutMs: options.upstreamTimeoutMs, + upstreamAdmission, upstreamFetch, upstreamTransport: async (route, request) => { if (!isTransferRoute(route, request.method)) return upstreamFetch(request); @@ -622,7 +617,6 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti request, ); } - await admission; return createNodeTransferFetch()(request); }, }; @@ -963,7 +957,7 @@ function rpcRefusalResponse(code: number, message: string): Response { /** An `/rpc` failure in the JSON-RPC envelope the client reads its error code and message from. */ function rpcErrorResponse(rpcId: unknown, error: unknown): Response { - const normalized = normalizeError(error); + const normalized = publicProxyError(error); const invalidArgs = normalized.code === 'INVALID_ARGS'; return Response.json( { @@ -979,7 +973,7 @@ async function proxyErrorResponse(error: unknown, request: Request): Promise { + const normalized = normalizeError(error); + if (normalized.details?.reason !== 'insecure_credential_transport') return normalized; + return { + code: normalized.code, + message: 'Refusing insecure credential transport.', + details: { reason: 'insecure_credential_transport' }, + hint: INSECURE_UPSTREAM_HINT, + }; +} 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 cbbae1bb60d..4a64902690f 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, expect, test, vi } from 'vitest'; import { buildCompanionPayload, runCompanionTunnelWorker, @@ -672,6 +672,28 @@ test('companion tunnel entrypoint runs only for its own run args and refuses inc } }); +test('companion admission uses the worker environment before registration', async () => { + vi.stubEnv('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT', '1'); + const fetch = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValue(new Response(null, { status: 400 })); + const env = companionEnv({ + AGENT_DEVICE_COMPANION_TUNNEL_SERVER_BASE_URL: 'http://bridge.example.test', + }); + try { + await expect( + runCompanionTunnelProcessFromEnv([METRO_COMPANION_RUN_ARG], env), + ).rejects.toMatchObject({ + code: 'INVALID_ARGS', + details: { reason: 'insecure_credential_transport' }, + }); + expect(fetch).not.toHaveBeenCalled(); + } finally { + fetch.mockRestore(); + vi.unstubAllEnvs(); + } +}); + test('metro companion worker proxies bridge http requests to the local server', async () => { const requests = [ { requestId: 'req-text', method: 'GET', path: '/text' }, 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 218765af973..a0f802bd113 100644 --- a/packages/react-native/src/companion/client-companion-tunnel-worker.ts +++ b/packages/react-native/src/companion/client-companion-tunnel-worker.ts @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import { admitCredentialDestination } from '@agent-device/host-kit/credential-admission'; import { COMPANION_TUNNEL_LEASE_CHECK_INTERVAL_MS, COMPANION_TUNNEL_RECONNECT_DELAY_MS, @@ -699,6 +700,7 @@ export async function runCompanionTunnelProcessFromEnv( ): Promise { const options = readWorkerOptions(argv, env); if (!options) return false; + admitCredentialDestination(options.serverBaseUrl, env); await runCompanionTunnelWorker(options, { exit: (code) => process.exit(code), registerProcessSignals: true,