From e5d7c6b58a8349d2d84792c35f051757c09044d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 08:30:52 +0100 Subject: [PATCH 1/7] fix(revyl): upload builds only to a public HTTPS destination --- .../src/artifact-upload.test.ts | 55 +++++++++++++++ .../provider-revyl/src/artifact-upload.ts | 67 +++++++++++++++++++ .../provider-revyl/src/deployment.test.ts | 30 +++++++-- packages/provider-revyl/src/revyl-client.ts | 37 +--------- website/docs/docs/error-reasons.md | 3 + website/docs/docs/revyl.md | 3 + 6 files changed, 154 insertions(+), 41 deletions(-) create mode 100644 packages/provider-revyl/src/artifact-upload.test.ts create mode 100644 packages/provider-revyl/src/artifact-upload.ts diff --git a/packages/provider-revyl/src/artifact-upload.test.ts b/packages/provider-revyl/src/artifact-upload.test.ts new file mode 100644 index 00000000000..0eb1371a720 --- /dev/null +++ b/packages/provider-revyl/src/artifact-upload.test.ts @@ -0,0 +1,55 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { expect, test, vi } from 'vitest'; +import { mkdtempForTest } from '@agent-device/test-kit'; +import { uploadRevylArtifact } from './artifact-upload.ts'; + +async function buildFile() { + const filePath = path.join(await mkdtempForTest('revyl-upload-'), 'app.apk'); + await fs.writeFile(filePath, 'apk-bytes'); + return { filePath, size: 9 }; +} + +const upload = async (fetchImpl: typeof fetch, url: string) => + uploadRevylArtifact(fetchImpl, url, await buildFile(), 'application/vnd.android.package-archive'); + +test.each([ + 'https://127.0.0.1/put', + 'https://169.254.169.254/put', + 'https://10.0.0.5/put', + 'https://localhost/put', + 'http://8.8.8.8/put', +])('refuses %s before reading the build', async (url) => { + const fetchImpl = vi.fn(); + const file = { filePath: '/nonexistent/build.apk', size: 9 }; + await expect(uploadRevylArtifact(fetchImpl, url, file, 'x')).rejects.toMatchObject({ + details: { reason: 'revyl_upload_destination_refused' }, + }); + assert.equal(fetchImpl.mock.calls.length, 0); +}); + +test('uploads to a public HTTPS address with no redirect and no Authorization header', async () => { + const fetchImpl = vi.fn(async () => new Response(null, { status: 200 })); + await upload(fetchImpl, 'https://8.8.8.8/put'); + const init = fetchImpl.mock.calls[0]![1]!; + assert.equal(init.method, 'PUT'); + assert.equal(init.redirect, 'error'); + assert.equal(new Headers(init.headers).has('authorization'), false); +}); + +test('a redirect from storage is unreachable, not followed', async () => { + const fetchImpl = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + await expect(upload(fetchImpl, 'https://8.8.8.8/put')).rejects.toMatchObject({ + details: { reason: 'revyl_upload_unreachable' }, + }); +}); + +test('a non-2xx answer surfaces its status', async () => { + const fetchImpl = vi.fn(async () => new Response(null, { status: 403 })); + await expect(upload(fetchImpl, 'https://8.8.8.8/put')).rejects.toMatchObject({ + details: { reason: 'revyl_upload_rejected', status: 403 }, + }); +}); diff --git a/packages/provider-revyl/src/artifact-upload.ts b/packages/provider-revyl/src/artifact-upload.ts new file mode 100644 index 00000000000..a6eba8e6c14 --- /dev/null +++ b/packages/provider-revyl/src/artifact-upload.ts @@ -0,0 +1,67 @@ +import fs from 'node:fs'; +import { Readable } from 'node:stream'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { approveDownloadSourceUrl } from '@agent-device/provision-kit/install-source-network'; + +const REVYL_UPLOAD_REASONS = { + // The storage URL Revyl returned is not an HTTPS URL on a public address. + destinationRefused: { reason: 'revyl_upload_destination_refused' }, + // Revyl storage answered the upload with a non-2xx status. + rejected: { reason: 'revyl_upload_rejected' }, + // Revyl storage never answered the upload, or answered with a redirect. + unreachable: { reason: 'revyl_upload_unreachable' }, +} as const satisfies ReasonTable<'revyl provider'>; + +/** + * Streams the build to the storage URL Revyl returned. The URL must be HTTPS on a public address; the + * upload follows no redirect and carries no Revyl credentials. + */ +export async function uploadRevylArtifact( + fetchImpl: typeof fetch, + uploadUrl: string, + file: Readonly<{ filePath: string; size: number }>, + contentType: string, + signal?: AbortSignal, +): Promise { + const url = URL.parse(uploadUrl); + try { + if (url?.protocol !== 'https:') throw new Error('Upload URL is not HTTPS.'); + await approveDownloadSourceUrl(url, signal); + } catch (error) { + signal?.throwIfAborted(); + throw new AppError( + 'COMMAND_FAILED', + 'Revyl returned an upload destination that is not a public HTTPS address.', + { reason: REVYL_UPLOAD_REASONS.destinationRefused.reason }, + error, + ); + } + // Node streams a request body only in half-duplex mode, which the DOM `RequestInit` type omits. + const init: RequestInit & { duplex: 'half' } = { + method: 'PUT', + headers: { 'Content-Type': contentType, 'Content-Length': String(file.size) }, + body: Readable.toWeb(fs.createReadStream(file.filePath)) as ReadableStream, + duplex: 'half', + redirect: 'error', + ...(signal === undefined ? {} : { signal }), + }; + let response: Response; + try { + response = await fetchImpl(url, init); + } catch (error) { + signal?.throwIfAborted(); + throw new AppError( + 'COMMAND_FAILED', + 'Revyl storage did not accept the app upload.', + { reason: REVYL_UPLOAD_REASONS.unreachable.reason }, + error, + ); + } + if (!response.ok) { + throw new AppError( + 'COMMAND_FAILED', + `Revyl storage refused the app upload with HTTP ${response.status}.`, + { reason: REVYL_UPLOAD_REASONS.rejected.reason, status: response.status }, + ); + } +} diff --git a/packages/provider-revyl/src/deployment.test.ts b/packages/provider-revyl/src/deployment.test.ts index 09bfd95f464..76c8a60b0bc 100644 --- a/packages/provider-revyl/src/deployment.test.ts +++ b/packages/provider-revyl/src/deployment.test.ts @@ -1,7 +1,8 @@ import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import path from 'node:path'; -import { afterEach, test } from 'vitest'; +import { afterEach, test, vi } from 'vitest'; +import * as storageAdmission from '@agent-device/provision-kit/install-source-network'; import { mkdtempForTest } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; import { @@ -15,10 +16,27 @@ import { revylSessionIdForLease } from './device.ts'; const openBackends: RevylFixtureBackend[] = []; afterEach(async () => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); await Promise.all(openBackends.splice(0).map((fixture) => fixture.close())); }); const UPLOAD_PATH = '/api/storage/put'; +const UPLOAD_URL = `https://storage.test${UPLOAD_PATH}`; + +/** Admits the fake storage host and sends its HTTPS uploads to the plain-HTTP fixture. */ +function routeStorageToFixture(fixture: RevylFixtureBackend): void { + vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ + address: '203.0.113.1', + family: 4, + }); + const realFetch = globalThis.fetch; + vi.stubGlobal('fetch', (input: string | URL, init?: RequestInit) => + String(input) === UPLOAD_URL + ? realFetch(new URL(UPLOAD_PATH, fixture.backendUrl), init) + : realFetch(input, init), + ); +} /** The host environment the packer runs `tar` with. */ const ENV = { PATH: '/usr/bin:/bin' }; const DOWNLOAD_URL = 'https://storage.test/session-build'; @@ -26,11 +44,10 @@ const DOWNLOAD_URL = 'https://storage.test/session-build'; /** A backend whose session accepts one upload and reports the install with `result`. */ async function installingBackend(result: Record, status = 'completed') { const sessionId = revylSessionIdForLease('lease-1'); - let backendUrl = ''; const fixture = await startRevylFixtureBackend({ respond: { [`POST /api/v1/execution/device-sessions/${sessionId}/artifacts/upload-url`]: () => ({ - body: { upload_url: `${backendUrl}${UPLOAD_PATH}`, download_url: DOWNLOAD_URL }, + body: { upload_url: UPLOAD_URL, download_url: DOWNLOAD_URL }, }), [`PUT ${UPLOAD_PATH}`]: { body: {} }, 'POST /api/v1/execution/device-proxy/run-1/install_async': { @@ -41,7 +58,7 @@ async function installingBackend(result: Record, status = 'comp }, }, }); - backendUrl = fixture.backendUrl; + routeStorageToFixture(fixture); openBackends.push(fixture); const runtime = fixture.createRuntime(); return { fixture, runtime }; @@ -179,11 +196,10 @@ test('a canceled install reports the cancellation', async () => { test('an install Revyl reports completed without a result is installed, with no identity of its own', async () => { const sessionId = revylSessionIdForLease('lease-1'); - let backendUrl = ''; const fixture = await startRevylFixtureBackend({ respond: { [`POST /api/v1/execution/device-sessions/${sessionId}/artifacts/upload-url`]: () => ({ - body: { upload_url: `${backendUrl}${UPLOAD_PATH}`, download_url: DOWNLOAD_URL }, + body: { upload_url: UPLOAD_URL, download_url: DOWNLOAD_URL }, }), [`PUT ${UPLOAD_PATH}`]: { body: {} }, 'POST /api/v1/execution/device-proxy/run-1/install_async': { @@ -194,7 +210,7 @@ test('an install Revyl reports completed without a result is installed, with no }, }, }); - backendUrl = fixture.backendUrl; + routeStorageToFixture(fixture); openBackends.push(fixture); const { session } = await liveSession(fixture.createRuntime(), 'android'); const dir = await mkdtempForTest('revyl-deploy-'); diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index dc193a820c5..9c803367828 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -11,8 +11,7 @@ import { PROVIDER_LARGE_BODY_LIMIT_BYTES, readBoundedResponse, } from '@agent-device/host-kit/response-body'; -import fs from 'node:fs'; -import { Readable } from 'node:stream'; +import { uploadRevylArtifact } from './artifact-upload.ts'; import { setTimeout as sleep } from 'node:timers/promises'; import type { RevylDeviceSessionStopResponse, @@ -362,38 +361,8 @@ function createRoutedClient(options: RevylRouteOptions): RevylClient { ...(signal === undefined ? {} : { signal }), }); }, - async uploadSessionArtifact(uploadUrl, file, contentType, signal) { - // Node streams a request body only in half-duplex mode, which the DOM `RequestInit` type omits. - const init: RequestInit & { duplex: 'half' } = { - method: 'PUT', - // A presigned PUT needs the length up front; a streamed body would otherwise go chunked. - headers: { 'Content-Type': contentType, 'Content-Length': String(file.size) }, - body: Readable.toWeb(fs.createReadStream(file.filePath)) as ReadableStream, - duplex: 'half', - redirect: 'error', - ...(signal === undefined ? {} : { signal }), - }; - let response: Response; - try { - response = await fetchImpl(uploadUrl, init); - } catch (error) { - throw new AppError( - 'COMMAND_FAILED', - 'Revyl storage did not accept the app upload.', - { reason: REVYL_HTTP_REASONS.unreachable.reason }, - error, - ); - } - if (!response.ok) { - throw new AppError( - 'COMMAND_FAILED', - `Revyl storage refused the app upload with HTTP ${response.status}.`, - { - reason: REVYL_OUTCOME_REASONS.refused.reason, - status: response.status, - }, - ); - } + uploadSessionArtifact(uploadUrl, file, contentType, signal) { + return uploadRevylArtifact(fetchImpl, uploadUrl, file, contentType, signal); }, startInstall(workflowRunId, body, signal) { return json({ diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 7d9fa7d9cfc..05adf9bb2b9 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -1156,6 +1156,9 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | +| `revyl_upload_destination_refused` | The storage URL Revyl returned is not an HTTPS URL on a public address. | +| `revyl_upload_rejected` | Revyl storage answered the upload with a non-2xx status. | +| `revyl_upload_unreachable` | Revyl storage never answered the upload, or answered with a redirect. | | `invalid_provider_app` | Revyl installs the app from a URL, so `--provider-app` cannot name a local file. | | `unsupported_platform` | Revyl rents an iOS simulator or an Android emulator, and the request names neither. | | `unsupported_app_artifact` | Revyl installs an iOS simulator build or an Android .apk, and the build is neither. | diff --git a/website/docs/docs/revyl.md b/website/docs/docs/revyl.md index b9251aaec90..900133b09e9 100644 --- a/website/docs/docs/revyl.md +++ b/website/docs/docs/revyl.md @@ -50,6 +50,9 @@ agent-device install com.example.app ./build/Example.app a simulator `.app` directory, or a `.zip`, `.tar.gz`, or `.tgz` of one. A device `.ipa` does not run on a simulator. For Android, pass the `.apk`. +The build goes only to the HTTPS upload URL that Revyl returns for the job, and only when that URL +resolves to a public address. Uploads refuse redirects and private network destinations. + `install-from-source` takes a build from a URL or a CI artifact instead. agent-device downloads it, reads the app's identifier from it, and installs it the same way: From 28a4e3b13385b9849ad653c3d38a44b1b732b923 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 09:01:48 +0100 Subject: [PATCH 2/7] fix(revyl): connect the build upload to the approved address --- .../src/artifact-upload.test.ts | 83 ++++++++++++++----- .../provider-revyl/src/artifact-upload.ts | 44 ++++++---- .../provider-revyl/src/deployment.test.ts | 20 +---- .../src/hosted-attachment.test.ts | 8 +- packages/provider-revyl/src/revyl-client.ts | 2 +- .../src/upload-storage.fixtures.ts | 22 +++++ website/docs/docs/revyl.md | 3 +- 7 files changed, 124 insertions(+), 58 deletions(-) create mode 100644 packages/provider-revyl/src/upload-storage.fixtures.ts diff --git a/packages/provider-revyl/src/artifact-upload.test.ts b/packages/provider-revyl/src/artifact-upload.test.ts index 0eb1371a720..19c0ca37c92 100644 --- a/packages/provider-revyl/src/artifact-upload.test.ts +++ b/packages/provider-revyl/src/artifact-upload.test.ts @@ -1,18 +1,37 @@ import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; +import https from 'node:https'; import path from 'node:path'; -import { expect, test, vi } from 'vitest'; +import { Readable, Writable } from 'node:stream'; +import { afterEach, expect, test, vi } from 'vitest'; +import * as storageAdmission from '@agent-device/provision-kit/install-source-network'; import { mkdtempForTest } from '@agent-device/test-kit'; import { uploadRevylArtifact } from './artifact-upload.ts'; +afterEach(() => vi.restoreAllMocks()); + async function buildFile() { const filePath = path.join(await mkdtempForTest('revyl-upload-'), 'app.apk'); await fs.writeFile(filePath, 'apk-bytes'); return { filePath, size: 9 }; } -const upload = async (fetchImpl: typeof fetch, url: string) => - uploadRevylArtifact(fetchImpl, url, await buildFile(), 'application/vnd.android.package-archive'); +/** Stands in for the HTTPS request: it records its arguments and answers with `statusCode`. */ +function stubHttps(statusCode: number) { + return vi.spyOn(https, 'request').mockImplementation( + ((_url: URL, _options: https.RequestOptions, callback: (response: Readable) => void) => + new Writable({ + write: (_chunk, _encoding, done) => done(), + final: (done) => { + callback(Object.assign(Readable.from([]), { statusCode })); + done(); + }, + })) as unknown as typeof https.request, + ); +} + +const upload = async (url: string) => + uploadRevylArtifact(url, await buildFile(), 'application/vnd.android.package-archive'); test.each([ 'https://127.0.0.1/put', @@ -21,35 +40,57 @@ test.each([ 'https://localhost/put', 'http://8.8.8.8/put', ])('refuses %s before reading the build', async (url) => { - const fetchImpl = vi.fn(); + const request = stubHttps(200); const file = { filePath: '/nonexistent/build.apk', size: 9 }; - await expect(uploadRevylArtifact(fetchImpl, url, file, 'x')).rejects.toMatchObject({ + await expect(uploadRevylArtifact(url, file, 'x')).rejects.toMatchObject({ details: { reason: 'revyl_upload_destination_refused' }, }); - assert.equal(fetchImpl.mock.calls.length, 0); + assert.equal(request.mock.calls.length, 0); }); -test('uploads to a public HTTPS address with no redirect and no Authorization header', async () => { - const fetchImpl = vi.fn(async () => new Response(null, { status: 200 })); - await upload(fetchImpl, 'https://8.8.8.8/put'); - const init = fetchImpl.mock.calls[0]![1]!; - assert.equal(init.method, 'PUT'); - assert.equal(init.redirect, 'error'); - assert.equal(new Headers(init.headers).has('authorization'), false); +test('connects to the approved address, not a fresh resolution of the host', async () => { + vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ + address: '203.0.113.1', + family: 4, + }); + const request = stubHttps(200); + await upload('https://storage.test/put'); + const [url, options] = request.mock.calls[0]!; + assert.equal((url as URL).hostname, 'storage.test'); + assert.equal(options!.method, 'PUT'); + assert.equal(new Headers(options!.headers as HeadersInit).has('authorization'), false); + const dialed: unknown[] = []; + options!.lookup!('storage.test', {}, (...args: unknown[]) => dialed.push(args)); + options!.lookup!('storage.test', { all: true }, (...args: unknown[]) => dialed.push(args)); + assert.deepEqual(dialed, [ + [null, '203.0.113.1', 4], + [null, [{ address: '203.0.113.1', family: 4 }]], + ]); }); -test('a redirect from storage is unreachable, not followed', async () => { - const fetchImpl = vi.fn(async () => { - throw new TypeError('fetch failed'); +test('an unanswered upload is unreachable', async () => { + vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ + address: '203.0.113.1', + family: 4, }); - await expect(upload(fetchImpl, 'https://8.8.8.8/put')).rejects.toMatchObject({ + vi.spyOn(https, 'request').mockImplementation( + (() => + new Writable({ + write: (_chunk, _encoding, done) => done(new Error('connect refused')), + })) as unknown as typeof https.request, + ); + await expect(upload('https://storage.test/put')).rejects.toMatchObject({ details: { reason: 'revyl_upload_unreachable' }, }); }); -test('a non-2xx answer surfaces its status', async () => { - const fetchImpl = vi.fn(async () => new Response(null, { status: 403 })); - await expect(upload(fetchImpl, 'https://8.8.8.8/put')).rejects.toMatchObject({ - details: { reason: 'revyl_upload_rejected', status: 403 }, +test.each([403, 302])('a %s answer is rejected, not followed', async (status) => { + vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ + address: '203.0.113.1', + family: 4, + }); + stubHttps(status); + await expect(upload('https://storage.test/put')).rejects.toMatchObject({ + details: { reason: 'revyl_upload_rejected', status }, }); }); diff --git a/packages/provider-revyl/src/artifact-upload.ts b/packages/provider-revyl/src/artifact-upload.ts index a6eba8e6c14..9d69dde22e4 100644 --- a/packages/provider-revyl/src/artifact-upload.ts +++ b/packages/provider-revyl/src/artifact-upload.ts @@ -1,5 +1,6 @@ import fs from 'node:fs'; -import { Readable } from 'node:stream'; +import https from 'node:https'; +import { pipeline } from 'node:stream'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { approveDownloadSourceUrl } from '@agent-device/provision-kit/install-source-network'; @@ -17,16 +18,16 @@ const REVYL_UPLOAD_REASONS = { * upload follows no redirect and carries no Revyl credentials. */ export async function uploadRevylArtifact( - fetchImpl: typeof fetch, uploadUrl: string, file: Readonly<{ filePath: string; size: number }>, contentType: string, signal?: AbortSignal, ): Promise { const url = URL.parse(uploadUrl); + let approved: Awaited>; try { if (url?.protocol !== 'https:') throw new Error('Upload URL is not HTTPS.'); - await approveDownloadSourceUrl(url, signal); + approved = await approveDownloadSourceUrl(url, signal); } catch (error) { signal?.throwIfAborted(); throw new AppError( @@ -36,18 +37,27 @@ export async function uploadRevylArtifact( error, ); } - // Node streams a request body only in half-duplex mode, which the DOM `RequestInit` type omits. - const init: RequestInit & { duplex: 'half' } = { - method: 'PUT', - headers: { 'Content-Type': contentType, 'Content-Length': String(file.size) }, - body: Readable.toWeb(fs.createReadStream(file.filePath)) as ReadableStream, - duplex: 'half', - redirect: 'error', - ...(signal === undefined ? {} : { signal }), - }; - let response: Response; + const { address, family } = approved; + let status: number; try { - response = await fetchImpl(url, init); + status = await new Promise((resolve, reject) => { + const request = https.request( + url, + { + method: 'PUT', + headers: { 'Content-Type': contentType, 'Content-Length': String(file.size) }, + // The socket dials the approved address; the URL host still names SNI, the certificate and Host. + lookup: (_host, options, callback) => + options.all ? callback(null, [{ address, family }]) : callback(null, address, family), + ...(signal === undefined ? {} : { signal }), + }, + (response) => { + response.resume(); + resolve(response.statusCode ?? 0); + }, + ); + pipeline(fs.createReadStream(file.filePath), request, (error) => error && reject(error)); + }); } catch (error) { signal?.throwIfAborted(); throw new AppError( @@ -57,11 +67,11 @@ export async function uploadRevylArtifact( error, ); } - if (!response.ok) { + if (status < 200 || status >= 300) { throw new AppError( 'COMMAND_FAILED', - `Revyl storage refused the app upload with HTTP ${response.status}.`, - { reason: REVYL_UPLOAD_REASONS.rejected.reason, status: response.status }, + `Revyl storage refused the app upload with HTTP ${status}.`, + { reason: REVYL_UPLOAD_REASONS.rejected.reason, status }, ); } } diff --git a/packages/provider-revyl/src/deployment.test.ts b/packages/provider-revyl/src/deployment.test.ts index 76c8a60b0bc..9ca100fedcb 100644 --- a/packages/provider-revyl/src/deployment.test.ts +++ b/packages/provider-revyl/src/deployment.test.ts @@ -2,7 +2,6 @@ import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import path from 'node:path'; import { afterEach, test, vi } from 'vitest'; -import * as storageAdmission from '@agent-device/provision-kit/install-source-network'; import { mkdtempForTest } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; import { @@ -12,31 +11,18 @@ import { } from './revyl-backend.fixtures.ts'; import { deployRevylApp } from './deployment.ts'; import { revylSessionIdForLease } from './device.ts'; +import { routeStorageTo } from './upload-storage.fixtures.ts'; const openBackends: RevylFixtureBackend[] = []; afterEach(async () => { vi.restoreAllMocks(); - vi.unstubAllGlobals(); await Promise.all(openBackends.splice(0).map((fixture) => fixture.close())); }); const UPLOAD_PATH = '/api/storage/put'; const UPLOAD_URL = `https://storage.test${UPLOAD_PATH}`; -/** Admits the fake storage host and sends its HTTPS uploads to the plain-HTTP fixture. */ -function routeStorageToFixture(fixture: RevylFixtureBackend): void { - vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ - address: '203.0.113.1', - family: 4, - }); - const realFetch = globalThis.fetch; - vi.stubGlobal('fetch', (input: string | URL, init?: RequestInit) => - String(input) === UPLOAD_URL - ? realFetch(new URL(UPLOAD_PATH, fixture.backendUrl), init) - : realFetch(input, init), - ); -} /** The host environment the packer runs `tar` with. */ const ENV = { PATH: '/usr/bin:/bin' }; const DOWNLOAD_URL = 'https://storage.test/session-build'; @@ -58,7 +44,7 @@ async function installingBackend(result: Record, status = 'comp }, }, }); - routeStorageToFixture(fixture); + routeStorageTo(fixture.backendUrl); openBackends.push(fixture); const runtime = fixture.createRuntime(); return { fixture, runtime }; @@ -210,7 +196,7 @@ test('an install Revyl reports completed without a result is installed, with no }, }, }); - routeStorageToFixture(fixture); + routeStorageTo(fixture.backendUrl); openBackends.push(fixture); const { session } = await liveSession(fixture.createRuntime(), 'android'); const dir = await mkdtempForTest('revyl-deploy-'); diff --git a/packages/provider-revyl/src/hosted-attachment.test.ts b/packages/provider-revyl/src/hosted-attachment.test.ts index 1ce44efc1e2..fb7ca6cfd4e 100644 --- a/packages/provider-revyl/src/hosted-attachment.test.ts +++ b/packages/provider-revyl/src/hosted-attachment.test.ts @@ -10,6 +10,7 @@ import { revylLease } from './revyl-backend.fixtures.ts'; import revyl from './index.ts'; import type { RevylRuntime } from './runtime.ts'; import { deployRevylApp } from './deployment.ts'; +import { routeStorageTo } from './upload-storage.fixtures.ts'; const SESSION = '00000000-0000-4000-8000-000000000001'; const ROUTE = `/v1/sessions/${SESSION}/revyl`; @@ -30,6 +31,7 @@ function refusal(error: unknown): { code?: string; reason?: unknown; hint?: unkn const runtimes: RevylRuntime[] = []; afterEach(async () => { + vi.restoreAllMocks(); await Promise.all(runtimes.splice(0).map(async (runtime) => await runtime.shutdown())); for (const server of servers.splice(0)) { server.closeAllConnections(); @@ -48,7 +50,10 @@ async function fakeRoute(respond: Record Answer)> = {}) [`POST ${ROUTE}/tap`]: { body: { success: true } }, [`GET ${ROUTE}/appearance`]: { body: { success: true, appearance: 'light' } }, [`POST ${ROUTE}/artifacts/upload-url`]: () => ({ - body: { upload_url: `${origin}${UPLOAD_PATH}`, download_url: 'https://storage.test/build' }, + body: { + upload_url: `https://storage.test${UPLOAD_PATH}`, + download_url: 'https://storage.test/build', + }, }), [`PUT ${UPLOAD_PATH}`]: { body: {} }, [`POST ${ROUTE}/install_async`]: { body: { install_id: 'install-1', status: 'accepted' } }, @@ -225,6 +230,7 @@ test('the idle-clock refresh outlives the lease and stops when the token expires test("an install uploads through the route's upload URL", async () => { const route = await fakeRoute(); + routeStorageTo(route.origin); const { runtime } = await attachedRuntime(route.origin); const device = await liveDevice(runtime); const session = runtime.getDeploymentSession(device); diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index 9c803367828..26925684122 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -362,7 +362,7 @@ function createRoutedClient(options: RevylRouteOptions): RevylClient { }); }, uploadSessionArtifact(uploadUrl, file, contentType, signal) { - return uploadRevylArtifact(fetchImpl, uploadUrl, file, contentType, signal); + return uploadRevylArtifact(uploadUrl, file, contentType, signal); }, startInstall(workflowRunId, body, signal) { return json({ diff --git a/packages/provider-revyl/src/upload-storage.fixtures.ts b/packages/provider-revyl/src/upload-storage.fixtures.ts new file mode 100644 index 00000000000..1e3c98b8503 --- /dev/null +++ b/packages/provider-revyl/src/upload-storage.fixtures.ts @@ -0,0 +1,22 @@ +import http from 'node:http'; +import https from 'node:https'; +import { vi } from 'vitest'; +import * as storageAdmission from '@agent-device/provision-kit/install-source-network'; + +/** Admits any storage host and sends its HTTPS uploads to a plain-HTTP fixture origin. */ +export function routeStorageTo(origin: string): void { + vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ + address: '203.0.113.1', + family: 4, + }); + vi.spyOn(https, 'request').mockImplementation((( + url: URL, + options: http.RequestOptions, + callback: (response: http.IncomingMessage) => void, + ) => + http.request( + new URL(url.pathname, origin), + { method: options.method, headers: options.headers, signal: options.signal }, + callback, + )) as typeof https.request); +} diff --git a/website/docs/docs/revyl.md b/website/docs/docs/revyl.md index 900133b09e9..60f30d0a594 100644 --- a/website/docs/docs/revyl.md +++ b/website/docs/docs/revyl.md @@ -163,7 +163,8 @@ with the same `--state-dir`, then rerun the command. See To use a staging or private Revyl backend, set `REVYL_API_URL` to its origin, for example `https://backend.example.com`. It must be HTTPS; plain HTTP is accepted only for a loopback address, -which is what a local fake of the API is for. +which is what a local fake of the API is for. Build uploads go only to public HTTPS storage, so a +private or staging backend that returns private storage URLs cannot install local builds. ## Use it from JavaScript From 2bc19799d89ad4d4427916a9fc5d899f0910400a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 11:00:16 +0100 Subject: [PATCH 3/7] fix(revyl): settle an upload after the answer and the body stream, fix reason docs --- .../src/artifact-upload.test.ts | 20 ++++++++++++++++ .../provider-revyl/src/artifact-upload.ts | 23 +++++++++++++++---- website/docs/docs/error-reasons.md | 2 +- 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/packages/provider-revyl/src/artifact-upload.test.ts b/packages/provider-revyl/src/artifact-upload.test.ts index 19c0ca37c92..37ac3c018ed 100644 --- a/packages/provider-revyl/src/artifact-upload.test.ts +++ b/packages/provider-revyl/src/artifact-upload.test.ts @@ -94,3 +94,23 @@ test.each([403, 302])('a %s answer is rejected, not followed', async (status) => details: { reason: 'revyl_upload_rejected', status }, }); }); + +test('an early 200 does not hide a build stream that fails after the answer', async () => { + vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ + address: '203.0.113.1', + family: 4, + }); + vi.spyOn(https, 'request').mockImplementation((( + _url: URL, + _options: https.RequestOptions, + callback: (response: Readable) => void, + ) => { + queueMicrotask(() => callback(Object.assign(Readable.from([]), { statusCode: 200 }))); + return new Writable({ + write: (_chunk, _encoding, done) => setImmediate(() => done(new Error('connection reset'))), + }); + }) as unknown as typeof https.request); + await expect(upload('https://storage.test/put')).rejects.toMatchObject({ + details: { reason: 'revyl_upload_unreachable' }, + }); +}); diff --git a/packages/provider-revyl/src/artifact-upload.ts b/packages/provider-revyl/src/artifact-upload.ts index 9d69dde22e4..2b91efb6e9c 100644 --- a/packages/provider-revyl/src/artifact-upload.ts +++ b/packages/provider-revyl/src/artifact-upload.ts @@ -7,9 +7,9 @@ import { approveDownloadSourceUrl } from '@agent-device/provision-kit/install-so const REVYL_UPLOAD_REASONS = { // The storage URL Revyl returned is not an HTTPS URL on a public address. destinationRefused: { reason: 'revyl_upload_destination_refused' }, - // Revyl storage answered the upload with a non-2xx status. + // Revyl storage answered the upload with a non-2xx status, including a redirect, which is never followed. rejected: { reason: 'revyl_upload_rejected' }, - // Revyl storage never answered the upload, or answered with a redirect. + // Revyl storage never answered the upload, or the build stream failed before the upload finished. unreachable: { reason: 'revyl_upload_unreachable' }, } as const satisfies ReasonTable<'revyl provider'>; @@ -53,10 +53,25 @@ export async function uploadRevylArtifact( }, (response) => { response.resume(); - resolve(response.statusCode ?? 0); + response.on('error', reject); + answered = response.statusCode ?? 0; + settle(); }, ); - pipeline(fs.createReadStream(file.filePath), request, (error) => error && reject(error)); + let answered: number | undefined; + let streamed = false; + // The upload succeeds only after both the answer and the full body stream are in. + const settle = () => { + if (answered !== undefined && streamed) resolve(answered); + }; + pipeline(fs.createReadStream(file.filePath), request, (error) => { + if (error) { + reject(error); + return; + } + streamed = true; + settle(); + }); }); } catch (error) { signal?.throwIfAborted(); diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 05adf9bb2b9..eaccf95b239 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -1158,7 +1158,7 @@ These reasons can come from more than one command. | --- | --- | | `revyl_upload_destination_refused` | The storage URL Revyl returned is not an HTTPS URL on a public address. | | `revyl_upload_rejected` | Revyl storage answered the upload with a non-2xx status. | -| `revyl_upload_unreachable` | Revyl storage never answered the upload, or answered with a redirect. | +| `revyl_upload_unreachable` | Revyl storage never answered the upload, or the build stream failed before the upload finished. | | `invalid_provider_app` | Revyl installs the app from a URL, so `--provider-app` cannot name a local file. | | `unsupported_platform` | Revyl rents an iOS simulator or an Android emulator, and the request names neither. | | `unsupported_app_artifact` | Revyl installs an iOS simulator build or an Android .apk, and the build is neither. | From 7146f3857b4baed5b0336f2556b62d788394aeff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 11:02:43 +0100 Subject: [PATCH 4/7] docs: regenerate error reasons --- website/docs/docs/error-reasons.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index eaccf95b239..b620ae90ee4 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -1157,7 +1157,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `revyl_upload_destination_refused` | The storage URL Revyl returned is not an HTTPS URL on a public address. | -| `revyl_upload_rejected` | Revyl storage answered the upload with a non-2xx status. | +| `revyl_upload_rejected` | Revyl storage answered the upload with a non-2xx status, including a redirect, which is never followed. | | `revyl_upload_unreachable` | Revyl storage never answered the upload, or the build stream failed before the upload finished. | | `invalid_provider_app` | Revyl installs the app from a URL, so `--provider-app` cannot name a local file. | | `unsupported_platform` | Revyl rents an iOS simulator or an Android emulator, and the request names neither. | From f4001e01037d3abeac2166d524c7cba4d7c6d336 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 11:29:33 +0100 Subject: [PATCH 5/7] fix(provider-revyl): report a storage refusal that precedes a connection reset --- .../src/artifact-upload.test.ts | 20 +++++++++++++++++++ .../provider-revyl/src/artifact-upload.ts | 9 +++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/provider-revyl/src/artifact-upload.test.ts b/packages/provider-revyl/src/artifact-upload.test.ts index 37ac3c018ed..ff5596972c5 100644 --- a/packages/provider-revyl/src/artifact-upload.test.ts +++ b/packages/provider-revyl/src/artifact-upload.test.ts @@ -114,3 +114,23 @@ test('an early 200 does not hide a build stream that fails after the answer', as details: { reason: 'revyl_upload_unreachable' }, }); }); + +test('a 403 answer survives a connection reset before the body finishes', async () => { + vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ + address: '203.0.113.1', + family: 4, + }); + vi.spyOn(https, 'request').mockImplementation((( + _url: URL, + _options: https.RequestOptions, + callback: (response: Readable) => void, + ) => { + queueMicrotask(() => callback(Object.assign(Readable.from([]), { statusCode: 403 }))); + return new Writable({ + write: (_chunk, _encoding, done) => setImmediate(() => done(new Error('connection reset'))), + }); + }) as unknown as typeof https.request); + await expect(upload('https://storage.test/put')).rejects.toMatchObject({ + details: { reason: 'revyl_upload_rejected', status: 403 }, + }); +}); diff --git a/packages/provider-revyl/src/artifact-upload.ts b/packages/provider-revyl/src/artifact-upload.ts index 2b91efb6e9c..19f3d9c82bd 100644 --- a/packages/provider-revyl/src/artifact-upload.ts +++ b/packages/provider-revyl/src/artifact-upload.ts @@ -53,7 +53,7 @@ export async function uploadRevylArtifact( }, (response) => { response.resume(); - response.on('error', reject); + response.on('error', fail); answered = response.statusCode ?? 0; settle(); }, @@ -64,9 +64,14 @@ export async function uploadRevylArtifact( const settle = () => { if (answered !== undefined && streamed) resolve(answered); }; + // A refusal that arrives before the connection drops still names its status; an incomplete 2xx body is no success. + const fail = (error: Error) => { + if (answered !== undefined && (answered < 200 || answered >= 300)) resolve(answered); + else reject(error); + }; pipeline(fs.createReadStream(file.filePath), request, (error) => { if (error) { - reject(error); + fail(error); return; } streamed = true; From e7d1e08236e49d1c14ba79d4be6a665037dea149 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 12:22:58 +0100 Subject: [PATCH 6/7] fix(revyl): dial a fresh socket per upload and send exactly the stat'ed build bytes --- .../src/artifact-upload.test.ts | 63 +++++++++++++++++++ .../provider-revyl/src/artifact-upload.ts | 25 +++++++- 2 files changed, 85 insertions(+), 3 deletions(-) diff --git a/packages/provider-revyl/src/artifact-upload.test.ts b/packages/provider-revyl/src/artifact-upload.test.ts index ff5596972c5..4235b43b6af 100644 --- a/packages/provider-revyl/src/artifact-upload.test.ts +++ b/packages/provider-revyl/src/artifact-upload.test.ts @@ -134,3 +134,66 @@ test('a 403 answer survives a connection reset before the body finishes', async details: { reason: 'revyl_upload_rejected', status: 403 }, }); }); + +test('a request error after the body is sent fails the upload', async () => { + vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ + address: '203.0.113.1', + family: 4, + }); + vi.spyOn(https, 'request').mockImplementation((() => { + const request: Writable = new Writable({ + write: (_chunk, _encoding, done) => done(), + final: (done) => { + done(); + setTimeout(() => request.emit('error', new Error('socket hang up')), 20); + }, + }); + return request; + }) as unknown as typeof https.request); + await expect(upload('https://storage.test/put')).rejects.toMatchObject({ + details: { reason: 'revyl_upload_unreachable' }, + }); +}); + +/** Records the body bytes and answers 200 once the body ends. */ +function recordBody() { + const sent: Buffer[] = []; + const request = vi.spyOn(https, 'request').mockImplementation( + ((_url: URL, _options: https.RequestOptions, callback: (response: Readable) => void) => + new Writable({ + write: (chunk: Buffer, _encoding, done) => { + sent.push(chunk); + done(); + }, + final: (done) => { + callback(Object.assign(Readable.from([]), { statusCode: 200 })); + done(); + }, + })) as unknown as typeof https.request, + ); + return { request, body: () => Buffer.concat(sent).toString() }; +} + +test('a build that grew after its stat sends only the stat-ed bytes', async () => { + vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ + address: '203.0.113.1', + family: 4, + }); + const { body } = recordBody(); + const { filePath } = await buildFile(); + await uploadRevylArtifact('https://storage.test/put', { filePath, size: 5 }, 'x'); + assert.equal(body(), 'apk-b'); +}); + +test.each([20, 0])('a build shorter than its stat-ed %s bytes is unreachable', async (size) => { + vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ + address: '203.0.113.1', + family: 4, + }); + const { request } = recordBody(); + const { filePath } = await buildFile(); + await expect( + uploadRevylArtifact('https://storage.test/put', { filePath, size }, 'x'), + ).rejects.toMatchObject({ details: { reason: 'revyl_upload_unreachable' } }); + if (size === 0) assert.equal(request.mock.calls.length, 0); +}); diff --git a/packages/provider-revyl/src/artifact-upload.ts b/packages/provider-revyl/src/artifact-upload.ts index 19f3d9c82bd..0af4660d770 100644 --- a/packages/provider-revyl/src/artifact-upload.ts +++ b/packages/provider-revyl/src/artifact-upload.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import https from 'node:https'; -import { pipeline } from 'node:stream'; +import { pipeline, Transform } from 'node:stream'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { approveDownloadSourceUrl } from '@agent-device/provision-kit/install-source-network'; @@ -9,7 +9,7 @@ const REVYL_UPLOAD_REASONS = { destinationRefused: { reason: 'revyl_upload_destination_refused' }, // Revyl storage answered the upload with a non-2xx status, including a redirect, which is never followed. rejected: { reason: 'revyl_upload_rejected' }, - // Revyl storage never answered the upload, or the build stream failed before the upload finished. + // Revyl storage never answered the upload, or the build stream failed or did not hold exactly its stat'ed size. unreachable: { reason: 'revyl_upload_unreachable' }, } as const satisfies ReasonTable<'revyl provider'>; @@ -40,11 +40,14 @@ export async function uploadRevylArtifact( const { address, family } = approved; let status: number; try { + if (file.size <= 0) throw new Error('The build file is empty.'); status = await new Promise((resolve, reject) => { const request = https.request( url, { method: 'PUT', + // A fresh socket per upload: a pooled or env-proxy agent would skip the pinned lookup. + agent: false, headers: { 'Content-Type': contentType, 'Content-Length': String(file.size) }, // The socket dials the approved address; the URL host still names SNI, the certificate and Host. lookup: (_host, options, callback) => @@ -69,7 +72,23 @@ export async function uploadRevylArtifact( if (answered !== undefined && (answered < 200 || answered >= 300)) resolve(answered); else reject(error); }; - pipeline(fs.createReadStream(file.filePath), request, (error) => { + request.on('error', fail); + // The body is exactly the stat'ed size: bytes past it are never read, and an early end fails the upload. + let sent = 0; + const exactSize = new Transform({ + transform: (chunk: Buffer, _encoding, done) => { + sent += chunk.length; + done(null, chunk); + }, + flush: (done) => + done( + sent === file.size + ? null + : new Error(`The build ended after ${sent} of ${file.size} bytes.`), + ), + }); + const source = fs.createReadStream(file.filePath, { start: 0, end: file.size - 1 }); + pipeline(source, exactSize, request, (error) => { if (error) { fail(error); return; From 4835963e3107529de4cca408cde2ff89e4b76fc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 12:30:07 +0100 Subject: [PATCH 7/7] docs: regenerate error reasons --- website/docs/docs/error-reasons.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index b620ae90ee4..0ea0d06e27c 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -1158,7 +1158,7 @@ These reasons can come from more than one command. | --- | --- | | `revyl_upload_destination_refused` | The storage URL Revyl returned is not an HTTPS URL on a public address. | | `revyl_upload_rejected` | Revyl storage answered the upload with a non-2xx status, including a redirect, which is never followed. | -| `revyl_upload_unreachable` | Revyl storage never answered the upload, or the build stream failed before the upload finished. | +| `revyl_upload_unreachable` | Revyl storage never answered the upload, or the build stream failed or did not hold exactly its stat'ed size. | | `invalid_provider_app` | Revyl installs the app from a URL, so `--provider-app` cannot name a local file. | | `unsupported_platform` | Revyl rents an iOS simulator or an Android emulator, and the request names neither. | | `unsupported_app_artifact` | Revyl installs an iOS simulator build or an Android .apk, and the build is neither. |