Skip to content
Open
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
199 changes: 199 additions & 0 deletions packages/provider-revyl/src/artifact-upload.test.ts
Original file line number Diff line number Diff line change
@@ -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');
Comment thread
thymikee marked this conversation as resolved.
Resolved
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);
});
116 changes: 116 additions & 0 deletions packages/provider-revyl/src/artifact-upload.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
const url = URL.parse(uploadUrl);
let approved: Awaited<ReturnType<typeof approveDownloadSourceUrl>>;
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.');

Check warning on line 43 in packages/provider-revyl/src/artifact-upload.ts

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

minor: An empty build is reported as storage refusing an upload that was never sent

With a zero-byte build, the user sees 'Revyl storage did not accept the app upload.' although no request was made. The empty-build guard throws inside the `try` whose `catch` maps everything to `revyl_upload_unreachable`. Check the size before the `try` so the message matches what happened.
Comment thread
thymikee marked this conversation as resolved.
Resolved
status = await new Promise<number>((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();
});
});
Comment thread
thymikee marked this conversation as resolved.
Resolved
} catch (error) {
signal?.throwIfAborted();
throw new AppError(
'COMMAND_FAILED',
'Revyl storage did not accept the app upload.',
{ reason: REVYL_UPLOAD_REASONS.unreachable.reason },
error,
);
}
Comment thread
thymikee marked this conversation as resolved.
Resolved
Comment thread
thymikee marked this conversation as resolved.
Resolved
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 },
);
}
}
16 changes: 9 additions & 7 deletions packages/provider-revyl/src/deployment.test.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -11,26 +11,29 @@ 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';

/** A backend whose session accepts one upload and reports the install with `result`. */
async function installingBackend(result: Record<string, unknown>, 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': {
Expand All @@ -41,7 +44,7 @@ async function installingBackend(result: Record<string, unknown>, status = 'comp
},
},
});
backendUrl = fixture.backendUrl;
routeStorageTo(fixture.backendUrl);
openBackends.push(fixture);
const runtime = fixture.createRuntime();
return { fixture, runtime };
Expand Down Expand Up @@ -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': {
Expand All @@ -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-');
Expand Down
Loading
Loading