Skip to content

Commit c601fff

Browse files
committed
fix(cache): harden cache directive parsing
Signed-off-by: Matteo Collina <[email protected]>
1 parent 2b3f749 commit c601fff

12 files changed

Lines changed: 2739 additions & 696 deletions

File tree

‎lib/cache/memory-cache-store.js‎

Lines changed: 54 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -218,17 +218,62 @@ class MemoryCacheStore extends EventEmitter {
218218
}
219219

220220
function findEntry (key, entries, now) {
221-
return entries.find((entry) => (
222-
entry.deleteAt > now &&
223-
entry.method === key.method &&
224-
(entry.vary == null || Object.keys(entry.vary).every(headerName => {
225-
if (entry.vary[headerName] === null) {
226-
return key.headers[headerName] === undefined
221+
for (let i = 0; i < entries.length; i++) {
222+
const entry = entries[i]
223+
if (
224+
entry.deleteAt > now &&
225+
entry.method === key.method &&
226+
varyMatches(key, entry)
227+
) {
228+
return entry
229+
}
230+
}
231+
}
232+
233+
function varyMatches (key, entry) {
234+
if (entry.vary == null) {
235+
return true
236+
}
237+
238+
for (const headerName in entry.vary) {
239+
if (Object.hasOwn(entry.vary, headerName) && !headerValueEquals(key.headers?.[headerName], entry.vary[headerName])) {
240+
return false
241+
}
242+
}
243+
244+
return true
245+
}
246+
247+
/**
248+
* @param {string|string[]|null|undefined} lhs
249+
* @param {string|string[]|null|undefined} rhs
250+
* @returns {boolean}
251+
*/
252+
function headerValueEquals (lhs, rhs) {
253+
if (lhs == null && rhs == null) {
254+
return true
255+
}
256+
257+
if ((lhs == null && rhs != null) ||
258+
(lhs != null && rhs == null)) {
259+
return false
260+
}
261+
262+
if (Array.isArray(lhs) && Array.isArray(rhs)) {
263+
if (lhs.length !== rhs.length) {
264+
return false
265+
}
266+
267+
for (let i = 0; i < lhs.length; i++) {
268+
if (lhs[i] !== rhs[i]) {
269+
return false
227270
}
271+
}
272+
273+
return true
274+
}
228275

229-
return entry.vary[headerName] === key.headers[headerName]
230-
}))
231-
))
276+
return lhs === rhs
232277
}
233278

234279
module.exports = MemoryCacheStore

‎lib/cache/sqlite-cache-store.js‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -456,7 +456,13 @@ function headerValueEquals (lhs, rhs) {
456456
return false
457457
}
458458

459-
return lhs.every((x, i) => x === rhs[i])
459+
for (let i = 0; i < lhs.length; i++) {
460+
if (lhs[i] !== rhs[i]) {
461+
return false
462+
}
463+
}
464+
465+
return true
460466
}
461467

462468
return lhs === rhs

0 commit comments

Comments
 (0)