-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.test.ts
More file actions
342 lines (300 loc) · 11.1 KB
/
Parser.test.ts
File metadata and controls
342 lines (300 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import type { VirtualFile, VirtualDirectory } from './types.js';
import type { MetadataKeywords } from '#types.js';
import fs from 'fs';
import path from 'path';
import os from 'os';
import fc from 'fast-check';
import { test } from '@fast-check/jest';
import * as tar from 'tar';
import * as testsUtils from './utils/index.js';
import Parser from '#Parser.js';
import { ParserState } from '#types.js';
import * as errors from '#errors.js';
import * as utils from '#utils.js';
import * as constants from '#constants.js';
describe('parsing archive blocks', () => {
test.prop([testsUtils.tarEntryArb()])(
'should parse headers with correct state',
({ headers, data }) => {
const { type, path, stat } = data;
const parser = new Parser();
const token = parser.write(headers[0]);
expect(token?.type).toEqual('header');
if (token?.type !== 'header') utils.never('Token type');
// @ts-ignore: accessing protected member for state analysis
const state = parser.state;
switch (type) {
case 'file':
// The file can have an extended header or a regular header
if (data.path.length > constants.STANDARD_PATH_SIZE) {
expect(token.fileType).toEqual('metadata');
expect(state).toEqual(ParserState.DATA);
} else {
// If there is no data, then another header can be parsed immediately
expect(token.fileType).toEqual('file');
if (stat.size !== 0) expect(state).toEqual(ParserState.DATA);
else expect(state).toEqual(ParserState.HEADER);
}
break;
case 'directory':
expect(state).toEqual(ParserState.HEADER);
expect(token.fileType).toEqual('directory');
break;
default:
utils.never('Invalid state');
}
expect(token.filePath).toEqual(path);
expect(token.ownerUid).toEqual(stat.uid);
expect(token.ownerGid).toEqual(stat.gid);
},
);
test.prop([fc.uint8Array({ minLength: 512, maxLength: 512 })])(
'should fail to parse gibberish data',
(data) => {
// Make sure a null block doesn't get tested. It is reserved for ending a
// tar archive.
fc.pre(!utils.isNullBlock(data));
const parser = new Parser();
expect(() => parser.write(data)).toThrowError(
errors.ErrorVirtualTarParserInvalidHeader,
);
},
);
test.prop([fc.uint8Array()])(
'should fail to parse blocks with arbitrary size',
(data) => {
// Make sure a null block doesn't get tested. It is reserved for ending a
// tar archive.
fc.pre(data.length !== constants.BLOCK_SIZE);
const parser = new Parser();
expect(() => parser.write(data)).toThrowError(
errors.ErrorVirtualTarParserBlockSize,
);
},
);
test.prop(
[testsUtils.tarEntryArb(), fc.uint8Array({ minLength: 8, maxLength: 8 })],
{
numRuns: 1,
},
)(
'should fail to parse header with an invalid checksum',
({ headers }, checksum) => {
headers[0].set(checksum, constants.HEADER_OFFSET.CHECKSUM);
const parser = new Parser();
expect(() => parser.write(headers[0])).toThrowError(
errors.ErrorVirtualTarParserInvalidHeader,
);
},
);
describe('parsing end of archive', () => {
test('should parse end of archive', () => {
const parser = new Parser();
const token1 = parser.write(new Uint8Array(constants.BLOCK_SIZE));
expect(token1).toBeUndefined();
// @ts-ignore: accessing protected member for state analysis
expect(parser.state).toEqual(ParserState.NULL);
const token2 = parser.write(new Uint8Array(constants.BLOCK_SIZE));
expect(token2?.type).toEqual('end');
// @ts-ignore: accessing protected member for state analysis
expect(parser.state).toEqual(ParserState.ENDED);
});
test.prop([testsUtils.tarEntryArb()], { numRuns: 1 })(
'should fail if end of archive is malformed',
({ headers }) => {
const parser = new Parser();
const token1 = parser.write(new Uint8Array(constants.BLOCK_SIZE));
expect(token1).toBeUndefined();
expect(() => parser.write(headers[0])).toThrowError(
errors.ErrorVirtualTarParserEndOfArchive,
);
},
);
test.prop([testsUtils.tarEntryArb()], { numRuns: 1 })(
'should fail if data is written after parser ending',
({ headers }) => {
const parser = new Parser();
// @ts-ignore: updating parser state for testing
parser.state = ParserState.ENDED;
expect(() => parser.write(headers[0])).toThrowError(
errors.ErrorVirtualTarParserEndOfArchive,
);
},
);
});
});
describe('parsing extended metadata', () => {
test.prop(
[testsUtils.tarEntryArb({ minFilePathSize: 256, maxFilePathSize: 512 })],
{
numRuns: 1,
},
)('should create pax header with long paths', ({ headers }) => {
const parser = new Parser();
const token = parser.write(headers[0]);
expect(token?.type).toEqual('header');
// @ts-ignore: accessing protected member for state analysis
expect(parser.state).toEqual(ParserState.DATA);
});
test.prop(
[testsUtils.tarEntryArb({ minFilePathSize: 256, maxFilePathSize: 512 })],
{
numRuns: 1,
},
)('should retrieve full file path from pax header', ({ headers, data }) => {
// Get the header size
const parser = new Parser();
const paxHeader = parser.write(headers[0]);
if (paxHeader == null || paxHeader.type !== 'header') {
throw new Error('Invalid state');
}
const size = paxHeader.fileSize;
// Concatenate all the data into a single array
const numDataBlocks = Math.ceil(size / constants.BLOCK_SIZE);
const dataBlock = new Uint8Array(size);
let offset = 0;
for (const header of headers.slice(1, 1 + numDataBlocks)) {
const paxData = parser.write(header);
if (paxData == null || paxData.type !== 'data') {
throw new Error(`Invalid state: ${paxData?.type}`);
}
dataBlock.set(paxData.data, offset);
offset += paxData.data.byteLength;
}
// Parse the data into a record
const parsedHeader = utils.decodeExtendedHeader(dataBlock);
expect(parsedHeader.path).toEqual(data.path);
// The actual path in the header is ignored if the PAX header contains
// metadata for the file path. Ignoring this is dependant on the user
// instead of on the parser.
});
});
describe('testing against tar', () => {
let tempDir: string | undefined;
afterEach(async () => {
if (tempDir) {
await fs.promises.rm(tempDir, { force: true, recursive: true });
}
});
test.prop([testsUtils.fileTreeArb()], { numRuns: 100 })(
'should match output of tar',
async (fileTree) => {
// Create a temp directory to use for node-tar
const tempDir = await fs.promises.mkdtemp(
path.join(os.tmpdir(), 'js-virtualtar-test-'),
);
try {
const fileTreePath = path.join(tempDir, 'tree');
await fs.promises.mkdir(fileTreePath);
// Write the vfs to disk for tar to archive
const writeFileTree = async (entry: VirtualFile | VirtualDirectory) => {
const entryPath = path.join(fileTreePath, entry.path);
if (entry.type === 'directory') {
await fs.promises.mkdir(entryPath, { recursive: true });
} else {
await fs.promises.writeFile(entryPath, entry.content);
}
};
for (const entry of fileTree) await writeFileTree(entry);
// Use tar to archive the file
const archivePath = path.join(tempDir, 'archive.tar');
const entries = await fs.promises.readdir(fileTreePath);
const archive = tar.create(
{
cwd: fileTreePath,
preservePaths: true,
},
entries,
);
const fd = await fs.promises.open(archivePath, 'w');
for await (const chunk of archive) {
await fd.write(chunk);
}
await fd.close();
const chunks: Uint8Array[] = [];
const stream = fs.createReadStream(archivePath, { highWaterMark: 512 });
for await (const chunk of stream) {
chunks.push(new Uint8Array(chunk.buffer));
}
const parser = new Parser();
const encoder = new TextEncoder();
const reconstructedTree: Record<string, Uint8Array | null> = {};
let workingPath: string | undefined = undefined;
let workingData: Uint8Array = new Uint8Array();
let extendedData: Uint8Array | undefined;
let dataOffset = 0;
for (const chunk of chunks) {
const token = parser.write(chunk);
if (token == null) continue;
switch (token.type) {
case 'header': {
let extendedMetadata:
| Partial<Record<MetadataKeywords, string>>
| undefined;
if (extendedData != null) {
extendedMetadata = utils.decodeExtendedHeader(extendedData);
}
const fullPath = extendedMetadata?.path
? extendedMetadata.path
: token.filePath;
if (workingPath != null) {
reconstructedTree[workingPath] = workingData;
workingData = new Uint8Array();
workingPath = undefined;
}
switch (token.fileType) {
case 'file': {
workingPath = fullPath;
break;
}
case 'directory': {
reconstructedTree[fullPath] = null;
break;
}
case 'extended': {
extendedData = new Uint8Array(token.fileSize);
extendedMetadata = {};
break;
}
default:
throw new Error('Invalid state');
}
// If we were using the extended metadata for this header, reset it
// for the next header.
extendedData = undefined;
dataOffset = 0;
break;
}
case 'data': {
if (extendedData == null) {
workingData = utils.concatUint8Arrays(workingData, token.data);
} else {
extendedData.set(token.data, dataOffset);
dataOffset += token.data.byteLength;
}
break;
}
case 'end': {
// Finalise adding the last file into the tree
if (workingPath != null) {
reconstructedTree[workingPath] = workingData;
workingData = new Uint8Array();
workingPath = undefined;
}
}
}
}
for (const entry of fileTree) {
if (entry.type === 'file') {
const content = encoder.encode(entry.content);
expect(reconstructedTree[entry.path]).toEqual(content);
} else {
expect(reconstructedTree[entry.path]).toBeNull();
}
}
} finally {
await fs.promises.rm(tempDir, { force: true, recursive: true });
}
},
);
});