diff --git a/packages/contracts/package.json b/packages/contracts/package.json index bcdc022689..d090b823ad 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -164,6 +164,10 @@ "types": "./src/command-policy.ts", "default": "./src/command-policy.ts" }, + "./credential-transport": { + "types": "./src/credential-transport.ts", + "default": "./src/credential-transport.ts" + }, "./daemon-command-surface": { "types": "./src/daemon-command-surface.ts", "default": "./src/daemon-command-surface.ts" @@ -280,6 +284,10 @@ "types": "./src/interactor-types.ts", "default": "./src/interactor-types.ts" }, + "./loopback-host": { + "types": "./src/loopback-host.ts", + "default": "./src/loopback-host.ts" + }, "./unsupported-interactor": { "types": "./src/unsupported-interactor.ts", "default": "./src/unsupported-interactor.ts" diff --git a/packages/contracts/src/credential-transport.test.ts b/packages/contracts/src/credential-transport.test.ts new file mode 100644 index 0000000000..76b87f3c31 --- /dev/null +++ b/packages/contracts/src/credential-transport.test.ts @@ -0,0 +1,69 @@ +import { expect, test } from 'vitest'; +import { credentialTransportRefusal } from './credential-transport.ts'; +import { isLoopbackHostname } from './loopback-host.ts'; + +test('loopback hostnames are recognized in each spelling a base URL carries', () => { + expect(isLoopbackHostname('LocalHost ')).toBe(true); + expect(isLoopbackHostname('127.0.0.1')).toBe(true); + expect(isLoopbackHostname('[::1]')).toBe(true); + expect(isLoopbackHostname('::ffff:127.0.0.1')).toBe(true); + expect(isLoopbackHostname('0.0.0.0')).toBe(false); + expect(isLoopbackHostname('127.1.2.3')).toBe(true); + expect(isLoopbackHostname('localhost.example.test')).toBe(false); + expect(isLoopbackHostname('')).toBe(false); +}); + +test.each([ + 'https://fleet.example.test/agent-device', + 'https://10.0.0.7:4310', + 'http://127.0.0.1:4310/agent-device', + 'http://127.1:4310', + 'http://[::1]:4310', + 'http://[::ffff:127.0.0.1]:4310', + 'http://LOCALHOST:4310', +])('a credential may travel to %s', (url) => { + expect(credentialTransportRefusal(url, {})).toBeUndefined(); +}); + +test.each([ + 'http://fleet.example.test/agent-device', + 'http://10.0.0.7:4310', + 'http://100.64.1.2:4310', + 'http://0.0.0.0:4310', + 'http://localhost.:4310', + 'http://127.0.0.1.nip.io:4310', + 'ws://127.0.0.1:4310', + 'http:', +])('a credential may not travel to %s', (url) => { + expect(credentialTransportRefusal(url, {})).toMatchObject({ + code: 'INVALID_ARGS', + details: { reason: 'insecure_credential_transport' }, + }); +}); + +test('the refusal names the origin and the override, and nothing else from the URL', () => { + const refusal = credentialTransportRefusal( + 'http://operator:hunter2@fleet.example.test:7777/private?token=secret', + {}, + ); + + expect(refusal?.message).toContain('http://fleet.example.test:7777'); + expect(refusal?.details?.hint).toContain('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1'); + expect(JSON.stringify([refusal?.message, refusal?.details])).not.toMatch( + /operator|hunter2|private|secret/, + ); +}); + +test.each([ + ['1', true], + ['true', false], + ['0', false], + [' 1', false], + ['', false], +])('the override value %j admits plain http: %s', (value, admitted) => { + const refusal = credentialTransportRefusal('http://10.0.0.7:4310', { + AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: value, + }); + + expect(refusal === undefined).toBe(admitted); +}); diff --git a/packages/contracts/src/credential-transport.ts b/packages/contracts/src/credential-transport.ts new file mode 100644 index 0000000000..57fae3bde3 --- /dev/null +++ b/packages/contracts/src/credential-transport.ts @@ -0,0 +1,38 @@ +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import type { EnvMap } from '@agent-device/kernel/source-value'; +import { isLoopbackHostname } from './loopback-host.ts'; + +const CREDENTIAL_TRANSPORT_REASONS = { + // A first-party credential would go to a configured URL that is neither https nor plain http to a + // loopback host, and the CLI or SDK environment does not set + // AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1 (@agent-device/proxy has no override). agent-device + // 0.21.x warns on stderr instead of failing with it; 0.22 refuses with it before sending anything. + insecureTransport: { reason: 'insecure_credential_transport' }, +} as const satisfies ReasonTable<'remote connection'>; + +/** + * The rule for a configured URL that receives a first-party credential: https, or plain http to a + * loopback host. Returns the refusal for any other URL, unless the operator set + * `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1`. The refusal names the origin only. + * + * `env` is the sending process's own environment, never a value from a profile, ticket or peer. + * A sender with no override passes an empty `env` and a `hint` that names its own fixes. + */ +export function credentialTransportRefusal( + url: string, + env: Readonly, + hint = 'Use https, ssh -L, or Tailscale Serve, or set AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1.', +): AppError | undefined { + if (env.AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT === '1') return undefined; + const destination = URL.parse(url); + if (destination?.protocol === 'https:') return undefined; + if (destination?.protocol === 'http:' && isLoopbackHostname(destination.hostname)) { + return undefined; + } + const origin = destination?.origin ?? 'an invalid URL'; + return new AppError('INVALID_ARGS', `Refusing to send a credential in cleartext to ${origin}.`, { + reason: CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason, + origin, + hint, + }); +} diff --git a/packages/contracts/src/loopback-host.ts b/packages/contracts/src/loopback-host.ts new file mode 100644 index 0000000000..05bbb35569 --- /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 a host names this machine: `localhost` or a loopback literal. No name is resolved. */ +export function isLoopbackHostname(hostname: string): boolean { + const normalized = hostname + .trim() + .toLowerCase() + .replace(/^\[(.*)\]$/, '$1'); + if (normalized === 'localhost') return true; + if (net.isIPv4(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv4'); + if (net.isIPv6(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv6'); + return false; +} diff --git a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts new file mode 100644 index 0000000000..4e5a0596aa --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts @@ -0,0 +1,55 @@ +// A remote daemon token over plain http off loopback is warned about from the settings the client +// reads, before the first request leaves. + +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { afterEach, test, vi } from 'vitest'; +import { beginStderrCapture, createTestHostEnvironment } from '@agent-device/test-kit'; +import { assertRemoteServesCheckedRpc } from '../index.ts'; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +/** The stderr written by the time the first request to `daemonBaseUrl` opens; nothing is sent. */ +async function stderrAtFirstSend( + daemonBaseUrl: string, + env: Record = {}, +): Promise { + const stderr = beginStderrCapture(); + let atSend: string | undefined; + vi.spyOn(http, 'request').mockImplementation(() => { + atSend ??= stderr.read(); + throw new Error('stop at the socket'); + }); + try { + await assert.rejects( + assertRemoteServesCheckedRpc( + { daemonBaseUrl, daemonAuthToken: 'remote-secret' }, + createTestHostEnvironment({ env }), + ), + ); + } finally { + stderr.restore(); + } + assert.ok(atSend !== undefined, 'the client never reached the socket'); + return atSend; +} + +test('a plain http daemon off loopback is warned about before the token leaves', async () => { + const warning = await stderrAtFirstSend('http://warned.example.test:7777/agent-device'); + + assert.match(warning, /http:\/\/warned\.example\.test:7777 are sent in cleartext/); + assert.doesNotMatch(warning, /remote-secret|agent-device\/health/); +}); + +test.each([ + ['a loopback daemon', 'http://127.0.0.1:7777', {}], + [ + 'the override in the host environment', + 'http://overridden.example.test:7777', + { AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1' }, + ], +] as const)('%s is not warned about', async (_label, daemonBaseUrl, env) => { + assert.equal(await stderrAtFirstSend(daemonBaseUrl, env), ''); +}); diff --git a/packages/daemon-client/src/__tests__/index.test.ts b/packages/daemon-client/src/__tests__/index.test.ts index 0549473e2a..89964dc5ee 100644 --- a/packages/daemon-client/src/__tests__/index.test.ts +++ b/packages/daemon-client/src/__tests__/index.test.ts @@ -1,5 +1,5 @@ import type { RequestProgressEvent } from '@agent-device/contracts/progress'; -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import assert from 'node:assert/strict'; import http from 'node:http'; import net from 'node:net'; @@ -37,10 +37,13 @@ async function withRemoteDaemonEnv(callback: () => Promise): Promise { 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_AUTH_TOKEN = 'remote-secret'; + // This host is not loopback: the transport warning would reach the tests that read stderr. + vi.stubEnv('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT', '1'); try { return await callback(); } finally { + vi.unstubAllEnvs(); 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 44d62cf525..1d0352cbb7 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -5,6 +5,8 @@ import type { EnsureDaemonOptions, } from '@agent-device/contracts/client'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; +import { admitCredentialDestination } from '@agent-device/host-kit/credential-admission'; import { AppError, normalizeError, type NormalizedError } from '@agent-device/kernel/errors'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import { readReplayDivergenceResume } from '@agent-device/ad-replay/divergence'; @@ -15,7 +17,6 @@ import { type OwnedReplayStateDir, } from '@agent-device/daemon-contracts/daemon-registration-owner'; import { - isLoopbackHostname, resolveDaemonPaths, resolveDaemonServerMode, resolveDaemonTransportPreference, @@ -254,6 +255,8 @@ function resolveRemoteClientSettings( const remoteBaseUrl = resolveRemoteDaemonBaseUrl(rawBaseUrl); const authToken = suppliedAuthToken ?? env.AGENT_DEVICE_DAEMON_AUTH_TOKEN; validateRemoteDaemonTrust(remoteBaseUrl, authToken); + // Every remote request sends the token to this base URL. + if (remoteBaseUrl) admitCredentialDestination(remoteBaseUrl, env); const daemonRpc = resolveDaemonRpcMode(req.flags?.daemonRpc); return { rawBaseUrl, remoteBaseUrl, authToken, daemonRpc }; } 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 7285c2e0b5..a95f512a1d 100644 --- a/packages/daemon-contracts/src/daemon-resolution.ts +++ b/packages/daemon-contracts/src/daemon-resolution.ts @@ -1,6 +1,5 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; -import net from 'node:net'; import path from 'node:path'; import { admitPrivateRoot, @@ -13,6 +12,7 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { type EnvMap } from '@agent-device/kernel/source-value'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; +import { isLoopbackHostname } from '@agent-device/contracts/loopback-host'; import type { OwnerIdentity } from '@agent-device/host-kit/process'; import type { DaemonServerMode, DaemonTransportPreference } from '@agent-device/kernel/contracts'; export type { DaemonServerMode, DaemonTransportPreference }; @@ -278,11 +278,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. @@ -299,18 +294,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/host-kit/package.json b/packages/host-kit/package.json index e75388b928..14b3aa4a9f 100644 --- a/packages/host-kit/package.json +++ b/packages/host-kit/package.json @@ -40,6 +40,10 @@ "types": "./src/command.ts", "default": "./src/command.ts" }, + "./credential-admission": { + "types": "./src/credential-admission.ts", + "default": "./src/credential-admission.ts" + }, "./diagnostics": { "types": "./src/diagnostics.ts", "default": "./src/diagnostics.ts" diff --git a/packages/host-kit/src/credential-admission.test.ts b/packages/host-kit/src/credential-admission.test.ts new file mode 100644 index 0000000000..7930d74cc6 --- /dev/null +++ b/packages/host-kit/src/credential-admission.test.ts @@ -0,0 +1,53 @@ +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; +import { admitCredentialDestination } from './credential-admission.ts'; + +let stderr: string[] = []; + +beforeEach(() => { + stderr = []; + vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { + stderr.push(String(chunk)); + return true; + }); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +test('an insecure destination is warned about once per origin and not refused', () => { + admitCredentialDestination('http://user:hunter2@once.example.test:7777/a?token=secret', {}); + admitCredentialDestination('http://once.example.test:7777/b', {}); + admitCredentialDestination('http://once.example.test:8888', {}); + + expect(stderr).toHaveLength(2); + expect(stderr[0]).toMatch(/^Warning: .*http:\/\/once\.example\.test:7777 .*cleartext/); + expect(stderr[0]).toContain('agent-device 0.22 will refuse this'); + for (const fix of ['https', 'ssh -L', 'Tailscale Serve']) expect(stderr[0]).toContain(fix); + expect(stderr[0]).toContain('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1'); + expect(stderr.join('')).not.toMatch(/user|hunter2|secret/); + expect(stderr[1]).toContain('http://once.example.test:8888'); +}); + +test('a stderr that fails does not change the outcome', () => { + const listeners = process.stderr.listenerCount('error'); + let listenersAtWrite = 0; + vi.mocked(process.stderr.write).mockImplementation(() => { + // A closed reader reports EPIPE as an event; without a listener at write time it is fatal. + listenersAtWrite = process.stderr.listenerCount('error'); + throw new Error('EPIPE'); + }); + + expect(() => admitCredentialDestination('http://broken-stderr.example.test', {})).not.toThrow(); + expect(listenersAtWrite).toBe(listeners + 1); +}); + +test('a secure destination and the override stay silent', () => { + admitCredentialDestination('https://quiet.example.test', {}); + admitCredentialDestination('http://127.0.0.1:4310', {}); + admitCredentialDestination('http://quiet.example.test', { + AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1', + }); + + expect(stderr).toEqual([]); +}); diff --git a/packages/host-kit/src/credential-admission.ts b/packages/host-kit/src/credential-admission.ts new file mode 100644 index 0000000000..aa5cf3966d --- /dev/null +++ b/packages/host-kit/src/credential-admission.ts @@ -0,0 +1,33 @@ +import { credentialTransportRefusal } from '@agent-device/contracts/credential-transport'; +import { escapeTerminalText } from '@agent-device/kernel/redaction'; +import type { EnvMap } from '@agent-device/kernel/source-value'; + +const warnedOrigins = new Set(); + +/** + * The one warn-or-refuse decision for a configured URL that receives a first-party credential. + * 0.21.x warns on stderr, once per origin per loaded package: each published bundle holds its own + * copy of this module. 0.22 throws the refusal instead. + */ +export function admitCredentialDestination( + url: string, + env: Readonly, + hint?: string, +): void { + const refusal = credentialTransportRefusal(url, env, hint); + if (!refusal) return; + const origin = String(refusal.details?.origin); + if (warnedOrigins.has(origin)) return; + warnedOrigins.add(origin); + // The warning is optional output and must not change what the command does. A closed stderr + // reports EPIPE as an 'error' event, which neither a write callback nor `catch` receives. + try { + process.stderr.once('error', () => {}); + process.stderr.write( + escapeTerminalText( + `Warning: credentials for ${origin} are sent in cleartext. agent-device 0.22 will refuse this. ` + + `${String(refusal.details?.hint)}\n`, + ), + ); + } catch {} +} 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 5d92ac6894..b2f3eef769 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -88,6 +88,10 @@ query or fragment. With the CLI, run tunnel, obtain its public name first, then configure and restart the proxy. This replaces the previous first-`X-Forwarded-Proto` behavior. +The setting gives direct-upload tickets an HTTPS origin. Without it, the agent-device client does +not use a plain HTTP ticket (unless `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1` is set) and uploads +through the HTTPS daemon URL instead. Older clients send that upload over plain HTTP. + Without a fixed origin, the Node listener uses the actual socket scheme and one validated `Host` header. Actual Node HTTPS sockets are supported. A custom direct-daemon HTTP embedding behind TLS termination can pass `publicOrigin` to `createDaemonHttpServer`. The built-in daemon listens on @@ -137,6 +141,12 @@ If your Bun deployment needs proxy routing for transfers, set `NODE_USE_ENV_PROX By default, `/rpc`, `/health` and request diagnostics use global `fetch`. +The default transport sends `upstreamToken` to `upstreamBaseUrl`, so use https, a loopback +upstream (`localhost`, `127.0.0.0/8`, or `::1`), or your own `upstreamFetch`. For any other URL, +0.21.x `createDaemonProxy` warns on stderr, and 0.22 refuses to send the token, with reason +`insecure_credential_transport`. With `upstreamFetch`, the URL is not checked: your transport owns +the route. + ### Reach the daemon over your own transport Pass `upstreamFetch` when the daemon is only reachable some other way, such as a tunnel the device 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..c112b38ddc --- /dev/null +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -0,0 +1,57 @@ +// The default upstream transport is judged by its URL once, at construction. A custom transport owns +// its route, so its URL is not judged. + +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; +import { createDaemonProxy, type DaemonProxyOptions } from './daemon-proxy.ts'; + +let stderr = ''; +beforeEach(() => { + stderr = ''; + vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { + stderr += String(chunk); + return true; + }); +}); +afterEach(() => { + vi.restoreAllMocks(); +}); + +const health = () => new Request('https://gateway.example.test/agent-device/health'); + +function proxyFor(upstreamBaseUrl: string, upstreamFetch?: DaemonProxyOptions['upstreamFetch']) { + return createDaemonProxy({ + upstreamBaseUrl, + upstreamToken: 'daemon-secret', + clientToken: 'client-secret', + upstreamFetch, + }); +} + +test('construction warns about a plain http upstream off loopback, ahead of any send', async () => { + const atSend: string[] = []; + vi.spyOn(globalThis, 'fetch').mockImplementation(async () => { + atSend.push(stderr); + return Response.json({ ok: true }); + }); + + const proxy = proxyFor('http://upstream.example.test:4310'); + await vi.waitFor(() => expect(stderr).toContain('http://upstream.example.test:4310')); + expect(atSend).toEqual([]); + + await proxy.handle(health()); + expect(atSend).toEqual([stderr]); + expect(stderr).toContain('Use https, a loopback upstream, or your own upstreamFetch.'); + expect(stderr).not.toMatch(/daemon-secret|AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT/); +}); + +test.each([ + ['a custom transport', 'http://custom.example.test', true], + ['a loopback upstream', 'http://127.0.0.1:4310', false], +])('%s is not warned about', async (_label, upstreamBaseUrl, custom) => { + const answer = async () => Response.json({ ok: true }); + vi.spyOn(globalThis, 'fetch').mockImplementation(answer); + const proxy = proxyFor(upstreamBaseUrl, custom ? answer : undefined); + + expect((await proxy.handle(health())).status).toBe(200); + expect(stderr).toBe(''); +}); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 5e1bb8d15e..92e47a60b1 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -65,7 +65,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`, use https, + * or plain http to loopback: the proxy sends `upstreamToken` to it. + */ upstreamBaseUrl: string; /** Auth token of the upstream daemon. Never leaves the proxy. */ upstreamToken: string; @@ -574,8 +577,27 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti const clientToken = options.authenticate ? undefined : normalizeToken(options.clientToken ?? '', 'clientToken'); - const upstreamFetch = options.upstreamFetch ?? ((request) => fetch(request)); 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 + ? 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.', + ), + ); + // A refusal reaches every request that waits for the verdict. + admission?.catch(() => {}); + const upstreamFetch: DaemonProxyUpstreamFetch = + customUpstreamFetch ?? + (async (request) => { + await admission; + return fetch(request); + }); return { upstreamBaseUrl, publicOrigin: @@ -592,12 +614,14 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti if (!isTransferRoute(route, request.method)) return upstreamFetch(request); const { createNodeTransferFetch, settleUpstreamFetch } = await import('./transfer-transport.ts'); - return customUpstreamFetch - ? settleUpstreamFetch( - (forwarded) => customUpstreamFetch(keepAliveWith(request, forwarded)), - request, - ) - : createNodeTransferFetch()(request); + if (customUpstreamFetch) { + return settleUpstreamFetch( + (forwarded) => customUpstreamFetch(keepAliveWith(request, forwarded)), + request, + ); + } + await admission; + return createNodeTransferFetch()(request); }, }; } 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..7ff03dc725 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 @@ -2,7 +2,11 @@ import { afterEach, test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; -import { mkdtempForTestSync, createTestHostEnvironment } from '@agent-device/test-kit'; +import { + beginStderrCapture, + createTestHostEnvironment, + mkdtempForTestSync, +} from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; vi.mock('../companion/client-metro-companion.ts', () => ({ @@ -550,3 +554,58 @@ test('prepareMetroRuntime retries malformed retryable bridge responses after com fs.rmSync(tempRoot, { recursive: true, force: true }); } }); + +test.each([ + ['warns before', 'http://bridge.example.test', {}, /http:\/\/bridge\.example\.test are sent/], + [ + 'honors the host override for', + 'http://allowed-bridge.example.test', + { AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1' }, + /^$/, + ], +] as const)( + 'prepareMetroRuntime %s a plain http bridge that gets the bearer', + async (_label, proxyBaseUrl, env, expected) => { + const projectRoot = mkdtempForTestSync('agent-device-metro-transport-'); + fs.writeFileSync( + path.join(projectRoot, 'package.json'), + JSON.stringify({ name: 'metro-transport-test', dependencies: { 'react-native': '0' } }), + ); + const stderr = beginStderrCapture(); + const atBridgeSend: Array<{ authorization: string | null; stderr: string }> = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string, init?: RequestInit) => { + if (url.endsWith('/status')) return new Response('packager-status:running'); + const authorization = new Headers(init?.headers).get('authorization'); + atBridgeSend.push({ authorization, stderr: stderr.read() }); + return new Response('{}', { status: 401 }); + }), + ); + + try { + await assert.rejects( + prepareMetroRuntime( + { + projectRoot, + proxyBaseUrl, + proxyBearerToken: 'shared-token', + bridgeScope: TEST_BRIDGE_SCOPE, + reuseExisting: true, + installDependenciesIfNeeded: false, + }, + createTestHostEnvironment({ env }), + ), + /401/, + ); + } finally { + stderr.restore(); + vi.unstubAllGlobals(); + } + + assert.equal(atBridgeSend.length, 1); + assert.equal(atBridgeSend[0]!.authorization, 'Bearer shared-token'); + assert.match(atBridgeSend[0]!.stderr, expected); + assert.doesNotMatch(atBridgeSend[0]!.stderr, /shared-token/); + }, +); diff --git a/packages/react-native/src/metro/client-metro.ts b/packages/react-native/src/metro/client-metro.ts index 7790b69585..19e084a460 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 { admitCredentialDestination } from '@agent-device/host-kit/credential-admission'; import { ensureMetroCompanion } from '../companion/client-metro-companion.ts'; import type { MetroBridgeDescriptor, @@ -707,6 +708,8 @@ function resolveMetroPrepareSettings( normalizeOptionalString(input.proxyBearerToken) ?? '', env, ); + // The bearer goes to this URL. `input.env` does not decide the transport; the host does. + if (proxyEnabled) admitCredentialDestination(proxyBaseUrl, host.env); return { env, 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..9c109dbd01 --- /dev/null +++ b/packages/remote/src/__tests__/upload-client-ticket-transport.test.ts @@ -0,0 +1,85 @@ +// An upload ticket can carry a credential in its headers or query, so a ticket over plain http to a +// host that is not loopback is never used; the upload takes the legacy route on the daemon. + +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; +import { afterEach, test, vi } from 'vitest'; +import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import { uploadArtifact } from '../upload-client.ts'; + +const INSECURE_TICKET = 'http://ticket.invalid/upload/direct/t?signature=secret'; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +/** + * A daemon whose preflights answer `ticketUrls` in turn, and which resets every direct PUT. + * `sentTo` lists the host of every upload request the client opened; those are `node:http` requests. + */ +async function uploadAgainstTickets(ticketUrls: (origin: string) => string[]): Promise<{ + uploadId: string; + requests: string[]; + sentTo: unknown[]; +}> { + const send = vi.spyOn(http, 'request'); + const localPath = path.join(mkdtempForTestSync('agent-device-upload-ticket-'), 'app.apk'); + fs.writeFileSync(localPath, 'apk-bytes'); + const requests: string[] = []; + let origin = ''; + let preflights = 0; + const server = http.createServer((req, res) => { + requests.push(`${req.method} ${req.url}`); + if (req.method === 'PUT') return void req.socket.destroy(); + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + const body = + req.url === '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/upload/preflight' + ? { upload: { url: ticketUrls(origin)[preflights++], headers: {} }, uploadId: 't' } + : { uploadId: 'legacy-upload' }; + res.end(JSON.stringify({ ok: true, ...body })); + }); + }); + origin = `http://127.0.0.1:${await listenOnLoopback(server)}`; + try { + const uploadId = await uploadArtifact({ + localPath, + baseUrl: origin, + token: 'daemon-token', + env: {}, + }); + const sentTo = send.mock.calls.map(([target]) => (target as http.RequestOptions).host); + return { uploadId, requests, sentTo }; + } finally { + await closeLoopbackServer(server); + } +} + +test('an insecure ticket is dropped unsent and the upload takes the legacy route', async () => { + const result = await uploadAgainstTickets(() => [INSECURE_TICKET]); + + assert.equal(result.uploadId, 'legacy-upload'); + // Only the legacy upload opened a request: nothing went to the ticket host. + assert.deepEqual(result.sentTo, ['127.0.0.1']); + assert.deepEqual(result.requests, ['POST /upload/preflight', 'POST /upload']); +}); + +test('an insecure ticket from the retry preflight is dropped too', async () => { + const result = await uploadAgainstTickets((origin) => [ + `${origin}/upload/direct/t`, + INSECURE_TICKET, + ]); + + assert.equal(result.uploadId, 'legacy-upload'); + assert.deepEqual(result.requests, [ + 'POST /upload/preflight', + 'PUT /upload/direct/t', + 'POST /upload/preflight', + 'POST /upload', + ]); + // The first ticket and the legacy upload; the retry ticket's host got nothing. + assert.deepEqual(result.sentTo, ['127.0.0.1', '127.0.0.1']); +}); diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index b390acbbf4..fe6801f52c 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -1,4 +1,4 @@ -import type { EnvMap } from '@agent-device/kernel/source-value'; +import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import { randomUUID } from 'node:crypto'; import { AppError } from '@agent-device/kernel/errors'; import { @@ -27,7 +27,7 @@ type UploadArtifactOptions = { baseUrl: string; token: string; platform?: string; - /** The environment a packaging command (`tar`) starts from. */ + /** The host environment: packaging commands (`tar`) start from it, and it judges ticket URLs. */ env: Readonly; /** The lease this upload is for; every request to the daemon names it in a header. */ leaseId?: string; @@ -92,6 +92,7 @@ async function uploadArtifactWithinBudget( leaseId: options.leaseId, artifact: prepared, uploadAttemptId, + env: options.env, signal: options.signal, }); @@ -106,6 +107,7 @@ async function uploadArtifactWithinBudget( artifact: prepared, preflight, uploadAttemptId, + env: options.env, onProgress: options.onProgress, signal: options.signal, }); @@ -146,6 +148,7 @@ async function tryDirectUploadWithResume(options: { artifact: PreparedUploadArtifact; preflight: Extract; uploadAttemptId: string; + env: HostEnvironment['env']; onProgress?: UploadProgressSink; signal: AbortSignal; }): Promise { @@ -189,6 +192,7 @@ async function retryDirectUpload( leaseId?: string; artifact: PreparedUploadArtifact; uploadAttemptId: string; + env: HostEnvironment['env']; onProgress?: UploadProgressSink; signal: AbortSignal; }, @@ -202,6 +206,7 @@ async function retryDirectUpload( leaseId: options.leaseId, artifact: options.artifact, uploadAttemptId: options.uploadAttemptId, + env: options.env, signal: options.signal, }); if (retryPreflight?.kind === 'cache-hit') { @@ -278,6 +283,7 @@ async function requestUploadPreflight(options: { leaseId?: string; artifact: PreparedUploadArtifact; uploadAttemptId: string; + env: HostEnvironment['env']; signal?: AbortSignal; }): Promise { const preflightUrl = new URL('upload/preflight', options.normalizedBase); @@ -317,7 +323,13 @@ 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 or query. One that breaks the transport rule is + // dropped unsent, and the upload takes the legacy route through the daemon base URL. + const { credentialTransportRefusal } = + await import('@agent-device/contracts/credential-transport'); + return credentialTransportRefusal(preflight.url, options.env) ? undefined : preflight; } async function requestUploadControl( diff --git a/scripts/layering/contracts-exports.snapshot.json b/scripts/layering/contracts-exports.snapshot.json index 085de6563f..eaabe50cbf 100644 --- a/scripts/layering/contracts-exports.snapshot.json +++ b/scripts/layering/contracts-exports.snapshot.json @@ -38,6 +38,7 @@ "@agent-device/contracts/command", "@agent-device/contracts/command-platform-execution", "@agent-device/contracts/command-policy", + "@agent-device/contracts/credential-transport", "@agent-device/contracts/daemon-command-surface", "@agent-device/contracts/daemon-http", "@agent-device/contracts/deploy-result-target", @@ -72,6 +73,7 @@ "@agent-device/contracts/lease-scope", "@agent-device/contracts/local-interactor-operation-set", "@agent-device/contracts/logs-runtime-plan", + "@agent-device/contracts/loopback-host", "@agent-device/contracts/managed-web-backend", "@agent-device/contracts/navigation", "@agent-device/contracts/network-runtime", diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index cb6a890b37..ef6f23a02e 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -611,6 +611,7 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/host-kit/code-signature', '@agent-device/host-kit/code-signature-cache', '@agent-device/host-kit/command', + '@agent-device/host-kit/credential-admission', '@agent-device/host-kit/diagnostics', '@agent-device/host-kit/doctor-lines', '@agent-device/host-kit/file', diff --git a/src/cli/__tests__/auth-session-cloud-transport.test.ts b/src/cli/__tests__/auth-session-cloud-transport.test.ts new file mode 100644 index 0000000000..bb19f45a57 --- /dev/null +++ b/src/cli/__tests__/auth-session-cloud-transport.test.ts @@ -0,0 +1,126 @@ +// Cloud login, refresh and profile requests warn before a credential goes over plain http to a host +// that is not loopback. The stored issuer is judged too, and the override covers it. + +import assert from 'node:assert/strict'; +import { afterEach, test } from 'vitest'; +import { beginStderrCapture, mkdtempForTestSync, type StreamCapture } from '@agent-device/test-kit'; +import { loginWithDeviceAuth, resolveRemoteAuth, writeCliSession } from '../auth-session.ts'; +import { CLI_SESSION_FORMAT_VERSION } from '../cli-session-format.ts'; +import { resolveCloudConnectProfile } from '../connection/cloud-profile.ts'; + +const flags = { + json: false, + help: false, + version: false, + daemonBaseUrl: 'https://bridge.agent-device.dev', +}; + +let stderr: StreamCapture | undefined; +afterEach(() => { + stderr?.restore(); +}); + +/** A cloud that records the stderr written by the time each request reaches it. */ +function recordingCloud(answer: (url: string) => unknown) { + stderr = beginStderrCapture(); + const atSend: string[] = []; + const fetch = async (url: URL | RequestInfo): Promise => { + atSend.push(stderr!.read()); + return Response.json(answer(String(url))); + }; + return { atSend, fetch }; +} + +function storeSession(cloudBaseUrl: string): string { + const stateDir = mkdtempForTestSync('agent-device-cloud-transport-'); + writeCliSession({ + stateDir, + session: { + version: CLI_SESSION_FORMAT_VERSION, + id: 'session-1', + cloudBaseUrl, + refreshCredential: 'adc_refresh_secret', + createdAt: new Date().toISOString(), + }, + }); + return stateDir; +} + +test('login warns before the first request to a plain http cloud', async () => { + const cloud = recordingCloud((url) => + url.endsWith('/start') + ? { + deviceCode: 'device-secret', + userCode: 'ABCD-EFGH', + verificationUri: 'https://cloud.example.test/authorize', + } + : { + status: 'approved', + accessToken: 'adc_agent_login', + cliSession: { id: 'session-new', refreshCredential: 'adc_refresh_new' }, + }, + ); + + await loginWithDeviceAuth({ + stateDir: mkdtempForTestSync('agent-device-cloud-transport-login-'), + flags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'http://login.example.test' }, + io: { + stdinIsTTY: true, + stdoutIsTTY: true, + stderr: { write: () => true }, + openBrowser: async () => {}, + fetch: cloud.fetch, + }, + }); + + assert.equal(cloud.atSend.length, 2); + assert.match(cloud.atSend[0]!, /http:\/\/login\.example\.test are sent in cleartext/); + assert.equal(cloud.atSend[1], cloud.atSend[0], 'one warning per origin'); +}); + +test.each([ + ['warns about', 'http://issuer.example.test', {}, /issuer\.example\.test are sent in cleartext/], + [ + 'honors the override for', + 'http://allowed-issuer.example.test', + { AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1' }, + /^$/, + ], +] as const)('a refresh %s the stored plain http issuer', async (_label, issuer, env, expected) => { + const cloud = recordingCloud(() => ({ accessToken: 'adc_agent_fresh' })); + + await resolveRemoteAuth({ + command: 'snapshot', + flags, + stateDir: storeSession(issuer), + allowInteractiveLogin: false, + env, + io: { fetch: cloud.fetch }, + }); + + assert.equal(cloud.atSend.length, 1); + assert.match(cloud.atSend[0]!, expected); +}); + +test('the profile request warns before it sends the access token', async () => { + const cloud = recordingCloud(() => ({})); + + await assert.rejects( + resolveCloudConnectProfile({ + flags, + stateDir: mkdtempForTestSync('agent-device-cloud-transport-profile-'), + cwd: process.cwd(), + env: { + AGENT_DEVICE_CLOUD_BASE_URL: 'http://profile.example.test', + AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'adc_live_secret', + }, + fetchImpl: cloud.fetch, + }), + /missing profile/, + ); + + assert.equal(cloud.atSend.length, 1); + assert.match(cloud.atSend[0]!, /http:\/\/profile\.example\.test are sent in cleartext/); + assert.doesNotMatch(cloud.atSend[0]!, /adc_live_secret/); +}); diff --git a/src/cli/auth-session.ts b/src/cli/auth-session.ts index 5d3f3aa26b..c428c7828b 100644 --- a/src/cli/auth-session.ts +++ b/src/cli/auth-session.ts @@ -245,6 +245,7 @@ export async function loginWithDeviceAuth(options: { throw buildNonInteractiveLoginError(options.commandLabel ?? 'agent-device connect', env); } const cloudBaseUrl = resolveCloudBaseUrl(env); + (await import('./cloud-auth-request.ts')).admitCloudUrl(cloudBaseUrl, env); const start = await postCloudAuthJson({ baseUrl: cloudBaseUrl, pathName: DEVICE_AUTH_START_PATH, @@ -551,6 +552,7 @@ async function resolveCliSessionAccess(options: { const session = readExchangeableCliSession(stateDir); if (!session || isExpired(session.expiresAt, io?.now)) return null; assertStoredSessionOrigin(session, env); + (await import('./cloud-auth-request.ts')).admitCloudUrl(session.cloudBaseUrl, env); return await exchangeCliSessionAccess({ stateDir, session, flags, io }); }, { io }, diff --git a/src/cli/cloud-auth-request.ts b/src/cli/cloud-auth-request.ts index e074cf5a03..05a901f216 100644 --- a/src/cli/cloud-auth-request.ts +++ b/src/cli/cloud-auth-request.ts @@ -1,6 +1,12 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { readCloudJsonResponse } from './cloud-response.ts'; +/** + * Judges a cloud URL that receives a credential. A flow calls it where it reads the URL, before its + * first request: login for start, poll and exchange, and a refresh for the stored issuer. + */ +export { admitCredentialDestination as admitCloudUrl } from '@agent-device/host-kit/credential-admission'; + const HTTP_TIMEOUT_MS = 15_000; const MAX_CLOUD_AUTH_REDIRECTS = 3; const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); diff --git a/src/cli/connection/cloud-profile.ts b/src/cli/connection/cloud-profile.ts index fe58324e96..4c176abc8f 100644 --- a/src/cli/connection/cloud-profile.ts +++ b/src/cli/connection/cloud-profile.ts @@ -38,6 +38,7 @@ export async function resolveCloudConnectProfile(options: { const profile = await fetchConnectionProfile({ cloudBaseUrl: auth.cloudBaseUrl, accessToken: auth.accessToken, + env: options.env, fetchImpl: options.fetchImpl, }); const clientId = buildConnectClientId( @@ -67,11 +68,14 @@ export async function resolveCloudConnectProfile(options: { async function fetchConnectionProfile(options: { cloudBaseUrl: string; accessToken: string; + env: EnvMap; // di-seam-approved: same fetch-global seam as resolveCloudConnectProfile's fetchImpl above, // on the request itself. fetchImpl?: typeof fetch; }): Promise { const fetchImpl = options.fetchImpl ?? fetch; + const admission = await import('@agent-device/host-kit/credential-admission'); + admission.admitCredentialDestination(options.cloudBaseUrl, options.env); const response = await fetchImpl(new URL(CONNECTION_PROFILE_PATH, options.cloudBaseUrl), { method: 'GET', headers: { authorization: `Bearer ${options.accessToken}` }, diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 165b187607..f1bca72816 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -471,7 +471,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. Use https, or a loopback http URL such as an ssh -L forward: for other plain http URLs, 0.21.x warns that the token travels in cleartext and 0.22 refuses (reason insecure_credential_transport). To allow plain http, set AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1 in the process that sends the credential: here the client, not the proxy host. 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/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index f05449e043..672bd4a996 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -176,9 +176,9 @@ "packages/remote/src/upload-client.ts#isStringRecord": "sha256:b6d6b571b90baf0976d9c347c4a45a4363a4df5ad184ea1087cb3b9febd4b624", "packages/remote/src/upload-client.ts#parseUploadPreflightResult": "sha256:7ce3f43b45c03df8b7f2690432beedc7a537c1bba540961716862f8a632d5623", "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:5689da0c0cd18d0293e5bb05ddc0d8a07d1bca9ab1d94f8ca185b03bc5b8d758", - "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:6976942601980c80ef069a0e1cbd7058840d0384e9e87c48f5dfd8d1c774703c", + "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:3080e4ac4e0d6f46345a3588a88c81152ac74628dd6c03328161188d383a97ff", "packages/remote/src/upload-client.ts#shouldRetryDirectUpload": "sha256:29059f076ff7f2b9540ad15408be48792b2d63a601ef2b9fb2d54f5576d49bbd", - "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:cc5d33f38e047cf3be4bd412b64958c7495eb9a45e58eefadaa00eefa0cb6b53", + "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:405c614f566f1385ac8ef7eebdc064fe93914241aefd46ca5b855f889c4eca83", "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:93a36a9d3dea88064569517f3cdc34f27b33df6bf5f0c0ecc9efc29b47f24b77", "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:1546c696134b47bfaaaffcf95deb176cccdce243818b658ae0494dafb57fafb6", "packages/remote/src/upload-stream.ts#MAX_UPLOAD_REDIRECTS": "sha256:12ff46dfe33a1dce95bdb79c90c17a3ba4f3919e7dc4b3a1b04590fff430f79f", @@ -484,8 +484,8 @@ }, { "declaration": "packages/remote/src/upload-client.ts#tryDirectUploadWithResume", - "digest": "sha256:cc5d33f38e047cf3be4bd412b64958c7495eb9a45e58eefadaa00eefa0cb6b53", - "rationale": "#4441 ends the direct-upload sequence when a transfer phase's own budget expires, instead of re-preflighting for a fresh ticket or falling back, because a second attempt would be permission that budget already refused. Preflight, ticket PUT and finalize requests are unchanged in route, method, headers and body, so a protocol-2 daemon parses everything it parsed before; it just receives no further legs once the caller's aggregate has expired. Its signal is now required, because the preparation aggregate is always the one passed down, and it is read directly; no request changes." + "digest": "sha256:405c614f566f1385ac8ef7eebdc064fe93914241aefd46ca5b855f889c4eca83", + "rationale": "#4441 ends the direct-upload sequence when a transfer phase's own budget expires, instead of re-preflighting for a fresh ticket or falling back, because a second attempt would be permission that budget already refused. Preflight, ticket PUT and finalize requests are unchanged in route, method, headers and body, so a protocol-2 daemon parses everything it parsed before; it just receives no further legs once the caller's aggregate has expired. Its signal is now required, because the preparation aggregate is always the one passed down, and it is read directly; no request changes. The client environment is now passed through to the retry preflight, which judges the ticket URL locally; no request changes." }, { "declaration": "packages/remote/src/upload-client.ts#uploadLegacyArtifact", @@ -554,8 +554,8 @@ }, { "declaration": "packages/remote/src/upload-client.ts#requestUploadPreflight", - "digest": "sha256:6976942601980c80ef069a0e1cbd7058840d0384e9e87c48f5dfd8d1c774703c", - "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs." + "digest": "sha256:3080e4ac4e0d6f46345a3588a88c81152ac74628dd6c03328161188d383a97ff", + "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. The client now also drops a direct-upload ticket whose URL is plain http to a host that is not loopback, unless the operator's environment overrides it, and takes the legacy upload route a released daemon already serves when it hands out no usable ticket. The preflight request and response shapes are unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#finalizeDirectUpload", diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 7eaa6820a3..d2eca1ccfb 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2565,7 +2565,7 @@ Exact behavior: `agent-device help proxy`. -Run `proxy` on the machine that can reach the simulator, emulator, or device, and drive it from another machine through an HTTP tunnel. It prints a daemon auth token: anyone who has it can control the daemon behind the proxy. Pass `--public-origin` when the tunnel terminates TLS, so app uploads use HTTPS. See [Remote proxy](/docs/remote-proxy) for the tunnel setup and `connect proxy`. +Run `proxy` on the machine that can reach the simulator, emulator, or device, and drive it from another machine through an HTTP tunnel. It prints a daemon auth token: anyone who has it can control the daemon behind the proxy. Pass `--public-origin` when the tunnel terminates TLS. It gives direct-upload tickets an HTTPS origin; without it, the client uploads through the HTTPS daemon URL instead, and older clients send that upload over plain HTTP. See [Remote proxy](/docs/remote-proxy) for the tunnel setup and `connect proxy`. ## Remote Metro workflow diff --git a/website/docs/docs/configuration.md b/website/docs/docs/configuration.md index f90673ebbd..9890bb3fc5 100644 --- a/website/docs/docs/configuration.md +++ b/website/docs/docs/configuration.md @@ -148,6 +148,7 @@ Only the variables below, and those documented on command pages, are supported. | Android test IME | `AGENT_DEVICE_TEST_IME` | Public. Same setting as `--test-ime` / `--no-test-ime` on `open`, `test`, and `replay`; see known limitations. | | Local daemon storage | `AGENT_DEVICE_STATE_DIR` | Public. The daemon and the CLI store the daemon's record, lock, log, and recordings there, so the directory must belong to you alone: a real directory, not a symbolic link, that you own with mode `0700`, with every directory above it owned by you or root and not writable by group or other users (a shared directory that is sticky, like `/tmp`, is allowed). Every route that starts, attaches to, stops or reports on the daemon checks that first, before it reads or writes anything there. A missing directory is created at `0700` when a command starts a daemon, and is left missing when a command only reports. A directory you own that is open to the group or other users is closed to `0700` by that check, so a directory created by another program under a permissive umask, or left open by an older version, never stops the daemon. Anything else fails the check, with `details.reason: "daemon_state_root_unsafe"`, naming the directory and the step that ends it: `details.fix` runs `chmod 700` on that directory, or points `AGENT_DEVICE_STATE_DIR` at a real private directory you own, such as `$HOME/.agent-device`, when even that change is refused. For anything besides the mode bits it names that move, because a mode change cannot make a symbolic link, another owner's directory, or a directory other accounts can write private. The check reads owner and mode bits and symbolic links, so it applies on macOS and Linux. On Windows agent-device only rejects a path shape it cannot support — a network path such as `\\server\share`, a device path such as `\\.\pipe\`, or a drive-relative path such as `C:state` — because there protection between accounts is not a question of mode bits, and a missing directory is still created when a command starts a daemon. | | Recording helper cache | `AGENT_DEVICE_SWIFT_CACHE_DIR` | Public operator control, read on macOS hosts. Recording compiles small Swift helpers and caches them here. The default is `~/Library/Caches/agent-device/swift-cache`. You or root must own the directory and every directory above it, and the group and other users must not have write access to any of them, even with the sticky bit set. A normal home directory at mode `0755` or `0750` is acceptable, and so are root-owned system directories such as `/Users`. A directory such as `/tmp` is refused. When the rule fails, recording refuses with `details.reason: "swift_cache_untrusted"`. The fix depends on which directory the refusal reports. For the cache root or a directory above it: if the group or other users can write to it, remove that access with `chmod g-w,o-w`; if another user owns it, or if it is a symbolic link, set this variable to a directory that only you can write. For `v3` or a directory inside it (`bin`, `home` and `module-cache`): agent-device creates these at mode `0700` and never deletes them, so if one of them is open to the group or other users, is a symbolic link, or is owned by another user, set this variable to a new directory that only you can write, or remove the reported directory yourself. Do not use `chmod` on it: that clears the refusal but keeps anything written while the directory was open. When recording compiles a Swift helper, it also checks the Xcode that `DEVELOPER_DIR` selects. A helper that is already compiled and cached is reused without checking that selection, so the same value can pass while the cache is warm and be refused when a helper next needs to compile. If that directory, or a directory above it, is owned by another user or open to the group or other users, recording refuses with `details.exposure: "untrusted_developer_dir"`. `/Applications` is the one exception, as stock macOS sets it up. A daemon keeps the `DEVELOPER_DIR` it started with, so unsetting it in your shell is not enough. To fix this, restart the daemon with `DEVELOPER_DIR` unset, or pass `DEVELOPER_DIR=''` to one local command to select the system default, or point it at an Xcode `Contents/Developer` directory, given as an absolute path, that you or root own along with every directory above it. agent-device checks only owner and mode bits, not ACLs. This applies to the default location and to an override. You must make sure that no ACL gives write access to another user. | +| Credential transport | `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT` | Public operator control, read by the CLI or SDK process that sends the credential (not `@agent-device/proxy`). Only `1` allows plain `http://` to a host that is not loopback; see [Remote access](/docs/security-trust#remote-access). | | Metro and install helpers | `AGENT_DEVICE_METRO_BEARER_TOKEN`, `AGENT_DEVICE_BUNDLETOOL_JAR` | Public | | App hooks and logs | `AGENT_DEVICE_APP_EVENT_URL_TEMPLATE`, `AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE`, `AGENT_DEVICE_MACOS_APP_EVENT_URL_TEMPLATE`, `AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE`, `AGENT_DEVICE_APP_LOG_MAX_BYTES`, `AGENT_DEVICE_APP_LOG_MAX_FILES`, `AGENT_DEVICE_APP_LOG_REDACT_PATTERNS`, `AGENT_DEVICE_EVENT_LOG_MAX_BYTES` | Public. Byte caps take whole integers (`5242880`), not `5MB`. | | Apple runner setup | `AGENT_DEVICE_IOS_TEAM_ID`, `AGENT_DEVICE_IOS_SIGNING_IDENTITY`, `AGENT_DEVICE_IOS_PROVISIONING_PROFILE`, `AGENT_DEVICE_IOS_BUNDLE_ID`, `AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH`, `AGENT_DEVICE_IOS_CLEAN_DERIVED`, `AGENT_DEVICE_IOS_RUNNER_CACHE_KEEP` | Public operator controls. Cleanup of an `AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH` override is only automatic for paths under project `.tmp/`; keys in the managed runner cache are swept after a build. No cleanup, rebuild or eviction removes runner products a live session holds: a launch holds its products from the cache decision until its runner lease is published, and the lease holds them after. A rebuild builds new products beside them. `AGENT_DEVICE_IOS_RUNNER_CACHE_KEEP` is the number of most-recent runner cache keys per platform folder (for example `ios-simulator` and `ios-device` are counted separately) guaranteed to survive a new build, the new key included (default 3, `0` keeps all). Keys used in the last day, held by a build, or named by a live runner lease also survive, so it is not a hard disk-usage cap. | diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 8c6ce9c1f6..3bb20787cf 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -901,6 +901,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | +| `insecure_credential_transport` | A first-party credential would go to a configured URL that is neither https nor plain http to a loopback host, and the CLI or SDK environment does not set AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1 (@agent-device/proxy has no override). agent-device 0.21.x warns on stderr instead of failing with it; 0.22 refuses with it before sending anything. | | `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 3198f394ad..91b932471c 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -23,12 +23,14 @@ Read the public HTTPS origin printed by the tunnel. In a second terminal, start agent-device proxy --port 4310 --public-origin https://example.trycloudflare.com ``` -**`--public-origin` is required when the tunnel terminates TLS**, so app uploads use HTTPS. Use the scheme, host and optional port, without the `/agent-device` path. If the tunnel URL changes, restart the proxy with the new origin. +**Set `--public-origin` when the tunnel terminates TLS.** It gives direct-upload tickets the tunnel's HTTPS origin. Without it, the client does not use the plain HTTP ticket (unless `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1` is set) and uploads through the HTTPS daemon URL instead. Older clients send that upload over plain HTTP. Use the scheme, host and optional port, without the `/agent-device` path. If the tunnel URL changes, restart the proxy with the new origin. 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. +Reach the proxy from another machine over an `https://` tunnel URL, or forward a local port with `ssh -L 4310:127.0.0.1:4310 ` and connect to `http://127.0.0.1:4310`. If the client would send the token over plain HTTP to a host that is not loopback, 0.21.x warns on stderr, and 0.22 refuses with `details.reason: "insecure_credential_transport"`. `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1` in the client's environment allows plain HTTP. See [Remote access](./security-trust.md#remote-access). + ## Connect from the agent machine On the machine running the agent, connect to the public tunnel URL with the `/agent-device` base path and the printed token. The connection profile stores only routing metadata, never the token, so export the token once and every command in the shell picks it up. Name the session the same way: diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index c53335c7a9..9e7fd4cc42 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -31,6 +31,26 @@ Holds and leases live in memory; neither survives a daemon restart. When a hook is configured, it must attest a `tenantId` on every request it wants admitted. If the hook's result has no `tenantId`, the daemon rejects the request with 401. It never falls back to a tenant the client declares (RPC body `meta.tenantId` or `flags.tenant`, or the `x-agent-device-tenant` header on the upload, artifact-download, and diagnostics routes), and it never admits the request unscoped. This keeps a caller with a shared token from claiming another tenant's identity, or from reading a tenant-owned session or artifact by declaring no tenant. Deployments without a hook are unaffected. +## Remote access + +The supported remote setup keeps the daemon and proxy HTTP listeners on `127.0.0.1` and reaches them through an encrypted channel: + +- Run `agent-device proxy` on the device host. It binds to `127.0.0.1` by default. +- Expose it through a TLS tunnel such as cloudflared, ngrok, or Tailscale Serve, and start the proxy with `--public-origin` set to the tunnel's HTTPS origin. Or forward it over SSH with `ssh -L`. +- Connect from the agent machine with the `https://` tunnel URL, or with the forwarded `http://127.0.0.1` URL, and the daemon auth token. + +In this setup the token and your device traffic travel between the two machines only inside TLS or SSH. See [Remote proxy setup](./remote-proxy.md) for the commands. + +Before agent-device sends a credential to a plain `http://` URL whose host is not loopback (`localhost`, `127.0.0.0/8`, or `::1`), agent-device 0.21.x warns on stderr, once per origin per loaded package. agent-device 0.22 refuses instead: it fails before it opens a connection, with reason `insecure_credential_transport`. This applies to the remote daemon URL, the cloud URL, the Metro bridge URL, and the upstream URL of [`@agent-device/proxy`](https://www.npmjs.com/package/@agent-device/proxy) with its default transport. Upload tickets are already refused: if a ticket points to plain HTTP, for example because `--public-origin` is missing, the client does not use it and uploads through the daemon URL instead. + +If your network already encrypts the route, for example a WireGuard or Tailscale address, you can allow plain HTTP for one process with `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1`. This silences the warning and lifts the refusal. With this setting, anyone who can read the network path can read your token. Prefer Tailscale Serve or `ssh -L`, which need no override. `@agent-device/proxy` does not read this setting: give its default transport an https or loopback upstream, or supply your own `upstreamFetch`. + +You stay responsible for these points: + +- Keep the daemon auth token secret. Anyone who has it can control the devices behind the proxy. To replace a leaked token, restart the proxy without `--daemon-auth-token`. It prints a new random token. +- If you run a TLS terminator on another machine, protect the hop from it to the proxy. +- If you set `HTTP_PROXY` and your runtime uses it (Bun by default, Node with `NODE_USE_ENV_PROXY=1`), bypass it for every loopback host you use (for example `NO_PROXY=localhost,127.0.0.1,::1`). + ## Apple runner Apple targets (iOS, tvOS, visionOS, and macOS) are driven through an XCTest runner that listens on its own port, separate from the daemon: