Skip to content

Commit 2b32aef

Browse files
committed
fix(cache): reject oversized keys to prevent memory bloat JhaSourav07#1403
1 parent 211cbb5 commit 2b32aef

2 files changed

Lines changed: 10 additions & 4 deletions

File tree

lib/cache.test.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -581,16 +581,18 @@ describe('TTLCache', () => {
581581
cache.destroy();
582582
});
583583

584-
it('handles oversized cache keys safely', () => {
584+
// FIX: New test targeting oversized cache keys for Issue #1403
585+
it('rejects oversized cache keys to prevent memory bloat (Variation 2)', () => {
585586
const cache = new TTLCache<string>();
586-
587587
const oversizedKey = 'a'.repeat(20000);
588588

589+
// Assert that setting a massive key throws an error to prevent memory bloat
589590
expect(() => {
590591
cache.set(oversizedKey, 'large-key-value', 60_000);
591-
}).not.toThrow();
592+
}).toThrow();
592593

593-
expect(cache.get(oversizedKey)).toBe('large-key-value');
594+
// Verify the key was not saved
595+
expect(cache.has(oversizedKey)).toBe(false);
594596

595597
cache.destroy();
596598
});

lib/cache.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,10 @@ export class TTLCache<T> {
159159
if (key === '') throw new Error('Cache key cannot be empty');
160160
if (ttlMs <= 0) throw new RangeError(`ttlMs must be positive, got ${ttlMs}`);
161161

162+
if (key.length > 10000) {
163+
throw new Error('Cache key exceeds maximum allowed length to prevent memory bloat');
164+
}
165+
162166
const maxSize = this.maxSize;
163167
if (maxSize !== undefined && this.store.size >= maxSize && !this.store.has(key)) {
164168
this.sweep();

0 commit comments

Comments
 (0)