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
3 changes: 2 additions & 1 deletion packages/provision-kit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@
}
},
"devDependencies": {
"@agent-device/test-kit": "workspace:*",
"ipaddr.js": "^2.5.0",
"undici": "7.30.1"
"socks": "^2.8.11"
}
}
1 change: 1 addition & 0 deletions packages/provision-kit/src/install-source-deadline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ test('a DNS approval stall reports the connect phase timeout', async () => {
assert.deepEqual(error.details, {
reason: 'transfer_phase_timeout',
transferPhase: 'connect',
networkErrorCode: 'connect-timeout',
timeoutMs: 30_000,
});
assert.ok(isRequestCanceledError(error.cause));
Expand Down
132 changes: 127 additions & 5 deletions packages/provision-kit/src/install-source-download.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import assert from 'node:assert/strict';
import dns from 'node:dns/promises';
import fs from 'node:fs/promises';
import path from 'node:path';
import { PassThrough, Readable } from 'node:stream';
import { afterEach, beforeEach, test, vi } from 'vitest';
import { AppError, isRequestCanceledError } from '@agent-device/kernel/errors';
import {
TRANSFER_BODY_INACTIVITY_TIMEOUT_MS,
TRANSFER_CONNECT_TIMEOUT_MS,
TRANSFER_RESPONSE_HEADER_TIMEOUT_MS,
isTransferPhaseTimeoutError,
} from '@agent-device/host-kit/transport';
import { mkdtempForTest } from './tmp-dir.fixtures.ts';
Expand Down Expand Up @@ -171,6 +173,51 @@ test('download identifies the daemon as the requester and preserves the network
}
});

test.for(['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ETIMEDOUT', 'ERR_TLS_CERT_ALTNAME_INVALID'])(
'download preserves %s while waiting for headers and streaming a partial file',
async (code) => {
const tempRoot = await mkdtempForTest('agent-device-download-partial-');
const restoreLookup = mockApprovedLookup();
const transportError = Object.assign(new Error('private transport diagnostic'), { code });
const body = new PassThrough();
const requester = vi
.spyOn(networkTransport, 'requestApprovedUrl')
.mockRejectedValueOnce(transportError)
.mockResolvedValueOnce(response(200, body));
const download = () =>
downloadInstallSource({
tempDir: tempRoot,
url: 'https://example.com/app.apk',
signal: new AbortController().signal,
environment: {},
});
const assertCode = (error: unknown) => {
assert.ok(error instanceof AppError);
assert.equal(error.code, 'COMMAND_FAILED');
assert.deepEqual(error.details, { networkErrorCode: code });
assert.equal(error.cause, transportError);
assert.ok(!error.message.includes(transportError.message));
return true;
};
try {
await assert.rejects(download(), assertCode);
const outcome = assert.rejects(download(), assertCode);
body.write('partial data');
await vi.waitFor(async () => {
assert.equal(await fs.readFile(path.join(tempRoot, 'app.apk'), 'utf8'), 'partial data');
});
body.destroy(transportError);
await outcome;
assert.deepEqual(await fs.readdir(tempRoot), []);
} finally {
body.destroy();
requester.mockRestore();
restoreLookup();
await fs.rm(tempRoot, { recursive: true, force: true });
}
},
);

test('download omits network error codes that are not identifiers', async () => {
const tempRoot = await mkdtempForTest('agent-device-download-network-error-code-');
const lookup = vi
Expand Down Expand Up @@ -286,23 +333,37 @@ function mockApprovedLookup(): () => void {
return () => lookup.mockRestore();
}

function assertPhaseTimeout(error: unknown, phase: string, timeoutMs: number): void {
function assertPhaseTimeout(
error: unknown,
phase: string,
timeoutMs: number,
networkErrorCode: string,
): void {
assert.ok(error instanceof AppError, 'phase expiry must stay a typed AppError');
assert.ok(isTransferPhaseTimeoutError(error), 'phase expiry must keep its typed reason');
assert.equal(isRequestCanceledError(error), false, 'a phase timeout is not caller cancellation');
assert.deepEqual(error.details, {
reason: 'transfer_phase_timeout',
transferPhase: phase,
networkErrorCode,
timeoutMs,
});
}

test('a connect that never completes expires at the adopted connect ceiling with typed evidence', async () => {
test.for([
{ phase: 'connect', timeout: TRANSFER_CONNECT_TIMEOUT_MS, code: 'connect-timeout' },
{
phase: 'response-headers',
timeout: TRANSFER_RESPONSE_HEADER_TIMEOUT_MS,
code: 'header-timeout',
},
])('a stalled $phase reports $code', async ({ phase, timeout, code }) => {
const tempRoot = await mkdtempForTest('agent-device-download-connect-stall-');
const restoreLookup = mockApprovedLookup();
const requestMock = vi.spyOn(networkTransport, 'requestApprovedUrl').mockImplementation(
(args) =>
new Promise<never>((_resolve, reject) => {
if (phase === 'response-headers') args.onConnected?.();
args.signal.addEventListener('abort', () => reject(args.signal.reason), {
once: true,
});
Expand All @@ -316,9 +377,9 @@ test('a connect that never completes expires at the adopted connect ceiling with
environment: process.env,
}).catch((error: unknown) => error);
await flushRealIOMacrotasks();
await vi.advanceTimersByTimeAsync(TRANSFER_CONNECT_TIMEOUT_MS + 1);
await vi.advanceTimersByTimeAsync(timeout + 1);
const error = await outcome;
assertPhaseTimeout(error, 'connect', TRANSFER_CONNECT_TIMEOUT_MS);
assertPhaseTimeout(error, phase, timeout, code);
} finally {
requestMock.mockRestore();
restoreLookup();
Expand All @@ -342,7 +403,8 @@ test('a stalled response body expires at the inactivity ceiling even without cal
await flushRealIOMacrotasks();
await vi.advanceTimersByTimeAsync(TRANSFER_BODY_INACTIVITY_TIMEOUT_MS + 1);
const error = await outcome;
assertPhaseTimeout(error, 'response-body', TRANSFER_BODY_INACTIVITY_TIMEOUT_MS);
assertPhaseTimeout(error, 'response-body', TRANSFER_BODY_INACTIVITY_TIMEOUT_MS, 'body-timeout');
assert.deepEqual(await fs.readdir(tempRoot), []);
} finally {
requestMock.mockRestore();
restoreLookup();
Expand Down Expand Up @@ -430,3 +492,63 @@ test('download and the trusted-source check refuse an unparsable source alike',
);
assert.throws(() => isTrustedInstallSourceUrl(source), expected);
});

test('download keeps the INVALID_ARGS refusal and hint when the source host does not resolve', async () => {
const tempRoot = await mkdtempForTest('agent-device-download-dns-');
const lookup = vi
.spyOn(dns, 'lookup')
.mockRejectedValue(Object.assign(new Error('getaddrinfo ENOTFOUND'), { code: 'ENOTFOUND' }));
const requester = vi.spyOn(networkTransport, 'requestApprovedUrl');
try {
const error = await downloadInstallSource({
tempDir: tempRoot,
url: 'https://typo.example/app.apk',
signal: new AbortController().signal,
environment: {},
}).catch((error: unknown) => error);

assert.ok(error instanceof AppError);
assert.equal(error.code, 'INVALID_ARGS');
assert.equal(error.details?.hint, 'Use a public artifact URL.');
assert.equal(error.details?.networkErrorCode, undefined);
assert.equal(requester.mock.calls.length, 0);
} finally {
requester.mockRestore();
lookup.mockRestore();
await fs.rm(tempRoot, { recursive: true, force: true });
}
});

test('download keeps the typed cancellation when the caller aborts during URL approval', async () => {
const tempRoot = await mkdtempForTest('agent-device-download-approval-abort-');
const controller = new AbortController();
let releaseLookup: () => void = () => {};
const lookup = vi.spyOn(dns, 'lookup').mockImplementation(
async () =>
await new Promise<Awaited<ReturnType<typeof dns.lookup>>>((resolve) => {
releaseLookup = () =>
resolve([{ address: '93.184.216.34', family: 4 }] as unknown as Awaited<
ReturnType<typeof dns.lookup>
>);
queueMicrotask(() => controller.abort());
}),
);
const requester = vi.spyOn(networkTransport, 'requestApprovedUrl');
try {
const error = await downloadInstallSource({
tempDir: tempRoot,
url: 'https://example.com/app.apk',
signal: controller.signal,
environment: {},
}).catch((error: unknown) => error);

assert.ok(error instanceof AppError);
assert.ok(isRequestCanceledError(error));
assert.equal(requester.mock.calls.length, 0);
} finally {
releaseLookup();
requester.mockRestore();
lookup.mockRestore();
await fs.rm(tempRoot, { recursive: true, force: true });
}
});
103 changes: 74 additions & 29 deletions packages/provision-kit/src/install-source-download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,17 @@ async function requestHop(
environment: NodeJS.ProcessEnv,
): Promise<networkTransport.InstallSourceNetworkResponse> {
const { watchdog } = phases;
let approved: Awaited<ReturnType<typeof approveDownloadSourceUrl>>;
try {
approved = await approveDownloadSourceUrl(url, watchdog.signal);
} catch (error) {
// An approval refusal is a typed answer about the URL, not a transport failure.
throw (
phaseTimeout(error, phases) ??
(isSignalFailure(error, watchdog.signal) ? watchdog.signal.reason : error)
);
}
Comment thread
thymikee marked this conversation as resolved.
Resolved
try {
const approved = await approveDownloadSourceUrl(url, watchdog.signal);
return await networkTransport.requestApprovedUrl({
url,
approvedAddress: approved.address,
Expand All @@ -116,24 +125,54 @@ async function requestHop(
onConnected: () => watchdog.arm('response-headers', phases.responseHeaderTimeoutMs),
});
} catch (error) {
if (phases.isPhaseTimeout(error)) throw error;
const reason: unknown = watchdog.signal.reason;
if (reason instanceof AppError && phases.isPhaseTimeout(reason)) {
throw new AppError(reason.code, reason.message, reason.details, error);
}
if (error instanceof AppError) throw error;
const networkErrorCode = readNetworkErrorCode(error);
throw new AppError(
'COMMAND_FAILED',
networkErrorCode
? `The daemon failed to fetch the app source (network error code: ${networkErrorCode})`
: 'The daemon failed to fetch the app source',
networkErrorCode ? { networkErrorCode } : undefined,
error,
);
const timeout = phaseTimeout(error, phases);
if (timeout) throw timeout;
if (isSignalFailure(error, watchdog.signal)) throw watchdog.signal.reason;
if (error instanceof AppError && !readNetworkErrorCode(error.cause)) throw error;
throw downloadNetworkError(error instanceof AppError ? error.cause : error);
Comment thread
thymikee marked this conversation as resolved.
Resolved
}
}

function phaseTimeout(error: unknown, phases: TransferPhaseTools): AppError | undefined {
const reason: unknown = phases.watchdog.signal.reason;
const timeout = phases.isPhaseTimeout(error) ? error : reason;
if (!(timeout instanceof AppError) || !phases.isPhaseTimeout(timeout)) return undefined;
const transferPhase = timeout.details?.transferPhase;
const networkErrorCode =
transferPhase === 'connect'
? 'connect-timeout'
: transferPhase === 'response-headers'
? 'header-timeout'
: 'body-timeout';
return new AppError(
timeout.code,
timeout.message,
{ ...timeout.details, networkErrorCode },
error === timeout ? timeout.cause : error,
);
}

/** A raw failure from the watchdog signal. A typed error that wraps the signal reason keeps its type. */
function isSignalFailure(error: unknown, signal: AbortSignal): boolean {
return (
signal.aborted &&
!(error instanceof AppError) &&
(error === signal.reason || (error instanceof Error && error.cause === signal.reason))
);
}

function downloadNetworkError(error: unknown): AppError {
const networkErrorCode = readNetworkErrorCode(error);
return new AppError(
'COMMAND_FAILED',
networkErrorCode
? `The daemon failed to fetch the app source (network error code: ${networkErrorCode})`
: 'The daemon failed to fetch the app source',
networkErrorCode ? { networkErrorCode } : undefined,
error,
);
}

// Only the code crosses to the caller: a remote daemon's cause message can name
// its resolved addresses, proxy, or server-supplied certificate names.
function readNetworkErrorCode(error: unknown): string | undefined {
Expand Down Expand Up @@ -198,22 +237,28 @@ async function writeResponse(
callback(null, chunk);
},
});
let created = false;
let failureSource: 'body' | 'file' | undefined;
response.body.once('error', () => {
failureSource ??= 'body';
});
const destination = createWriteStream(destinationPath, { flags: 'wx' });
destination.once('open', () => {
created = true;
});
destination.once('error', () => {
failureSource ??= 'file';
});
try {
await pipeline(
response.body,
progress,
byteLimit,
createWriteStream(destinationPath, {
flags: 'wx',
}),
{ signal: watchdog.signal },
);
await pipeline(response.body, progress, byteLimit, destination, { signal: watchdog.signal });
return destinationPath;
} catch (error) {
await fs.rm(destinationPath, { force: true }).catch(() => {});
if (phases.isPhaseTimeout(error)) throw error;
if (phases.isPhaseTimeout(watchdog.signal.reason)) throw watchdog.signal.reason;
throw error;
if (created) await fs.rm(destinationPath, { force: true }).catch(() => {});
const timeout = phaseTimeout(error, phases);
if (timeout) throw timeout;
if (isSignalFailure(error, watchdog.signal)) throw watchdog.signal.reason;
if (error instanceof AppError || failureSource === 'file') throw error;
throw downloadNetworkError(error);
}
}

Expand Down
Loading
Loading