diff --git a/src/commands/artifacts.ts b/src/commands/artifacts.ts index c87448b..b521c96 100644 --- a/src/commands/artifacts.ts +++ b/src/commands/artifacts.ts @@ -4,6 +4,7 @@ import { apiFlags } from '../config/flags/api.flags.js'; import { jsonFlag } from '../config/flags/output.flags.js'; import { type DownloadResult, + downloadsSucceeded, ReportDownloadService, reportFormatDeprecation, } from '../services/report-download.service.js'; @@ -140,12 +141,15 @@ export const artifactsCommand = defineCommand({ if (result) downloads.push(result); } + // Downloading is this command's only job, so a failed or incomplete + // download exits 1, with or without --json. Its warning is already + // printed, and fail() prints nothing more (no second JSON object). + const ok = downloadsSucceeded(downloads); if (json) { - const ok = downloads.some((d) => d.ok); logger.json({ status: ok ? 'SUCCESS' : 'FAILED', uploadId, downloads }); - // Same exit code a thrown error would give, without a second JSON object. - if (!ok) logger.fail('Every download failed', 1); } + + if (!ok) logger.fail('Download failed', 1); }, }); diff --git a/src/gateways/api-gateway.ts b/src/gateways/api-gateway.ts index 69629f8..7d3dc31 100644 --- a/src/gateways/api-gateway.ts +++ b/src/gateways/api-gateway.ts @@ -1,4 +1,5 @@ import { createWriteStream, mkdirSync } from 'node:fs'; +import { rm } from 'node:fs/promises'; import { homedir } from 'node:os'; import * as path from 'node:path'; import { Readable } from 'node:stream'; @@ -19,6 +20,7 @@ import type { } from '../types/domain/live.types.js'; import type { TeamSettings } from '../types/domain/team-settings.types.js'; import { components, paths } from '../types/generated/schema.types.js'; +import { assertCompleteZip, IncompleteZipError } from '../utils/zip-integrity.js'; /** Expand a leading `~` to the home directory, as the download paths allow. */ function expandHome(p: string): string { @@ -402,9 +404,52 @@ export const ApiGateway = { bytes_received: bytesReceived, }); } + + // A bundle that fails after its 200 headers still ends cleanly, so the + // stream above succeeds and leaves a ZIP with no central directory. Check + // before calling it done; the inline path then overwrites the file. + try { + await assertCompleteZip(expandHome(destinationPath)); + } catch (error) { + return failure('bundle_truncated', { + ...errorDetail(error), + bytes_received: bytesReceived, + }); + } + return true; }, + /** + * Fail an inline ZIP download that ended before its central directory: the + * API streams the ZIP as it builds it, so a failure after the headers can + * still close the response cleanly. Deletes the partial file, so nothing + * downstream (a CI artifact upload, say) picks up a corrupt ZIP. + */ + async assertInlineZipComplete( + destinationPath: string, + operation: string, + route: string, + uploadId: string, + ) { + const file = expandHome(destinationPath); + try { + await assertCompleteZip(file); + } catch (error) { + if (!(error instanceof IncompleteZipError)) throw error; + await rm(file, { force: true }).catch(() => {}); + telemetry.recordDownloadIncomplete({ + bytes: error.bytes, + route, + upload_id: uploadId, + }); + throw new Error( + `${operation}: the download ended early and ${error.message}. Please retry.`, + { cause: error }, + ); + } + }, + /** * Look for an already-uploaded binary to skip re-uploading. * @@ -492,6 +537,12 @@ export const ApiGateway = { } await this.streamResponseToFile(res, artifactsPath, 'Failed to download artifacts'); + await this.assertInlineZipComplete( + artifactsPath, + 'Failed to download artifacts', + 'download', + uploadId, + ); } catch (error) { if (error instanceof TypeError && error.message === 'fetch failed') { throw this.enhanceFetchError(error, `${baseUrl}/results/${uploadId}/download`); @@ -1089,6 +1140,15 @@ export const ApiGateway = { } await this.streamResponseToFile(res, finalReportPath, errorPrefix); + // Only the HTML report is a ZIP; junit is XML and allure is one HTML file. + if (reportType === 'html') { + await this.assertInlineZipComplete( + finalReportPath, + errorPrefix, + 'html-report', + uploadId, + ); + } } catch (error) { if (error instanceof TypeError && error.message === 'fetch failed') { throw this.enhanceFetchError(error, url); diff --git a/src/services/report-download.service.ts b/src/services/report-download.service.ts index 6587e22..1011e0a 100644 --- a/src/services/report-download.service.ts +++ b/src/services/report-download.service.ts @@ -57,6 +57,14 @@ export interface DownloadResult { type: 'allure' | 'artifacts' | 'html' | 'junit'; } +/** + * Whether every requested download succeeded. `dcd artifacts` exits 1 when + * not; `dcd cloud` only warns, so a download never changes a test-run exit. + */ +export function downloadsSucceeded(downloads: DownloadResult[]): boolean { + return downloads.length > 0 && downloads.every((d) => d.ok); +} + /** * Service for downloading test artifacts and reports */ diff --git a/src/services/telemetry.service.ts b/src/services/telemetry.service.ts index 2726533..7b6a234 100644 --- a/src/services/telemetry.service.ts +++ b/src/services/telemetry.service.ts @@ -49,6 +49,8 @@ export type BundleFallbackReason = | 'bundle_http_error' | 'bundle_request_failed' | 'bundle_stream_failed' + /** The stream ended cleanly but the ZIP has no complete central directory. */ + | 'bundle_truncated' | 'manifest_http_error' | 'manifest_incomplete' | 'manifest_invalid_json' @@ -195,6 +197,19 @@ class Telemetry { ); } + /** + * Record an inline ZIP download that ended before its central directory. + * The user sees the failure; this keeps a count of how often it happens. + */ + recordDownloadIncomplete(detail: { + bytes: number; + /** The inline route, e.g. `download` or `html-report`. */ + route: string; + upload_id?: string; + }) { + this.enqueue('warn', 'cli.download', 'download incomplete', { ...detail }); + } + recordCommandSuccess() { this.enqueue('info', 'cli.lifecycle', 'command completed', { duration_ms: Date.now() - this.startedAt, diff --git a/src/utils/zip-integrity.ts b/src/utils/zip-integrity.ts new file mode 100644 index 0000000..044c28d --- /dev/null +++ b/src/utils/zip-integrity.ts @@ -0,0 +1,50 @@ +import { stat } from 'node:fs/promises'; +import StreamZip from 'node-stream-zip'; + +/** + * A downloaded ZIP that ends before its central directory, so `unzip` and most + * tools reject it. A server streams a ZIP's entries first and its central + * directory last, so a response that stops early, but still closes cleanly, + * leaves exactly this behind. + */ +export class IncompleteZipError extends Error { + constructor( + readonly bytes: number, + readonly detail?: string, + ) { + super(`the ZIP is incomplete (${bytes} bytes, no valid central directory)`); + this.name = 'IncompleteZipError'; + } +} + +/** + * Check that the file at `filePath` is a complete ZIP: its end-of-central- + * directory record (or the ZIP64 one) is there and every central directory + * header after it is intact. Only the central directory is read, never the + * entries' data, so this costs about its size even for a multi-GB archive. + * + * Throws {@link IncompleteZipError} when the file is not a complete ZIP, + * including when it is empty or missing. + */ +export async function assertCompleteZip(filePath: string): Promise { + const bytes = await stat(filePath).then( + (s) => s.size, + () => 0, + ); + const zip = new StreamZip.async({ + file: filePath, + skipEntryNameValidation: true, + storeEntries: false, + }); + try { + // Resolves only once every central directory header has been read. + await zip.entriesCount; + } catch (error) { + throw new IncompleteZipError( + bytes, + error instanceof Error ? error.message : String(error), + ); + } finally { + await zip.close().catch(() => {}); + } +} diff --git a/test/helpers/zip-fixture.ts b/test/helpers/zip-fixture.ts new file mode 100644 index 0000000..3a78a00 --- /dev/null +++ b/test/helpers/zip-fixture.ts @@ -0,0 +1,19 @@ +import * as yazl from 'yazl'; + +/** + * A stored (uncompressed) ZIP holding `count` entries of `size` bytes, each + * filled with `fill + i` so two fixtures with different fills differ. + */ +export async function zipBuffer(count = 20, size = 4096, fill = 0): Promise { + const zip = new yazl.ZipFile(); + for (let i = 0; i < count; i++) { + zip.addBuffer(Buffer.alloc(size, (fill + i) % 256), `${i}/logs/file-${i}.log`, { + compress: false, + }); + } + + zip.end(); + const chunks: Buffer[] = []; + for await (const chunk of zip.outputStream) chunks.push(chunk as Buffer); + return Buffer.concat(chunks); +} diff --git a/test/unit/report-download.service.test.ts b/test/unit/report-download.service.test.ts index eba68ee..99f4747 100644 --- a/test/unit/report-download.service.test.ts +++ b/test/unit/report-download.service.test.ts @@ -5,6 +5,7 @@ import * as path from 'node:path'; import { ApiGateway } from '../../src/gateways/api-gateway.js'; import { + downloadsSucceeded, ReportDownloadService, reportFormatDeprecation, } from '../../src/services/report-download.service.js'; @@ -13,6 +14,7 @@ import { telemetry, } from '../../src/services/telemetry.service.js'; import type { AuthContext } from '../../src/types/domain/auth.types.js'; +import { zipBuffer } from '../helpers/zip-fixture.js'; const TEST_AUTH: AuthContext = { mode: 'apiKey', @@ -31,6 +33,20 @@ type CapturedRequest = { }; let captured: CapturedRequest | null = null; + +// Artifact and HTML report downloads are checked for a complete ZIP, so they +// are served real ones. Two, with different contents, so a test can tell which +// path wrote the file. +let INLINE_ZIP: Buffer; +let BUNDLE_ZIP: Buffer; + +before(async () => { + INLINE_ZIP = await zipBuffer(20, 4096, 1); + BUNDLE_ZIP = await zipBuffer(20, 4096, 2); +}); + +/** `zip` cut off before its central directory, as a dropped stream leaves it. */ +const truncated = (zip: Buffer) => zip.subarray(0, Math.floor(zip.length / 2)); // eslint-disable-next-line @typescript-eslint/no-explicit-any const originalFetch = (global as any).fetch; @@ -42,8 +58,10 @@ const originalFetch = (global as any).fetch; * @param responseBody Response body string * @returns void */ -function mockFetch(status: number, responseBody = 'fake-zip-content') { +function mockFetch(status: number, responseBody?: Buffer | string) { const encoder = new TextEncoder(); + // Default: a complete ZIP, the body a successful artifacts download has. + const body = responseBody ?? INLINE_ZIP; // eslint-disable-next-line @typescript-eslint/no-explicit-any (global as any).fetch = async ( input: URL | string, @@ -60,7 +78,9 @@ function mockFetch(status: number, responseBody = 'fake-zip-content') { const stream = new ReadableStream({ start(controller) { - controller.enqueue(encoder.encode(responseBody)); + controller.enqueue( + typeof body === 'string' ? encoder.encode(body) : new Uint8Array(body), + ); controller.close(); }, }); @@ -150,7 +170,7 @@ describe('ReportDownloadService', () => { it('writes the response body to the specified file path', async () => { const outPath = path.join(tempDir, 'written.zip'); - mockFetch(200, 'zip-file-contents'); + mockFetch(200, INLINE_ZIP); await service.downloadArtifacts({ ...BASE, @@ -159,12 +179,12 @@ describe('ReportDownloadService', () => { }); expect(fs.existsSync(outPath)).to.be.true; - expect(fs.readFileSync(outPath, 'utf8')).to.equal('zip-file-contents'); + expect(fs.readFileSync(outPath).equals(INLINE_ZIP)).to.be.true; }); it('creates intermediate directories if they do not exist', async () => { const outPath = path.join(tempDir, 'nested', 'dir', 'artifacts.zip'); - mockFetch(200, 'content'); + mockFetch(200); await service.downloadArtifacts({ ...BASE, @@ -195,7 +215,7 @@ describe('ReportDownloadService', () => { it('calls logger with success message when download succeeds', async () => { const outPath = path.join(tempDir, 'logged.zip'); - mockFetch(200, 'data'); + mockFetch(200); const logs: string[] = []; @@ -212,7 +232,7 @@ describe('ReportDownloadService', () => { // `dcd artifacts --json` reports these, since failures only warn. it('returns ok: true with the path when the download succeeds', async () => { const outPath = path.join(tempDir, 'result-ok.zip'); - mockFetch(200, 'data'); + mockFetch(200); const result = await service.downloadArtifacts({ ...BASE, @@ -237,6 +257,82 @@ describe('ReportDownloadService', () => { expect(result.type).to.equal('artifacts'); expect(result.error).to.be.a('string').and.not.be.empty; }); + + describe('an inline download that ends early', () => { + let incomplete: Array<{ bytes: number; route: string; upload_id?: string }>; + const realRecordDownloadIncomplete = telemetry.recordDownloadIncomplete; + + beforeEach(() => { + incomplete = []; + telemetry.recordDownloadIncomplete = (detail) => { + incomplete.push(detail); + }; + }); + + afterEach(() => { + telemetry.recordDownloadIncomplete = realRecordDownloadIncomplete; + }); + + it('fails, deletes the partial ZIP and records it', async () => { + const outPath = path.join(tempDir, 'cut-inline.zip'); + const cut = truncated(INLINE_ZIP); + mockFetch(200, cut); + const warnings: string[] = []; + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: outPath, + downloadType: 'ALL', + warnLogger: (msg) => warnings.push(msg), + }); + + expect(result.ok).to.equal(false); + expect(result.error).to.include('the download ended early'); + expect(result.error).to.include(`${cut.length} bytes`); + expect(warnings.join(' ')).to.match(/failed to download artifacts/i); + expect(fs.existsSync(outPath)).to.be.false; + expect(incomplete).to.deep.equal([ + { bytes: cut.length, route: 'download', upload_id: 'upload-abc-123' }, + ]); + }); + + it('fails an HTML report ZIP that ends early', async () => { + const outPath = path.join(tempDir, 'cut-report.zip'); + mockFetch(200, truncated(INLINE_ZIP)); + + const result = await service.downloadReports({ + ...BASE, + htmlPath: outPath, + reportType: 'html', + }); + + expect(result?.ok).to.equal(false); + expect(fs.existsSync(outPath)).to.be.false; + expect(incomplete[0]).to.include({ route: 'html-report' }); + }); + + it('never checks a JUnit or Allure report, which are not ZIPs', async () => { + for (const [reportType, file, body] of [ + ['junit', 'not-zip.xml', ''], + ['allure', 'not-zip.html', ''], + ] as const) { + const outPath = path.join(tempDir, file); + mockFetch(200, body); + + const result = await service.downloadReports({ + ...BASE, + allurePath: outPath, + junitPath: outPath, + reportType, + }); + + expect(result?.ok, reportType).to.equal(true); + expect(fs.readFileSync(outPath, 'utf8')).to.equal(body); + } + + expect(incomplete).to.deep.equal([]); + }); + }); }); // ------------------------------------------------------------------------- @@ -285,7 +381,7 @@ describe('ReportDownloadService', () => { it('uses GET /results/{uploadId}/html-report for html', async () => { const outPath = path.join(tempDir, 'html.html'); - mockFetch(200, ''); + mockFetch(200, INLINE_ZIP); await service.downloadReports({ ...BASE, @@ -367,7 +463,7 @@ describe('ReportDownloadService', () => { opts: { manifestBody?: Record; manifestStatus?: number; - zipBody?: string; + zipBody?: Buffer | string; zipBreaksAfter?: string; zipStatus?: number; } = {}, @@ -381,15 +477,17 @@ describe('ReportDownloadService', () => { sig: 'SIG', }, manifestStatus = 200, - zipBody = 'bundle-zip', + zipBody = BUNDLE_ZIP, zipBreaksAfter, zipStatus = 200, } = opts; const encoder = new TextEncoder(); - const stream = (s: string) => + const stream = (s: Buffer | string) => new ReadableStream({ start(controller) { - controller.enqueue(encoder.encode(s)); + controller.enqueue( + typeof s === 'string' ? encoder.encode(s) : new Uint8Array(s), + ); controller.close(); }, }); @@ -435,7 +533,7 @@ describe('ReportDownloadService', () => { } return new Response(stream(zipBody), { status: zipStatus }); } - return new Response(stream('inline-zip'), { status: 200 }); + return new Response(stream(INLINE_ZIP), { status: 200 }); }; globalThis.fetch = impl as typeof fetch; } @@ -474,7 +572,7 @@ describe('ReportDownloadService', () => { url: 'https://cdn.example.com/bundle', }); expect(calls.some((c) => c.url.endsWith('/download'))).to.be.false; - expect(fs.readFileSync(outPath, 'utf8')).to.equal('bundle-zip'); + expect(fs.readFileSync(outPath).equals(BUNDLE_ZIP)).to.be.true; }); it('does not send the auth header to the (pre-signed) bundle URL', async () => { @@ -509,7 +607,7 @@ describe('ReportDownloadService', () => { expect( calls.some((c) => c.method === 'POST' && c.url.endsWith('/download')), ).to.be.true; - expect(fs.readFileSync(outPath, 'utf8')).to.equal('inline-zip'); + expect(fs.readFileSync(outPath).equals(INLINE_ZIP)).to.be.true; }); describe('records why it fell back', () => { @@ -559,7 +657,7 @@ describe('ReportDownloadService', () => { reason: 'bundle_http_error', status: 502, }); - expect(fs.readFileSync(outPath, 'utf8')).to.equal('inline-zip'); + expect(fs.readFileSync(outPath).equals(INLINE_ZIP)).to.be.true; }); it('records a stream that breaks partway, with the error and bytes received', async () => { @@ -579,7 +677,34 @@ describe('ReportDownloadService', () => { reason: 'bundle_stream_failed', }); // The inline download still replaced the partial file. - expect(fs.readFileSync(outPath, 'utf8')).to.equal('inline-zip'); + expect(fs.readFileSync(outPath).equals(INLINE_ZIP)).to.be.true; + }); + + it('falls back when a bundle ends cleanly but its ZIP is incomplete', async () => { + // What a bundle that fails after its 200 headers delivers: a clean + // end of stream, and a ZIP with no central directory. + const cut = truncated(BUNDLE_ZIP); + mockBundleFetch({ zipBody: cut }); + const outPath = path.join(tempDir, 'bundle-truncated.zip'); + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: outPath, + downloadType: 'ALL', + }); + + expect(result.ok).to.equal(true); + expect(fallbacks).to.have.length(1); + expect(fallbacks[0]).to.include({ + bytes_received: cut.length, + error_name: 'IncompleteZipError', + reason: 'bundle_truncated', + route: 'artifacts-bundle', + }); + expect( + calls.some((c) => c.method === 'POST' && c.url.endsWith('/download')), + ).to.be.true; + expect(fs.readFileSync(outPath).equals(INLINE_ZIP)).to.be.true; }); }); @@ -687,3 +812,18 @@ describe('reportFormatDeprecation', () => { } }); }); + +describe('downloadsSucceeded', () => { + const ok = { ok: true, path: 'a.zip', type: 'artifacts' } as const; + const failed = { error: 'boom', ok: false, path: 'a.zip', type: 'artifacts' } as const; + + it('is true only when every download succeeded', () => { + expect(downloadsSucceeded([ok])).to.equal(true); + expect(downloadsSucceeded([failed])).to.equal(false); + expect(downloadsSucceeded([ok, failed])).to.equal(false); + }); + + it('is false when nothing was downloaded', () => { + expect(downloadsSucceeded([])).to.equal(false); + }); +}); diff --git a/test/unit/zip-integrity.test.ts b/test/unit/zip-integrity.test.ts new file mode 100644 index 0000000..5c92fa7 --- /dev/null +++ b/test/unit/zip-integrity.test.ts @@ -0,0 +1,81 @@ +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +import { + assertCompleteZip, + IncompleteZipError, +} from '../../src/utils/zip-integrity.js'; +import { zipBuffer } from '../helpers/zip-fixture.js'; + +describe('assertCompleteZip', () => { + let dir: string; + let complete: Buffer; + + before(async () => { + complete = await zipBuffer(); + }); + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-zip-integrity-')); + }); + + afterEach(() => { + fs.rmSync(dir, { force: true, recursive: true }); + }); + + const write = (name: string, data: Buffer) => { + const file = path.join(dir, name); + fs.writeFileSync(file, data); + return file; + }; + + const rejection = async (file: string) => { + try { + await assertCompleteZip(file); + } catch (error) { + return error; + } + + throw new Error(`expected ${file} to be rejected`); + }; + + it('accepts a complete ZIP', async () => { + await assertCompleteZip(write('ok.zip', complete)); + }); + + it('accepts an empty ZIP (no entries, just the end record)', async () => { + await assertCompleteZip(write('none.zip', await zipBuffer(0))); + }); + + for (const [name, cut] of [ + ['cut off among the entries', (b: Buffer) => b.subarray(0, b.length / 2)], + ['cut off inside the central directory', (b: Buffer) => b.subarray(0, b.length - 40)], + ['missing only its last byte', (b: Buffer) => b.subarray(0, b.length - 1)], + ] as const) { + it(`rejects a ZIP ${name}`, async () => { + const truncated = cut(complete); + const error = await rejection(write('cut.zip', truncated)); + expect(error).to.be.instanceOf(IncompleteZipError); + expect((error as IncompleteZipError).bytes).to.equal(truncated.length); + expect((error as Error).message).to.include(`${truncated.length} bytes`); + }); + } + + it('rejects an empty file', async () => { + const error = await rejection(write('empty.zip', Buffer.alloc(0))); + expect(error).to.be.instanceOf(IncompleteZipError); + expect((error as IncompleteZipError).bytes).to.equal(0); + }); + + it('rejects a file that is not a ZIP at all', async () => { + const error = await rejection(write('page.zip', Buffer.from('Bad gateway'))); + expect(error).to.be.instanceOf(IncompleteZipError); + }); + + it('rejects a missing file', async () => { + const error = await rejection(path.join(dir, 'missing.zip')); + expect(error).to.be.instanceOf(IncompleteZipError); + }); +});