Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -225,25 +227,22 @@ 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[] = [];
const ensuring = withEnsuredDaemon(transport, {
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) => {
Expand Down
35 changes: 34 additions & 1 deletion packages/proxy/src/daemon-proxy-credential-transport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,50 @@ 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());

expect(response.status).toBe(400);
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();
});

Expand Down
41 changes: 23 additions & 18 deletions packages/proxy/src/daemon-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ type NormalizedProxyOptions = {
authenticate: DaemonProxyAuthenticate | undefined;
maxRpcBodyBytes: number;
upstreamTimeoutMs: number | undefined;
upstreamAdmission: Promise<void> | undefined;
upstreamFetch: DaemonProxyUpstreamFetch;
upstreamTransport: (route: string, request: Request) => Promise<Response>;
};
Expand All @@ -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',
Expand Down Expand Up @@ -363,6 +365,7 @@ async function readUpstreamHealth(
request: Request,
options: NormalizedProxyOptions,
): Promise<unknown> {
if (options.upstreamAdmission) await options.upstreamAdmission;
const response = await options.upstreamFetch(
forwardedRequest(request, buildDaemonHttpUrl(options.upstreamBaseUrl, 'health'), {
method: 'GET',
Expand All @@ -386,6 +389,7 @@ async function forwardProxyRequest(params: {
caller: ProxyCaller;
}): Promise<Response> {
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(
Expand Down Expand Up @@ -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:
Expand All @@ -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);
Expand All @@ -622,7 +617,6 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti
request,
);
}
await admission;
return createNodeTransferFetch()(request);
},
};
Expand Down Expand Up @@ -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(
{
Expand All @@ -979,7 +973,7 @@ async function proxyErrorResponse(error: unknown, request: Request): Promise<Res
const details = isTransferRoute(resolveProxyRoute(request.url), request.method)
? (await import('./transfer-transport.ts')).transferWireDetails(error)
Comment thread
thymikee marked this conversation as resolved.
Resolved
: {};
const normalized = normalizeError(error);
const normalized = publicProxyError(error);
return Response.json(
{
ok: false,
Expand All @@ -993,3 +987,14 @@ async function proxyErrorResponse(error: unknown, request: Request): Promise<Res
{ status: normalized.code === 'INVALID_ARGS' ? 400 : 500 },
);
}

function publicProxyError(error: unknown): ReturnType<typeof normalizeError> {
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,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
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,
Expand Down Expand Up @@ -672,6 +672,28 @@
}
});

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();
}
});

Check warning on line 695 in packages/react-native/src/companion/client-companion-tunnel-worker.test.ts

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

minor: Companion admission test stubs the insecure-transport override to "1"

The test stubs `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1'` on `process.env` and asserts rejection with `insecure_credential_transport`, but `runCompanionTunnelProcessFromEnv` reads the `env` object from `companionEnv`, not `process.env`, so the stub is inert. The test passes only because the override never reached `credentialTransportRefusal`.
Comment thread
thymikee marked this conversation as resolved.
Resolved

test('metro companion worker proxies bridge http requests to the local server', async () => {
const requests = [
{ requestId: 'req-text', method: 'GET', path: '/text' },
Expand Down
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -699,6 +700,7 @@ export async function runCompanionTunnelProcessFromEnv(
): Promise<boolean> {
const options = readWorkerOptions(argv, env);
if (!options) return false;
admitCredentialDestination(options.serverBaseUrl, env);
await runCompanionTunnelWorker(options, {
exit: (code) => process.exit(code),
registerProcessSignals: true,
Expand Down
Loading