Repository navigation
fix(revyl): bind uploads to admitted job destinations #5337
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
thymikee
wants to merge
7
commits into
0.22
Choose a base branch
from
t3/revyl-upload-admission
base: 0.22
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+364
−43
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e5d7c6b
fix(revyl): upload builds only to a public HTTPS destination
thymikee 28a4e3b
fix(revyl): connect the build upload to the approved address
thymikee 2bc1979
fix(revyl): settle an upload after the answer and the body stream, fi…
thymikee 7146f38
docs: regenerate error reasons
thymikee f4001e0
fix(provider-revyl): report a storage refusal that precedes a connect…
thymikee e7d1e08
fix(revyl): dial a fresh socket per upload and send exactly the stat'…
thymikee 4835963
docs: regenerate error reasons
thymikee File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'); | ||
| 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); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
|
||
|
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(); | ||
| }); | ||
| }); | ||
|
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, | ||
| ); | ||
| } | ||
|
thymikee marked this conversation as resolved.
Resolved
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 }, | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.