Skip to content

Commit 98011a8

Browse files
committed
fix(cache): harden cache directive parsing
Signed-off-by: Matteo Collina <hello@matteocollina.com>
1 parent 4a9dafb commit 98011a8

12 files changed

Lines changed: 2961 additions & 316 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
@@ -454,7 +454,13 @@ function headerValueEquals (lhs, rhs) {
454454
return false
455455
}
456456

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

460466
return lhs === rhs

0 commit comments

Comments
 (0)