@nathapp/nestjs-cache 2.1.0-rc.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +149 -0
- package/README.md +330 -420
- package/TODO.md +56 -0
- package/dist/enum/strategy.enum.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/inteceptor/index.d.ts +1 -2
- package/dist/inteceptor/index.js +1 -2
- package/dist/inteceptor/index.js.map +1 -1
- package/dist/interceptor/cache-invalidate.interceptor.js.map +1 -0
- package/dist/{inteceptor → interceptor}/cache.interceptor.js +9 -3
- package/dist/interceptor/cache.interceptor.js.map +1 -0
- package/dist/interceptor/index.d.ts +2 -0
- package/dist/interceptor/index.js +19 -0
- package/dist/interceptor/index.js.map +1 -0
- package/dist/interface/cache-invalidate.interface.d.ts +8 -0
- package/dist/interface/enhanced-cache-options.interface.d.ts +16 -0
- package/dist/interface/health.interface.d.ts +19 -0
- package/dist/interface/health.interface.js +3 -0
- package/dist/interface/health.interface.js.map +1 -0
- package/dist/interface/index.d.ts +2 -0
- package/dist/interface/index.js +2 -0
- package/dist/interface/index.js.map +1 -1
- package/dist/interface/metrics.interface.d.ts +17 -0
- package/dist/interface/metrics.interface.js +3 -0
- package/dist/interface/metrics.interface.js.map +1 -0
- package/dist/module/cache-invalidate.provider.js +5 -0
- package/dist/module/cache-invalidate.provider.js.map +1 -1
- package/dist/module/cache-module.interface.d.ts +1 -0
- package/dist/module/cache.module.d.ts +2 -1
- package/dist/module/cache.module.js +7 -3
- package/dist/module/cache.module.js.map +1 -1
- package/dist/module/cache.provider.js +69 -1
- package/dist/module/cache.provider.js.map +1 -1
- package/dist/provider/cacheable.provider.d.ts +3 -0
- package/dist/provider/cacheable.provider.js +120 -35
- package/dist/provider/cacheable.provider.js.map +1 -1
- package/dist/service/cache-invalidate.factory.js.map +1 -1
- package/dist/service/cache-invalidate.manager.d.ts +4 -3
- package/dist/service/cache-invalidate.manager.js +8 -5
- package/dist/service/cache-invalidate.manager.js.map +1 -1
- package/dist/service/cache-manager.d.ts +39 -8
- package/dist/service/cache-manager.js +579 -71
- package/dist/service/cache-manager.js.map +1 -1
- package/dist/service/cache-provider.js +3 -6
- package/dist/service/cache-provider.js.map +1 -1
- package/dist/service/cache-tag-registry.d.ts +30 -0
- package/dist/service/cache-tag-registry.js +100 -0
- package/dist/service/cache-tag-registry.js.map +1 -0
- package/dist/service/index.d.ts +1 -0
- package/dist/service/index.js +1 -0
- package/dist/service/index.js.map +1 -1
- package/dist/service/redis-cache-invalidate.manager.d.ts +9 -1
- package/dist/service/redis-cache-invalidate.manager.js +107 -55
- package/dist/service/redis-cache-invalidate.manager.js.map +1 -1
- package/dist/service/redis-pattern-invalidation.js +4 -0
- package/dist/service/redis-pattern-invalidation.js.map +1 -1
- package/dist/utils/cache-key.utils.d.ts +3 -0
- package/dist/utils/cache-key.utils.js +34 -2
- package/dist/utils/cache-key.utils.js.map +1 -1
- package/dist/utils/config-validation.d.ts +2 -0
- package/dist/utils/config-validation.js +57 -0
- package/dist/utils/config-validation.js.map +1 -0
- package/dist/utils/deprecation.d.ts +1 -0
- package/dist/utils/deprecation.js +13 -2
- package/dist/utils/deprecation.js.map +1 -1
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.js +3 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/redis-uri.utils.d.ts +9 -0
- package/dist/utils/redis-uri.utils.js +62 -0
- package/dist/utils/redis-uri.utils.js.map +1 -0
- package/dist/utils/validation.d.ts +10 -0
- package/dist/utils/validation.js +39 -0
- package/dist/utils/validation.js.map +1 -0
- package/docker-compose.e2e.yml +16 -0
- package/docs/CACHEOBLESYNC-MIGRATION-PLAN.md +55 -0
- package/docs/CODE-REVIEW-2026-02-10-v2.md +134 -0
- package/docs/CODE-REVIEW-2026-02-10.md +142 -0
- package/docs/CODE_REVIEW.md +356 -0
- package/docs/FINAL-CODE-REVIEW-2026-02-10.md +312 -0
- package/docs/IMPLEMENTATION_PLAN.md +1045 -0
- package/docs/IMPLEMENTATION_PLAN_V2.md +201 -0
- package/docs/IMPLEMENTATION_PLAN_V3.md +169 -0
- package/docs/IMPLEMENTATION_TASKS.md +1090 -0
- package/docs/PHASE3_COVERAGE_TASKS.md +266 -0
- package/docs/TAG-BASED-INVALIDATION-PLAN.md +367 -0
- package/docs/UNIFIED-INVALIDATE-PLAN.md +229 -0
- package/package.json +11 -4
- package/dist/inteceptor/cache-invalidate.interceptor.js.map +0 -1
- package/dist/inteceptor/cache.interceptor.js.map +0 -1
- /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.d.ts +0 -0
- /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.js +0 -0
- /package/dist/{inteceptor → interceptor}/cache.interceptor.d.ts +0 -0
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# nestjs-cache Code Review — 2026-02-10
|
|
2
|
+
|
|
3
|
+
**Reviewer:** Subrina (AI) · **Scope:** Full source + test analysis · **Verdict: B — Solid architecture, needs hardening for enterprise production**
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 🐛 Bugs Found
|
|
8
|
+
|
|
9
|
+
### Critical
|
|
10
|
+
|
|
11
|
+
#### 1. Race condition in `touch()` — get-then-set is not atomic
|
|
12
|
+
- **File:** `lib/service/cache-manager.ts` ~L310-330
|
|
13
|
+
- **Description:** The `touch()` fallback does `get()` then `set()` — between these calls another process can delete or update the key, causing stale data to be re-written with a new TTL.
|
|
14
|
+
- **Fix:** Use Redis `EXPIRE` command directly instead of get+set. For the cacheable path, if `touch()` isn't available, accept the limitation but document it.
|
|
15
|
+
|
|
16
|
+
#### 2. `CacheProvider.get()` drops falsy values
|
|
17
|
+
- **File:** `lib/service/cache-provider.ts` L23, L31
|
|
18
|
+
- **Description:** `if (value)` is used to check cache hits. This means `false`, `0`, `""`, and `null` (all valid cached values) are treated as cache misses, causing the resolver to re-execute every time. The set guard on line 31 also gates on `if(value)`, so falsy values never get cached.
|
|
19
|
+
- **Fix:** Change `if (value)` to `if (value !== undefined && value !== null)` on both L23 and L31.
|
|
20
|
+
|
|
21
|
+
#### 3. `keys()` skips the last store
|
|
22
|
+
- **File:** `lib/service/cache-provider.ts` L117
|
|
23
|
+
- **Description:** Loop uses `i < storesLength - 1`, which always skips the last store. If there's only one store, zero iterations occur and `keys()` always returns `[]`. Pattern-based deletion via `delByPatternRaw` depends on `keys()`, so this **silently breaks all pattern invalidation in legacy mode**.
|
|
24
|
+
- **Fix:** Change to `i < storesLength`.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
### High
|
|
29
|
+
|
|
30
|
+
#### 4. Double error metric emission in `get()`
|
|
31
|
+
- **File:** `lib/service/cache-manager.ts` ~L120-130
|
|
32
|
+
- **Description:** `emitMetric('onCacheError', ...)` is called explicitly, then `handleCacheError()` is called which internally calls `emitMetric('onCacheError', ...)` again. Every cache error fires the metric **twice**, corrupting monitoring dashboards and alerting thresholds.
|
|
33
|
+
- **Fix:** Remove the explicit `emitMetric` call before `handleCacheError`, or remove the one inside `handleCacheError`.
|
|
34
|
+
|
|
35
|
+
#### 5. `dipatch()` returns `undefined` instead of `Promise<void>`
|
|
36
|
+
- **File:** `lib/service/redis-cache-invalidate.manager.ts` ~L110, L127
|
|
37
|
+
- **Description:** When validation fails or key is protected, the method returns `undefined` (no `return Promise.resolve()`). Since callers `await` the result, this works at runtime but is semantically incorrect. Also `subscribe()` in `EmptyCacheInvalidateManager` returns bare `undefined` from a `Promise<void>`-typed method.
|
|
38
|
+
- **Fix:** Mark methods as `async` or return `Promise.resolve()`.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
### Medium
|
|
43
|
+
|
|
44
|
+
#### 6. `CacheInterceptor` crashes if `nestjs-i18n` is not installed
|
|
45
|
+
- **File:** `lib/inteceptor/cache.interceptor.ts`, constructor
|
|
46
|
+
- **Description:** `loadPackage` will throw or return an empty object. If it throws, the interceptor fails to instantiate entirely.
|
|
47
|
+
- **Fix:** Wrap in try-catch: `try { ... } catch { this.hasI18n = false; }`
|
|
48
|
+
|
|
49
|
+
#### 7. `isCacheInvalidateMessage` type guard misses edge cases
|
|
50
|
+
- **File:** `lib/service/cache-manager.ts` ~L265
|
|
51
|
+
- **Description:** `(cacheKeyParts as CacheInvalidateMessage).cacheKey !== undefined` — if someone passes `{ cacheKey: undefined, group: true }`, the guard returns `false` and it's treated as a plain CacheKey, losing the `group` flag.
|
|
52
|
+
- **Fix:** Check shape more robustly: `typeof cacheKeyParts === 'object' && !Array.isArray(cacheKeyParts) && 'cacheKey' in cacheKeyParts`.
|
|
53
|
+
|
|
54
|
+
#### 8. `validateInvalidateMessage` exists but is never used in message handlers
|
|
55
|
+
- **File:** `lib/utils/validation.ts` / `lib/service/redis-cache-invalidate.manager.ts`
|
|
56
|
+
- **Description:** `handleSingleInvalidate` and `handleMultiInvalidate` use raw `JSON.parse` without the validation utility, bypassing all input validation.
|
|
57
|
+
- **Fix:** Use `parseInvalidateMessage()` in the message handlers.
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
### Low
|
|
62
|
+
|
|
63
|
+
#### 9. Typo: directory named `inteceptor` instead of `interceptor`
|
|
64
|
+
- **File:** `lib/inteceptor/`
|
|
65
|
+
- **Description:** Misspelling in directory name. Not a runtime bug but affects developer experience and discoverability.
|
|
66
|
+
|
|
67
|
+
#### 10. `mset` format may be incorrect
|
|
68
|
+
- **File:** `lib/service/cache-provider.ts` ~L63
|
|
69
|
+
- **Description:** `cache-manager`'s `mset` expects `[key, value, key, value, ...]` format (varies by version), not an array of objects. This may silently fail depending on the cache-manager version in use.
|
|
70
|
+
- **Fix:** Verify the expected API signature for the cache-manager version.
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## 🔒 Security Issues
|
|
75
|
+
|
|
76
|
+
### High
|
|
77
|
+
|
|
78
|
+
#### 1. Unsanitized JSON deserialization from Redis pub/sub
|
|
79
|
+
- **File:** `lib/service/redis-cache-invalidate.manager.ts` L78, L95
|
|
80
|
+
- **Description:** Messages from Redis pub/sub are `JSON.parse`'d and used directly to construct cache keys for deletion. A compromised Redis instance or malicious publisher could craft messages to delete arbitrary cache keys (cache poisoning / denial of service). The `validateInvalidateMessage` utility exists but is **NOT used here**.
|
|
81
|
+
- **Recommendation:** Use `parseInvalidateMessage()` for all incoming messages. Apply `sanitizeCacheKeyPart()` to parsed keys before deletion.
|
|
82
|
+
|
|
83
|
+
### Medium
|
|
84
|
+
|
|
85
|
+
#### 2. Protected key names leaked in logs
|
|
86
|
+
- **File:** `lib/service/redis-cache-invalidate.manager.ts` L125
|
|
87
|
+
- **Description:** `this.logger.warn(\`Protected key ${cacheKey} is not allowed to be invalidated\`)` — logs the actual key name, which could contain sensitive identifiers.
|
|
88
|
+
- **Recommendation:** Remove key value from log: `"Protected key invalidation attempt blocked"`.
|
|
89
|
+
|
|
90
|
+
#### 3. Redis password in URL construction
|
|
91
|
+
- **File:** `lib/provider/cacheable.provider.ts`, `buildRedisUrl()`
|
|
92
|
+
- **Description:** Redis password is embedded directly in the URL string. If this URL is logged anywhere (e.g., ioredis connection errors), the password leaks. `buildRedisUrlForLogging()` exists but there's no guarantee it's always used.
|
|
93
|
+
- **Recommendation:** Use connection objects instead of URL strings where possible. Ensure ioredis error handlers mask credentials.
|
|
94
|
+
|
|
95
|
+
#### 4. No rate limiting on cache invalidation pub/sub
|
|
96
|
+
- **File:** `lib/service/redis-cache-invalidate.manager.ts`
|
|
97
|
+
- **Description:** A flood of invalidation messages could cause denial-of-service by continuously clearing the cache. No throttling or rate limiting exists.
|
|
98
|
+
- **Recommendation:** Add a configurable rate limiter or debounce for invalidation operations.
|
|
99
|
+
|
|
100
|
+
### Low
|
|
101
|
+
|
|
102
|
+
#### 5. Pattern invalidation with overly broad patterns
|
|
103
|
+
- **File:** `lib/service/redis-pattern-invalidation.ts`
|
|
104
|
+
- **Description:** `deleteByPattern` takes a pattern string. If user input reaches this without sanitization, overly broad patterns like `*` could flush the entire cache.
|
|
105
|
+
- **Recommendation:** Validate pattern input, reject `*` alone as a pattern.
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## 🏢 Enterprise Readiness Assessment
|
|
110
|
+
|
|
111
|
+
| Area | Grade | Findings |
|
|
112
|
+
|------|-------|----------|
|
|
113
|
+
| **Error Handling** | **B+** | Good graceful degradation with `fallbackToMemory`. Proper try-catch in most operations. Dinged for double error metric emission and silent undefined returns. |
|
|
114
|
+
| **Code Quality** | **B** | Clean separation of concerns with provider/manager/interceptor layers. Good TypeScript interfaces. Dinged for typos (`inteceptor`, `dipatch`), inconsistent `any` typing, mixed async patterns. |
|
|
115
|
+
| **Testing** | **B+** | Comprehensive suite: 16 test files, ~3400 lines. Covers graceful degradation, metrics, namespaces, touch operations. Missing: real Redis integration tests, falsy value edge cases. |
|
|
116
|
+
| **Documentation** | **B** | Good JSDoc on public APIs. Strategy enum well documented. Missing: clear migration paths for deprecated APIs. |
|
|
117
|
+
| **Scalability** | **A-** | Multi-tier L1+L2 well designed. Redis SCAN for non-blocking pattern ops. UNLINK preferred over DEL. Pub/sub for distributed invalidation. `keys()` is O(n) but acknowledged. |
|
|
118
|
+
| **Security** | **C+** | Key sanitization (`sanitizeCacheKeyPart`) and protected keys exist. But validation utility isn't wired into critical paths. No rate limiting. Password in URLs. |
|
|
119
|
+
| **SOLID Principles** | **B+** | Good interface segregation (CacheMetrics, CacheHealthCheck). Strategy and factory patterns used well. CacheManager has too many responsibilities (caching + invalidation + health + metrics + namespace). |
|
|
120
|
+
| **Config Validation** | **C** | TTL parsing has validation. No startup validation of module options — invalid strategy, missing Redis config for DISTRIBUTED, etc. won't fail until runtime. |
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## 📋 Summary
|
|
125
|
+
|
|
126
|
+
**Overall Verdict: B — Solid library with good architecture, needs hardening before enterprise production.**
|
|
127
|
+
|
|
128
|
+
The package demonstrates thoughtful design with multi-tier caching, graceful degradation, extensible metrics, and pub/sub-based distributed invalidation. However, several bugs silently corrupt behavior and the security validation gap is concerning.
|
|
129
|
+
|
|
130
|
+
### Top 5 Priority Fixes
|
|
131
|
+
|
|
132
|
+
| Priority | Type | Issue | Impact |
|
|
133
|
+
|----------|------|-------|--------|
|
|
134
|
+
| **1** | 🐛 Critical | Fix falsy value handling in `CacheProvider.get()` | Silent data corruption — `false`, `0`, `""` never cached |
|
|
135
|
+
| **2** | 🐛 Critical | Fix `keys()` skipping last store | Breaks all pattern invalidation in legacy mode |
|
|
136
|
+
| **3** | 🔒 High | Wire `parseInvalidateMessage()` into Redis handlers | Validation exists but isn't used — pub/sub messages trusted raw |
|
|
137
|
+
| **4** | 🐛 High | Fix double error metric emission | Every cache error fires metric twice, corrupts monitoring |
|
|
138
|
+
| **5** | 🔒 Medium | Add startup configuration validation | DISTRIBUTED with no Redis config should fail fast, not at first request |
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
*Generated by Subrina · 2026-02-10*
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
# @nathapp/nestjs-cache Code Review
|
|
2
|
+
|
|
3
|
+
**Date**: 2026-02-09
|
|
4
|
+
**Reviewer**: Subrina
|
|
5
|
+
**Version**: 2.1.0-rc.0
|
|
6
|
+
**Branch**: cache-cacheable-migration
|
|
7
|
+
|
|
8
|
+
## Executive Summary
|
|
9
|
+
|
|
10
|
+
This code review focuses on memory leaks, security vulnerabilities, test coverage gaps, and enhancement opportunities. The package supports both **legacy mode** (`@nestjs/cache-manager`) and **enhanced mode** (`cacheable`) with zero breaking changes.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 🔴 Critical Issues
|
|
15
|
+
|
|
16
|
+
### C1. Memory Leak: `warnedFeatures` Set Never Cleared
|
|
17
|
+
|
|
18
|
+
**File**: `lib/utils/deprecation.ts`
|
|
19
|
+
**Severity**: Medium
|
|
20
|
+
**Impact**: Memory grows indefinitely in long-running applications
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
// Current implementation - Set grows forever
|
|
24
|
+
const warnedFeatures = new Set<string>();
|
|
25
|
+
|
|
26
|
+
export function warnDeprecation(feature: string, message: string, alternative?: string): void {
|
|
27
|
+
if (warnedFeatures.has(feature)) {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
warnedFeatures.add(feature);
|
|
31
|
+
// ...
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
**Issue**: While `clearDeprecationWarnings()` exists, it's only for testing. In production, if many unique deprecation warnings are generated (e.g., from dynamic feature names), the Set grows unbounded.
|
|
36
|
+
|
|
37
|
+
**Fix**: Add a max size limit or use LRU cache for warnings.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
### C2. Memory Leak: Redis Pattern Invalidation Creates New Instance Per Call
|
|
42
|
+
|
|
43
|
+
**File**: `lib/service/cache-manager.ts`
|
|
44
|
+
**Severity**: Medium
|
|
45
|
+
**Impact**: Creates new `RedisPatternInvalidation` instance on every `invalidateByPattern()` call
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
async invalidateByPattern(pattern: string): Promise<void> {
|
|
49
|
+
if (this.useCacheable && this.cacheable) {
|
|
50
|
+
try {
|
|
51
|
+
const { RedisPatternInvalidation } = await import('./redis-pattern-invalidation');
|
|
52
|
+
const invalidator = new RedisPatternInvalidation(this.cacheable); // New instance every call
|
|
53
|
+
await invalidator.deleteByPattern(pattern);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
// ...
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
**Fix**: Cache the `RedisPatternInvalidation` instance as a class property.
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
### C3. Potential Redis Connection Leak in RedisCacheInvalidateManager
|
|
66
|
+
|
|
67
|
+
**File**: `lib/service/redis-cache-invalidate.manager.ts`
|
|
68
|
+
**Severity**: High
|
|
69
|
+
**Impact**: Redis connections may not be properly closed on errors
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
public close() {
|
|
73
|
+
this.pubClient && this.pubClient.quit();
|
|
74
|
+
this.subClient && this.subClient.quit();
|
|
75
|
+
this.pubClient = this.subClient = null;
|
|
76
|
+
this.isExplicitlyTerminated = true;
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
**Issues**:
|
|
81
|
+
1. No error handling for `quit()` failures
|
|
82
|
+
2. No timeout for graceful shutdown
|
|
83
|
+
3. If `subscribe()` throws, clients may be left connected
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
### C4. Event Listener Leak in RedisCacheInvalidateManager
|
|
88
|
+
|
|
89
|
+
**File**: `lib/service/redis-cache-invalidate.manager.ts`
|
|
90
|
+
**Severity**: Medium
|
|
91
|
+
**Impact**: Event listeners not removed on close
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
async subscribe(): Promise<void> {
|
|
95
|
+
// ...
|
|
96
|
+
this.subClient.on('message', async (channel: string, message: string) => {
|
|
97
|
+
// Listener registered but never removed
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
**Fix**: Remove listener in `close()` method.
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## 🟡 Security Issues
|
|
107
|
+
|
|
108
|
+
### S1. JSON Parsing Without Validation
|
|
109
|
+
|
|
110
|
+
**File**: `lib/service/redis-cache-invalidate.manager.ts`
|
|
111
|
+
**Severity**: Medium
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
this.subClient.on('message', async (channel: string, message: string) => {
|
|
115
|
+
try {
|
|
116
|
+
const { cacheKey, group } = JSON.parse(message); // No validation
|
|
117
|
+
// ...
|
|
118
|
+
} catch(err) {
|
|
119
|
+
this.logger.error(`Failed to parse message: ${message}`);
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
**Issues**:
|
|
125
|
+
1. No validation of `cacheKey` structure
|
|
126
|
+
2. Logging raw message may expose sensitive data
|
|
127
|
+
3. No protection against prototype pollution
|
|
128
|
+
|
|
129
|
+
**Fix**: Validate message structure and sanitize before logging.
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
### S2. Cache Key Injection via Unsanitized Input
|
|
134
|
+
|
|
135
|
+
**File**: `lib/utils/cache-key.utils.ts`
|
|
136
|
+
**Severity**: Medium
|
|
137
|
+
|
|
138
|
+
```typescript
|
|
139
|
+
export const resolveCacheKey = (cacheKeyParts: CacheKey): string => {
|
|
140
|
+
if (Array.isArray(cacheKeyParts)) {
|
|
141
|
+
return cacheKeyParts.map(k => k.toUpperCase()).join(':');
|
|
142
|
+
}
|
|
143
|
+
return cacheKeyParts.toUpperCase();
|
|
144
|
+
}
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
**Issue**: No sanitization of special characters. Malicious input like `"../../../secret"` or `"key:*"` could cause issues.
|
|
148
|
+
|
|
149
|
+
**Fix**: Sanitize cache keys to remove dangerous patterns.
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
### S3. Protected Keys Bypass via Pattern Matching
|
|
154
|
+
|
|
155
|
+
**File**: `lib/service/redis-cache-invalidate.manager.ts`
|
|
156
|
+
**Severity**: Low
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
if (isProtectedKey(cacheKey, this.protectedKeys) ||
|
|
160
|
+
isProtectedKeyPrefix(cacheKey, this.protectedKeys, ':')) {
|
|
161
|
+
this.logger.warn(`Protected key ${cacheKey} is not allowed to be invalidated`);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
**Issue**: Pattern-based invalidation (`invalidateByPattern`) bypasses protected key checks entirely.
|
|
167
|
+
|
|
168
|
+
---
|
|
169
|
+
|
|
170
|
+
### S4. Redis Password Exposed in URL Logging
|
|
171
|
+
|
|
172
|
+
**File**: `lib/provider/cacheable.provider.ts`
|
|
173
|
+
**Severity**: Low
|
|
174
|
+
**Potential**: If URL is logged anywhere, password is exposed.
|
|
175
|
+
|
|
176
|
+
```typescript
|
|
177
|
+
export function buildRedisUrl(options: DistributedCacheOptions): string {
|
|
178
|
+
// ...
|
|
179
|
+
if (password) {
|
|
180
|
+
url += `:${password}@`; // Password in plain text
|
|
181
|
+
}
|
|
182
|
+
// ...
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
---
|
|
187
|
+
|
|
188
|
+
## 🟠 Test Coverage Gaps
|
|
189
|
+
|
|
190
|
+
### Current Coverage Status
|
|
191
|
+
|
|
192
|
+
```
|
|
193
|
+
Jest Coverage: 0% (misconfigured - collectCoverageFrom points to "src/**" but code is in "lib/**")
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
**Fix Jest Config** (`test/jest-test.json`):
|
|
197
|
+
```json
|
|
198
|
+
{
|
|
199
|
+
"collectCoverageFrom": [
|
|
200
|
+
"lib/**/*.ts",
|
|
201
|
+
"!lib/**/index.ts",
|
|
202
|
+
"!**/node_modules/**"
|
|
203
|
+
]
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Missing Test Coverage
|
|
208
|
+
|
|
209
|
+
| File | Current | Target | Gap |
|
|
210
|
+
|------|---------|--------|-----|
|
|
211
|
+
| `cache-provider.ts` | ~30% | 80% | Keys iteration, error handling |
|
|
212
|
+
| `redis-cache-invalidate.manager.ts` | ~20% | 80% | Connection errors, retry, close |
|
|
213
|
+
| `redis-pattern-invalidation.ts` | ~60% | 80% | Edge cases, batching |
|
|
214
|
+
| `cacheable.provider.ts` | ~50% | 80% | Strategy creation, error paths |
|
|
215
|
+
| `cache.interceptor.ts` | ~40% | 80% | I18n, error handling |
|
|
216
|
+
| `cache-invalidate.interceptor.ts` | ~30% | 80% | Pattern matching, errors |
|
|
217
|
+
| `cache.module.ts` | ~50% | 80% | Async config, shutdown |
|
|
218
|
+
|
|
219
|
+
### Tests Needed
|
|
220
|
+
|
|
221
|
+
1. **CacheProvider.keys()** - Test iteration behavior
|
|
222
|
+
2. **RedisCacheInvalidateManager** - Connection failure, reconnection, close
|
|
223
|
+
3. **CacheInterceptor** - I18n locale handling, StreamableFile handling
|
|
224
|
+
4. **Module Lifecycle** - onModuleInit, onApplicationShutdown
|
|
225
|
+
5. **Error Paths** - All catch blocks need test coverage
|
|
226
|
+
|
|
227
|
+
---
|
|
228
|
+
|
|
229
|
+
## 🔵 Enhancement Opportunities
|
|
230
|
+
|
|
231
|
+
### E1. Add Health Check Interface
|
|
232
|
+
|
|
233
|
+
```typescript
|
|
234
|
+
export interface CacheHealthCheck {
|
|
235
|
+
isHealthy(): Promise<{
|
|
236
|
+
healthy: boolean;
|
|
237
|
+
latencyMs: number;
|
|
238
|
+
connections: Array<{
|
|
239
|
+
name: string;
|
|
240
|
+
status: 'connected' | 'disconnected' | 'error';
|
|
241
|
+
error?: string;
|
|
242
|
+
}>;
|
|
243
|
+
}>;
|
|
244
|
+
}
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
### E2. Add Metrics/Observability Hooks
|
|
248
|
+
|
|
249
|
+
```typescript
|
|
250
|
+
export interface CacheMetrics {
|
|
251
|
+
onCacheHit(key: string, source: 'memory' | 'distributed'): void;
|
|
252
|
+
onCacheMiss(key: string): void;
|
|
253
|
+
onCacheSet(key: string, ttlMs: number): void;
|
|
254
|
+
onCacheDelete(key: string): void;
|
|
255
|
+
onCacheError(operation: string, error: Error): void;
|
|
256
|
+
}
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
### E3. Add Bulk Operations for Legacy Mode
|
|
260
|
+
|
|
261
|
+
```typescript
|
|
262
|
+
// Currently only enhanced mode has efficient mget/mset
|
|
263
|
+
async mget(keys: string[]): Promise<unknown[]>
|
|
264
|
+
async mset(list: Array<{ key: CacheKey; value: any; ttl?: number }>): Promise<void>
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### E4. Add Cache Warming/Preloading
|
|
268
|
+
|
|
269
|
+
```typescript
|
|
270
|
+
export interface CacheWarmer {
|
|
271
|
+
warmUp(keys: Array<{ key: string; loader: () => Promise<any>; ttl: number }>): Promise<void>;
|
|
272
|
+
}
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
### E5. Add TTL Extension/Touch
|
|
276
|
+
|
|
277
|
+
```typescript
|
|
278
|
+
async touch(key: CacheKey, newTtl?: number): Promise<boolean>;
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
### E6. Add Namespace Support
|
|
282
|
+
|
|
283
|
+
```typescript
|
|
284
|
+
// Group related cache keys under a namespace
|
|
285
|
+
const userCache = cacheManager.namespace('user');
|
|
286
|
+
await userCache.get('123'); // Key becomes: user:123
|
|
287
|
+
await userCache.invalidateAll(); // Invalidates user:*
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
### E7. Add Graceful Degradation
|
|
291
|
+
|
|
292
|
+
```typescript
|
|
293
|
+
// Continue operating when Redis is down (fall back to memory-only)
|
|
294
|
+
{
|
|
295
|
+
strategy: CacheStrategy.MULTI_TIER,
|
|
296
|
+
fallbackToMemory: true, // New option
|
|
297
|
+
}
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
### E8. Add Cache Compression
|
|
301
|
+
|
|
302
|
+
```typescript
|
|
303
|
+
{
|
|
304
|
+
compression: {
|
|
305
|
+
enabled: true,
|
|
306
|
+
threshold: 1024, // Compress values > 1KB
|
|
307
|
+
algorithm: 'gzip' | 'lz4' | 'snappy',
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
---
|
|
313
|
+
|
|
314
|
+
## 📋 Implementation Priority
|
|
315
|
+
|
|
316
|
+
### Phase 1: Critical Fixes (P0) - Must Fix
|
|
317
|
+
1. Fix Jest coverage configuration
|
|
318
|
+
2. Fix memory leak in `warnedFeatures`
|
|
319
|
+
3. Fix `RedisPatternInvalidation` instance creation
|
|
320
|
+
4. Add proper cleanup in `close()` methods
|
|
321
|
+
|
|
322
|
+
### Phase 2: Security Hardening (P1)
|
|
323
|
+
1. Add message validation in Redis subscriber
|
|
324
|
+
2. Sanitize cache keys
|
|
325
|
+
3. Protected key check for pattern invalidation
|
|
326
|
+
4. Secure logging (mask passwords)
|
|
327
|
+
|
|
328
|
+
### Phase 3: Test Coverage (P2)
|
|
329
|
+
1. Unit tests for uncovered code paths
|
|
330
|
+
2. Integration tests for Redis operations
|
|
331
|
+
3. E2E tests for module lifecycle
|
|
332
|
+
4. Error handling tests
|
|
333
|
+
|
|
334
|
+
### Phase 4: Enhancements (P3)
|
|
335
|
+
1. Health check interface
|
|
336
|
+
2. Metrics hooks
|
|
337
|
+
3. Namespace support
|
|
338
|
+
4. Graceful degradation
|
|
339
|
+
|
|
340
|
+
---
|
|
341
|
+
|
|
342
|
+
## ⚠️ Legacy Mode Preservation
|
|
343
|
+
|
|
344
|
+
All changes MUST maintain backward compatibility with legacy mode:
|
|
345
|
+
|
|
346
|
+
1. **No Breaking Changes**: All existing APIs must continue to work
|
|
347
|
+
2. **Default Behavior**: `strategy: LEGACY` must remain the default
|
|
348
|
+
3. **Feature Detection**: Use `isEnhancedMode()` to guard enhanced-only features
|
|
349
|
+
4. **Deprecation Warnings**: Warn but don't fail on deprecated options
|
|
350
|
+
5. **Fallback Paths**: Enhanced features should gracefully degrade in legacy mode
|
|
351
|
+
|
|
352
|
+
---
|
|
353
|
+
|
|
354
|
+
## Next Steps
|
|
355
|
+
|
|
356
|
+
See `IMPLEMENTATION_PLAN.md` for detailed task breakdown with code examples.
|