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 0000000000..4235b43b6a --- /dev/null +++ b/packages/provider-revyl/src/artifact-upload.test.ts @@ -0,0 +1,199 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import https from 'node:https'; +import path from 'node:path'; +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 }; +} + +/** 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', + '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 request = stubHttps(200); + const file = { filePath: '/nonexistent/build.apk', size: 9 }; + await expect(uploadRevylArtifact(url, file, 'x')).rejects.toMatchObject({ + details: { reason: 'revyl_upload_destination_refused' }, + }); + assert.equal(request.mock.calls.length, 0); +}); + +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('an unanswered upload is unreachable', async () => { + vi.spyOn(storageAdmission, 'approveDownloadSourceUrl').mockResolvedValue({ + address: '203.0.113.1', + family: 4, + }); + 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.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 }, + }); +}); + +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' }, + }); +}); + +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 }, + }); +}); + +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 new file mode 100644 index 0000000000..0af4660d77 --- /dev/null +++ b/packages/provider-revyl/src/artifact-upload.ts @@ -0,0 +1,116 @@ +import fs from 'node:fs'; +import https from 'node:https'; +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'; + +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, including a redirect, which is never followed. + rejected: { reason: 'revyl_upload_rejected' }, + // 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'>; + +/** + * 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( + 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.'); + approved = 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, + ); + } + 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) => + options.all ? callback(null, [{ address, family }]) : callback(null, address, family), + ...(signal === undefined ? {} : { signal }), + }, + (response) => { + response.resume(); + response.on('error', fail); + answered = response.statusCode ?? 0; + settle(); + }, + ); + 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); + }; + // 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); + }; + 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; + } + streamed = true; + settle(); + }); + }); + } 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 (status < 200 || status >= 300) { + throw new AppError( + 'COMMAND_FAILED', + `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 09bfd95f46..9ca100fedc 100644 --- a/packages/provider-revyl/src/deployment.test.ts +++ b/packages/provider-revyl/src/deployment.test.ts @@ -1,7 +1,7 @@ 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 { mkdtempForTest } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; import { @@ -11,14 +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(); await Promise.all(openBackends.splice(0).map((fixture) => fixture.close())); }); const UPLOAD_PATH = '/api/storage/put'; +const UPLOAD_URL = `https://storage.test${UPLOAD_PATH}`; + /** The host environment the packer runs `tar` with. */ const ENV = { PATH: '/usr/bin:/bin' }; const DOWNLOAD_URL = 'https://storage.test/session-build'; @@ -26,11 +30,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 +44,7 @@ async function installingBackend(result: Record, status = 'comp }, }, }); - backendUrl = fixture.backendUrl; + routeStorageTo(fixture.backendUrl); openBackends.push(fixture); const runtime = fixture.createRuntime(); return { fixture, runtime }; @@ -179,11 +182,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 +196,7 @@ test('an install Revyl reports completed without a result is installed, with no }, }, }); - backendUrl = fixture.backendUrl; + 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 1ce44efc1e..fb7ca6cfd4 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 dc193a820c..2692568412 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(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 0000000000..1e3c98b850 --- /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/error-reasons.md b/website/docs/docs/error-reasons.md index 7d9fa7d9cf..0ea0d06e27 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, including a redirect, which is never followed. | +| `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. | diff --git a/website/docs/docs/revyl.md b/website/docs/docs/revyl.md index b9251aaec9..60f30d0a59 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: @@ -160,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