-
Notifications
You must be signed in to change notification settings - Fork 29
/
verify.js
402 lines (373 loc) · 10.2 KB
/
verify.js
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
'use strict'
const contentPath = require('../lib/content/path')
const index = require('../lib/entry-index')
const fs = require('fs/promises')
const path = require('path')
const t = require('tap')
const ssri = require('ssri')
const CacheContent = require('./fixtures/cache-content')
const CONTENT = Buffer.from('foobarbaz', 'utf8')
const KEY = 'my-test-key'
const INTEGRITY = ssri.fromData(CONTENT)
const METADATA = { foo: 'bar' }
const cacache = require('..')
const verify = cacache.verify
// defines reusable errors
const genericError = new Error('ERR')
genericError.code = 'ERR'
// helpers
const getVerify = (t, opts) => t.mock('../lib/verify', opts)
async function mockCache (t) {
const cacheContent = CacheContent({
[INTEGRITY]: CONTENT,
})
cacheContent.tmp = {}
const CACHE = t.testdir(cacheContent)
await index.insert(CACHE, KEY, INTEGRITY, {
metadata: METADATA,
})
return CACHE
}
t.test('removes corrupted index entries from buckets', async t => {
const CACHE = await mockCache(t)
const BUCKET = index.bucketPath(CACHE, KEY)
const BUCKETDATA = await fs.readFile(BUCKET, 'utf8')
// traaaaash
await fs.appendFile(BUCKET, '\n234uhhh')
const stats = await verify(CACHE)
t.equal(
stats.missingContent,
0,
'content valid because of good entry'
)
t.equal(stats.totalEntries, 1, 'only one entry counted')
const bucketData = await fs.readFile(BUCKET, 'utf8')
const bucketEntry = JSON.parse(bucketData.split('\t')[1])
const targetEntry = JSON.parse(BUCKETDATA.split('\t')[1])
targetEntry.time = bucketEntry.time // different timestamps
t.same(
bucketEntry,
targetEntry,
'bucket only contains good entry'
)
})
t.test('removes shadowed index entries from buckets', async t => {
const CACHE = await mockCache(t)
const BUCKET = index.bucketPath(CACHE, KEY)
const newEntry = await index.insert(CACHE, KEY, INTEGRITY, { metadata: 'meh' })
const stats = await verify(CACHE)
t.equal(
stats.missingContent,
0,
'content valid because of good entry'
)
t.equal(stats.totalEntries, 1, 'only one entry counted')
const bucketData = await fs.readFile(BUCKET, 'utf8')
const stringified = JSON.stringify({
key: newEntry.key,
integrity: newEntry.integrity.toString(),
time: +bucketData.match(/"time":([0-9]+)/)[1],
metadata: newEntry.metadata,
})
t.equal(
bucketData,
`\n${index.hashEntry(stringified)}\t${stringified}`,
'only the most recent entry is still in the bucket'
)
})
t.test('accepts function for custom user filtering of index entries', async t => {
const KEY2 = KEY + 'aaa'
const KEY3 = KEY + 'bbb'
const CACHE = await mockCache(t)
const [entryA, entryB] = await Promise.all([
index.insert(CACHE, KEY2, INTEGRITY, {
metadata: 'haayyyy',
}),
index.insert(CACHE, KEY3, INTEGRITY, {
metadata: 'haayyyy again',
}),
])
const newEntries = {
[entryA.key]: entryA,
[entryB.key]: entryB,
}
const stats = await verify(CACHE, {
filter (entry) {
return entry.key.length === KEY2.length
},
})
t.same(
{
verifiedContent: stats.verifiedContent,
rejectedEntries: stats.rejectedEntries,
totalEntries: stats.totalEntries,
},
{
verifiedContent: 1,
rejectedEntries: 1,
totalEntries: 2,
},
'reported relevant changes'
)
const entries = await index.ls(CACHE)
entries[KEY2].time = newEntries[KEY2].time
entries[KEY3].time = newEntries[KEY3].time
t.same(entries, newEntries, 'original entry not included')
})
t.test('removes corrupted content', async t => {
const CACHE = await mockCache(t)
const cpath = contentPath(CACHE, INTEGRITY)
await fs.truncate(cpath, CONTENT.length - 1)
const stats = await verify(CACHE)
delete stats.startTime
delete stats.runTime
delete stats.endTime
t.same(
stats,
{
verifiedContent: 0,
reclaimedCount: 1,
reclaimedSize: CONTENT.length - 1,
badContentCount: 1,
keptSize: 0,
missingContent: 1,
rejectedEntries: 1,
totalEntries: 0,
},
'reported correct collection counts'
)
await t.rejects(
fs.stat(cpath),
/no such file/,
'content no longer in cache'
)
})
t.test('removes content not referenced by any entries', async t => {
const CACHE = t.testdir(
CacheContent({
[INTEGRITY]: CONTENT,
})
)
const stats = await verify(CACHE)
delete stats.startTime
delete stats.runTime
delete stats.endTime
t.same(
stats,
{
verifiedContent: 0,
reclaimedCount: 1,
reclaimedSize: CONTENT.length,
badContentCount: 0,
keptSize: 0,
missingContent: 0,
rejectedEntries: 0,
totalEntries: 0,
},
'reported correct collection counts'
)
})
t.test('cleans up contents of tmp dir', async t => {
const CACHE = await mockCache(t)
const tmpFile = path.join(CACHE, 'tmp', 'x')
const misc = path.join(CACHE, 'y')
await Promise.all([fs.writeFile(tmpFile, ''), fs.writeFile(misc, '')])
await verify(CACHE)
const [err, stat] = await Promise.all([
fs.stat(tmpFile).catch((err) => {
if (err.code === 'ENOENT') {
return err
}
throw err
}),
fs.stat(misc),
])
t.equal(err.code, 'ENOENT', 'tmp file was blown away')
t.ok(stat, 'misc file was not touched')
})
t.test('writes a file with last verification time', async t => {
const CACHE = t.testdir()
await verify(CACHE)
const [fromLastRun, fromFile] = await Promise.all([
verify.lastRun(CACHE),
fs.readFile(path.join(CACHE, '_lastverified'), 'utf8').then((data) => {
return new Date(parseInt(data))
}),
])
t.equal(+fromLastRun, +fromFile, 'last verified was writen')
})
t.test('missing file error when validating cache content', async t => {
const missingFileError = new Error('ENOENT')
missingFileError.code = 'ENOENT'
const mockVerify = getVerify(t, {
'fs/promises': Object.assign({}, fs, {
stat: async (path) => {
throw missingFileError
},
}),
})
t.plan(1)
const CACHE = await mockCache(t)
await t.resolveMatch(
mockVerify(CACHE),
{
verifiedContent: 0,
rejectedEntries: 1,
totalEntries: 0,
},
'should reject entry'
)
})
t.test('unknown error when validating content', async t => {
const mockVerify = getVerify(t, {
'fs/promises': Object.assign({}, fs, {
stat: async (path) => {
throw genericError
},
}),
})
t.plan(1)
const CACHE = await mockCache(t)
await t.rejects(
mockVerify(CACHE),
genericError,
'should throw any unknown errors'
)
})
t.test('unknown error when checking sri stream', async t => {
const mockVerify = getVerify(t, {
ssri: Object.assign({}, ssri, {
checkStream: () => Promise.reject(genericError),
}),
})
const CACHE = await mockCache(t)
await t.rejects(
mockVerify(CACHE),
genericError,
'should throw any unknown errors'
)
})
t.test('unknown error when rebuilding bucket', async t => {
// rebuild bucket uses stat after content-validation
// shouldFail controls the right time to mock the error
let shouldFail = false
const mockVerify = getVerify(t, {
'fs/promises': Object.assign({}, fs, {
stat: async (path) => {
if (shouldFail) {
throw genericError
}
shouldFail = true
return fs.stat(path)
},
}),
})
const CACHE = await mockCache(t)
await t.rejects(
mockVerify(CACHE),
genericError,
'should throw any unknown errors'
)
})
t.test('re-builds the index with the size parameter', async t => {
const KEY2 = KEY + 'aaa'
const KEY3 = KEY + 'bbb'
const CACHE = await mockCache(t)
await Promise.all([
index.insert(CACHE, KEY2, INTEGRITY, {
metadata: 'haayyyy',
size: 20,
}),
index.insert(CACHE, KEY3, INTEGRITY, {
metadata: 'haayyyy again',
size: 30,
}),
])
const newEntries = await index.ls(CACHE)
const stats = await verify(CACHE)
t.same(
{
verifiedContent: stats.verifiedContent,
rejectedEntries: stats.rejectedEntries,
totalEntries: stats.totalEntries,
},
{
verifiedContent: 1,
rejectedEntries: 0,
totalEntries: 3,
},
'reported relevant changes'
)
const entries = await index.ls(CACHE)
entries[KEY].time = newEntries[KEY].time
entries[KEY2].time = newEntries[KEY2].time
entries[KEY3].time = newEntries[KEY3].time
t.same(
entries,
newEntries,
'original index entries not preserved'
)
})
t.test('hash collisions', async t => {
const mockVerify = getVerify(t, {
'../lib/entry-index': Object.assign({}, index, {
hashKey: () => 'aaa',
}),
})
t.plan(1)
const CACHE = await mockCache(t)
await index.insert(CACHE, 'foo', INTEGRITY, {
metadata: 'foo',
})
const stats = await mockVerify(CACHE)
t.same(
{
verifiedContent: stats.verifiedContent,
rejectedEntries: stats.rejectedEntries,
totalEntries: stats.totalEntries,
},
{
verifiedContent: 1,
rejectedEntries: 0,
totalEntries: 2,
},
'should resolve with no errors'
)
})
t.test('hash collisions excluded', async t => {
const mockVerify = getVerify(t, {
'../lib/entry-index': Object.assign({}, index, {
hashKey: () => 'aaa',
}),
})
t.plan(1)
const CACHE = await mockCache(t)
await index.insert(CACHE, 'foo', INTEGRITY, { metadata: 'foo' })
const stats = await mockVerify(CACHE, { filter: () => null })
t.same(
{
verifiedContent: stats.verifiedContent,
rejectedEntries: stats.rejectedEntries,
totalEntries: stats.totalEntries,
},
{
verifiedContent: 0,
rejectedEntries: 2,
totalEntries: 0,
},
'should resolve while also excluding filtered out entries'
)
})
t.test('handles multiple hashes of the same content', async t => {
const cache = t.testdir()
let integrity
// anything other than the default (currently sha512)
await cacache.put.stream(cache, 'test', { algorithms: ['sha256'] }).on('integrity', i => {
integrity = i
}).end('CONTENT!').promise()
await cacache.put.stream(cache, 'test', { integrity }).end('CONTENT!').promise()
await cacache.verify(cache)
const ls = await cacache.ls(cache)
t.match(ls.test.integrity, 'sha512')
t.match(ls.test.integrity, 'sha256')
})