Skip to content

Commit 07264d4

Browse files
authored
Merge pull request #6382 from rtibbles/fix-html5-zip-oom
Fix out-of-memory crash when uploading large HTML5 zips
2 parents 7975859 + 582db4a commit 07264d4

4 files changed

Lines changed: 120 additions & 67 deletions

File tree

‎contentcuration/contentcuration/frontend/shared/utils/__tests__/zipFile.spec.js‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,23 +47,38 @@ const TEST_CASES = {
4747
},
4848
};
4949

50-
function getMD5(data) {
51-
return createHash('md5').update(Buffer.from(data)).digest('hex');
50+
function readBytes(blob) {
51+
return new Promise((resolve, reject) => {
52+
const reader = new FileReader();
53+
reader.onload = () => resolve(new Uint8Array(reader.result));
54+
reader.onerror = reject;
55+
reader.readAsArrayBuffer(blob);
56+
});
57+
}
58+
59+
async function getMD5(blob) {
60+
return createHash('md5')
61+
.update(await readBytes(blob))
62+
.digest('hex');
63+
}
64+
65+
function zipFiles(files, paths = Object.keys(files)) {
66+
return createPredictableZip(paths, async path => files[path]);
5267
}
5368

5469
describe('createPredictableZip', () => {
5570
for (const [name, testCase] of Object.entries(TEST_CASES)) {
5671
it(`creates expected zip for ${name} case`, async () => {
57-
const zipData = await createPredictableZip(testCase.files, testCase.options);
58-
expect(getMD5(zipData)).toBe(testCase.expectedMD5);
72+
const zipData = await zipFiles(testCase.files);
73+
expect(await getMD5(zipData)).toBe(testCase.expectedMD5);
5974
});
6075
}
6176

6277
it('creates consistent hashes regardless of input order', async () => {
63-
const reversed = { ...TEST_CASES.reversed.files };
64-
const zipData1 = await createPredictableZip(TEST_CASES.reversed.files);
65-
const zipData2 = await createPredictableZip(reversed);
66-
expect(getMD5(zipData1)).toBe(getMD5(zipData2));
78+
const files = TEST_CASES.reversed.files;
79+
const zipData1 = await zipFiles(files);
80+
const zipData2 = await zipFiles(files, Object.keys(files).reverse());
81+
expect(await getMD5(zipData1)).toBe(await getMD5(zipData2));
6782
});
6883
});
6984

‎contentcuration/contentcuration/frontend/shared/utils/zipFile.js‎

Lines changed: 18 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -156,31 +156,31 @@ function calculateCrc32(data) {
156156
}
157157

158158
/**
159-
* Creates a predictable ZIP file from the given files.
159+
* Creates a predictable ZIP file, reading and compressing one file at a time.
160160
*
161-
* @param {Object.<string, string|Uint8Array>} files - An object where the keys are file paths and
162-
* the values are file contents.
163-
* @returns {Promise<Buffer>} - A promise that resolves to a Buffer containing the ZIP file data.
161+
* @param {string[]} paths - Paths of the files to include in the zip.
162+
* @param {function(string): Promise<string|Uint8Array>} readFile - Returns the contents of a path.
163+
* @returns {Promise<Blob>} - A promise that resolves to a Blob containing the ZIP file data.
164164
*
165165
* @example
166166
* const files = {
167167
* 'file1.txt': 'Hello, world!',
168168
* 'file2.bin': new Uint8Array([0x00, 0x01, 0x02, 0x03]),
169169
* 'folder/nested.txt': 'Nested content',
170170
* };
171-
* createPredictableZip(files).then(zipBuffer => {
172-
* // Do something with the zipBuffer
171+
* createPredictableZip(Object.keys(files), async path => files[path]).then(zipBlob => {
172+
* // Do something with the zipBlob
173173
* });
174174
*/
175-
export async function createPredictableZip(files) {
176-
const sortedPaths = Object.keys(files).sort();
177-
const entries = [];
175+
export async function createPredictableZip(paths, readFile) {
176+
const sortedPaths = [...paths].sort();
177+
const parts = [];
178178
let offset = 0;
179179
const centralDir = [];
180180
let centralDirSize = 0;
181181

182182
for (const path of sortedPaths) {
183-
const content = files[path];
183+
const content = await readFile(path);
184184
// Handle binary data more carefully
185185
const rawData =
186186
typeof content === 'string'
@@ -207,38 +207,24 @@ export async function createPredictableZip(files) {
207207
checksum,
208208
);
209209

210-
const entry = {
211-
header,
212-
compressed: new Uint8Array(compressed),
213-
path: filenameCleaned,
214-
crc32: checksum,
215-
compressedSize: compressed.length,
216-
uncompressedSize: rawData.length,
217-
offset,
218-
};
219-
220-
entries.push(entry);
210+
parts.push(header, compressed);
221211

222212
const dirEntry = createCentralDirectoryEntry(
223-
entry.path,
224-
entry.compressedSize,
225-
entry.uncompressedSize,
226-
entry.offset,
227-
entry.crc32,
213+
filenameCleaned,
214+
compressed.length,
215+
rawData.length,
216+
offset,
217+
checksum,
228218
);
229219
centralDir.push(dirEntry);
230220
centralDirSize += dirEntry.length;
231221

232222
offset += header.length + compressed.length;
233223
}
234224

235-
const endOfCentralDir = createEndOfCentralDirectory(entries.length, centralDirSize, offset);
225+
const endOfCentralDir = createEndOfCentralDirectory(centralDir.length, centralDirSize, offset);
236226

237-
return new Uint8Array([
238-
...entries.map(e => [...e.header, ...e.compressed]).flat(),
239-
...centralDir.map(dir => [...dir]).flat(),
240-
...endOfCentralDir,
241-
]);
227+
return new Blob([...parts, ...centralDir, endOfCentralDir]);
242228
}
243229

244230
/**

‎contentcuration/contentcuration/frontend/shared/vuex/file/__tests__/clean.spec.js‎

Lines changed: 71 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
1+
import { randomFillSync } from 'crypto';
12
import JSZip from 'jszip';
23
import { cleanFile } from '../clean';
34

5+
function readBytes(blob) {
6+
return new Promise((resolve, reject) => {
7+
const reader = new FileReader();
8+
reader.onload = () => resolve(new Uint8Array(reader.result));
9+
reader.onerror = reject;
10+
reader.readAsArrayBuffer(blob);
11+
});
12+
}
13+
414
describe('cleanFile', () => {
515
let mockZip;
616
let originalCreateElement;
@@ -19,10 +29,14 @@ describe('cleanFile', () => {
1929

2030
// Helper function to create a zip file with given contents
2131
async function createTestZip(files, options = {}) {
32+
const zip = new JSZip();
2233
for (const [path, content] of Object.entries(files)) {
23-
mockZip.file(path, content);
34+
zip.file(path, content, { date: options.date });
2435
}
25-
const zipContent = await mockZip.generateAsync({ type: 'blob' });
36+
const zipContent = await zip.generateAsync({
37+
type: 'blob',
38+
compression: options.compression || 'STORE',
39+
});
2640
return new File([zipContent], options.filename || 'test.zip', {
2741
type: 'application/zip',
2842
lastModified: options.lastModified || Date.now(),
@@ -85,6 +99,61 @@ describe('cleanFile', () => {
8599
expect(cleanedPaths).toContain('index.html');
86100
expect(cleanedPaths).toContain('assets/style.css');
87101
});
102+
103+
it('should preserve file contents', async () => {
104+
const binary = new Uint8Array([0x00, 0xff, 0x10, 0x80, 0x7f]);
105+
const file = await createTestZip({
106+
'dist/index.html': '<html>ünïcödé</html>',
107+
'dist/model/weights.bin': binary,
108+
});
109+
const cleanedZip = await JSZip.loadAsync(await cleanFile(file));
110+
111+
expect(await cleanedZip.file('index.html').async('string')).toBe('<html>ünïcödé</html>');
112+
expect(await cleanedZip.file('model/weights.bin').async('uint8array')).toEqual(binary);
113+
});
114+
115+
it('should produce identical bytes for the same files zipped differently', async () => {
116+
const files = {
117+
'index.html': '<html></html>',
118+
'js/main.js': "console.log('hello')",
119+
};
120+
const nestedReversed = {
121+
'build/js/main.js': files['js/main.js'],
122+
'build/index.html': files['index.html'],
123+
};
124+
const first = await cleanFile(await createTestZip(files, { date: new Date(2020, 1, 1) }));
125+
const second = await cleanFile(
126+
await createTestZip(nestedReversed, {
127+
compression: 'DEFLATE',
128+
date: new Date(2024, 5, 5),
129+
}),
130+
);
131+
132+
expect(await readBytes(second)).toEqual(await readBytes(first));
133+
});
134+
135+
it('should keep the original file name, type and modification time', async () => {
136+
const file = await createTestZip(
137+
{ 'dist/index.html': '<html></html>' },
138+
{ filename: 'course.zip', lastModified: 1234567890 },
139+
);
140+
const cleanedFile = await cleanFile(file);
141+
142+
expect(cleanedFile.name).toBe('course.zip');
143+
expect(cleanedFile.type).toBe('application/zip');
144+
expect(cleanedFile.lastModified).toBe(1234567890);
145+
});
146+
147+
it('should clean zips of incompressible content larger than 100 MB', async () => {
148+
const size = 110 * 1024 * 1024;
149+
const file = await createTestZip({
150+
'index.html': '<html></html>',
151+
'model/weights.bin': randomFillSync(new Uint8Array(size)),
152+
});
153+
const cleanedFile = await cleanFile(file);
154+
155+
expect(cleanedFile.size).toBeGreaterThan(size);
156+
}, 120000);
88157
});
89158

90159
describe('Error handling', () => {

‎contentcuration/contentcuration/frontend/shared/vuex/file/clean.js‎

Lines changed: 8 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,6 @@ import { inferPreset } from './utils';
33
import { createPredictableZip, findCommonRoot } from 'shared/utils/zipFile';
44
import { FormatPresetsNames } from 'shared/leUtils/FormatPresets';
55

6-
/**
7-
* Creates a new files object with common root directory removed
8-
* @param {Object} files - JSZip files object
9-
* @param {string} commonRoot - Common root path to remove
10-
* @returns {Object} New files object with paths remapped
11-
*/
12-
async function remapFiles(files, commonRoot) {
13-
const cleanedFiles = {};
14-
commonRoot = commonRoot === '' ? commonRoot : commonRoot + '/';
15-
const commonRootLength = commonRoot.length;
16-
17-
for (const [path, file] of Object.entries(files)) {
18-
if (!file.dir) {
19-
// Skip directory entries
20-
const newPath = path.slice(commonRootLength);
21-
cleanedFiles[newPath] = await file.async('uint8array');
22-
}
23-
}
24-
25-
return cleanedFiles;
26-
}
27-
286
/**
297
* Cleans an HTML5 zip file by removing unnecessary directory nesting
308
* @param {File} file - The HTML5 zip file to clean
@@ -37,13 +15,18 @@ export async function cleanHTML5Zip(file) {
3715

3816
// Find and remove common root directory
3917
const commonRoot = findCommonRoot(zipContent.files);
40-
const cleanedFiles = await remapFiles(zipContent.files, commonRoot);
18+
const rootPrefix = commonRoot === '' ? '' : commonRoot + '/';
19+
const cleanedPaths = Object.entries(zipContent.files)
20+
.filter(([, entry]) => !entry.dir)
21+
.map(([path]) => path.slice(rootPrefix.length));
4122

4223
// Create new predictable zip with cleaned files
43-
const cleanedZipBuffer = await createPredictableZip(cleanedFiles);
24+
const cleanedZip = await createPredictableZip(cleanedPaths, path =>
25+
zipContent.files[rootPrefix + path].async('uint8array'),
26+
);
4427

4528
// Create new File object with original metadata
46-
const cleanedFile = new File([cleanedZipBuffer], file.name, {
29+
const cleanedFile = new File([cleanedZip], file.name, {
4730
type: file.type,
4831
lastModified: file.lastModified,
4932
});

0 commit comments

Comments
 (0)