Claude skill memory cache security — SA-SKL-MEMCACHE
In-process LRU and memoization caches in MCP skills create four distinct security problems: cross-user data leakage when the cache key is too coarse, indefinite retention of sensitive secrets, cache key manipulation that injects attacker-controlled data into the cache, and stampede conditions that collapse the upstream database under concurrent load. SA-SKL-MEMCACHE-001 through MEMCACHE-004 cover each of these patterns with concrete Node.js examples.
Why in-process caches are a security concern for MCP skills
MCP skills frequently add an in-process LRU or memoization cache to speed up responses to Claude — caching tool call results, audit report JSON, or upstream API responses to avoid redundant network round-trips. When that cache lives as a module-level singleton, it is shared across every concurrent request handled by the same Node.js process. A cache key that does not include the requesting user's identity will serve one user's data to another. When the cached payload contains secrets — API keys, session tokens, OAuth credentials — a cache without a time-to-live keeps those secrets in process memory far longer than necessary. When the cache key is constructed from unvalidated user input, an attacker can craft a key that collides with or overwrites another user's entry. And when there is no coalescing of concurrent cache misses, a cold process under load will fire hundreds of simultaneous upstream queries and bring the backing database to its knees.
SA-SKL-MEMCACHE in scope: MEMCACHE-001 (shared singleton cache leaks responses across users), MEMCACHE-002 (sensitive data cached without TTL), MEMCACHE-003 (cache poisoning via unvalidated key construction), MEMCACHE-004 (cache stampede on cold start). All four are detected by SkillAudit's static analysis of cache instantiation patterns, key construction expressions, and cache-miss handler concurrency guards.
MEMCACHE-001 — Shared singleton cache leaks responses across users
When a module-level LRUCache instance is created once at startup and reused across all requests, the cache key determines the blast radius of a data leak. A key built only from the route path — /audits/42 — does not encode which user is requesting the resource. The first user to load audit 42 populates the cache; every subsequent user who requests the same path receives that cached response, regardless of whether they own the audit or even have permission to view it. The fix for authenticated user-specific resources is to include the user identity in the key, or better, to avoid caching authenticated responses entirely and restrict the cache to genuinely public, non-sensitive resources.
// VULNERABLE: module-level singleton cache with path-only key
const { LRUCache } = require('lru-cache');
const cache = new LRUCache({ max: 100 }); // shared across ALL requests
app.get('/audits/:id', requireAuth, async (req, res) => {
const cacheKey = req.path; // "/audits/42" — no user identity
if (cache.has(cacheKey)) {
// User B receives User A's audit report here
return res.json(cache.get(cacheKey));
}
const audit = await db.audits.findById(req.params.id);
if (!audit) return res.status(404).end();
cache.set(cacheKey, audit); // stores User A's data under "/audits/42"
res.json(audit);
});
// FIXED: include user identity in key; only cache public resources
const { LRUCache } = require('lru-cache');
// Cache only genuinely public, non-personalised resources
const publicCache = new LRUCache({ max: 200, ttl: 60_000 });
// For authenticated user-specific resources: skip the cache entirely
app.get('/audits/:id', requireAuth, async (req, res) => {
// No cache — always fetch from DB, enforcing row-level ownership check
const audit = await db.audits.findOne({
id: req.params.id,
ownerId: req.session.userId, // ownership enforced at DB query level
});
if (!audit) return res.status(404).end();
res.json(audit);
});
// Public summary endpoint — safe to cache with explicit cache key
app.get('/public/audits/:id/summary', async (req, res) => {
const cacheKey = `public:summary:${req.params.id}`;
if (publicCache.has(cacheKey)) return res.json(publicCache.get(cacheKey));
const summary = await db.audits.getPublicSummary(req.params.id);
if (!summary) return res.status(404).end();
publicCache.set(cacheKey, summary);
res.json(summary);
});
LRUCache instance shared across all requests and builds cache keys from the route path alone without including the requesting user's identity; authenticated user-specific responses are served from cache to any user who requests the same path, leaking data across authentication boundaries. Fix: never cache authenticated user-specific responses; restrict caching to genuinely public resources; when caching is necessary include req.session.userId or equivalent in every cache key.MEMCACHE-002 — Sensitive data cached without TTL
An LRU cache configured without a ttl (time-to-live) evicts entries only under memory pressure — when the cache is full and a new entry must displace the least-recently-used item. For a skill that handles moderate traffic, entries can survive in process memory for hours. When those entries contain API keys, session tokens, or OAuth credentials that were returned as part of a larger response payload, the secret lives in the heap for the same duration. A heap dump, process crash file, or memory-inspection attack can then extract the credential long after the HTTP session that produced it has ended. The fix is to never include secrets in cached values, and to apply a short TTL (60 seconds or less) on any cache that might receive sensitive metadata.
// VULNERABLE: LRUCache with no TTL caches payload containing API key
const { LRUCache } = require('lru-cache');
// No ttl option — entries live until LRU eviction (potentially hours)
const cache = new LRUCache({ max: 500 });
async function getIntegrationConfig(userId) {
const key = `integration:${userId}`;
if (cache.has(key)) return cache.get(key);
const config = await db.integrations.findByUser(userId);
// config = { apiKey: 'sk-live-...', webhookSecret: '...', endpoint: '...' }
cache.set(key, { apiKey: config.apiKey, ...config }); // ← secret in cache
return config;
}
// FIXED: separate sensitive from cacheable data; apply short TTL
const { LRUCache } = require('lru-cache');
// 60-second TTL — cached entries expire quickly
const cache = new LRUCache({ max: 500, ttl: 60_000 });
async function getIntegrationConfig(userId) {
const key = `integration:${userId}`;
// Cache only the non-sensitive portion
if (cache.has(key)) {
const cached = cache.get(key); // { endpoint, webhookCallbackUrl }
// Re-fetch the secret fresh on every call — never cache it
const { apiKey } = await db.integrations.getSecretOnly(userId);
return { ...cached, apiKey };
}
const config = await db.integrations.findByUser(userId);
// Store ONLY the non-sensitive fields in cache
cache.set(key, { endpoint: config.endpoint,
webhookCallbackUrl: config.webhookCallbackUrl });
return config; // apiKey returned to caller but NOT stored in cache
}
ttl configured; sensitive secrets remain in process heap memory until LRU eviction under memory pressure, which may be hours after the originating session ends, exposing credentials to heap-dump or memory-inspection attacks. Fix: never include API keys or session tokens in cached values; separate public cacheable fields from sensitive fields at the data model level; configure a short ttl (60 seconds) on all caches that handle even non-secret authenticated data.MEMCACHE-003 — Cache poisoning via unvalidated key construction
When a cache key is built by concatenating the route path with a user-supplied query parameter — such as ?format=json — without validating that parameter against an explicit allowlist, the attacker controls part of the key string. A crafted value such as ?format=../../admin/secret or ?format=:adminUserId:path can produce a key that matches another user's cache entry, causing the attacker's response to overwrite the legitimate cached value (cache poisoning), or causing the attacker to read a value they should not have access to (cache oracle). The fix is to validate the format parameter against an explicit allowlist Set before it is used in any cache key construction.
// VULNERABLE: cache key includes unvalidated user-supplied format param
app.get('/reports/:id', requireAuth, async (req, res) => {
// req.query.format is fully attacker-controlled
const cacheKey = `${req.path}:${req.query.format}`;
// Attacker sends ?format=../../admin/secret
// → cacheKey = "/reports/42:../../admin/secret"
// Attacker sends ?format=:otherUserId:/reports/99
// → cacheKey collides with another user's entry
if (cache.has(cacheKey)) return res.json(cache.get(cacheKey));
const report = await generateReport(req.params.id, req.query.format);
cache.set(cacheKey, report); // poisons cache with attacker-chosen key
res.json(report);
});
// FIXED: validate format against explicit allowlist before key construction
const ALLOWED_FORMATS = new Set(['json', 'csv', 'pdf']);
app.get('/reports/:id', requireAuth, async (req, res) => {
const rawFormat = req.query.format;
// Reject any format value not in the allowlist
if (rawFormat !== undefined && !ALLOWED_FORMATS.has(rawFormat)) {
return res.status(400).json({ error: 'Invalid format parameter' });
}
// Use a safe default if format is omitted
const format = ALLOWED_FORMATS.has(rawFormat) ? rawFormat : 'json';
// Cache key uses only validated, allowlisted values — no path traversal
const cacheKey = `report:${req.session.userId}:${req.params.id}:${format}`;
if (cache.has(cacheKey)) return res.json(cache.get(cacheKey));
const report = await generateReport(req.params.id, format);
cache.set(cacheKey, report);
res.json(report);
});
req.query.format); an attacker can craft a parameter value that collides with another user's cache entry to read their cached response (cache oracle) or overwrite it with attacker-controlled data (cache poisoning). Fix: validate every query parameter used in cache key construction against an explicit allowlist Set before use; reject requests with parameter values outside the allowlist with 400 Bad Request.MEMCACHE-004 — Cache stampede on cold start floods database
When a process starts cold — or when a popular cache entry expires — multiple concurrent requests will all miss the cache simultaneously and each independently fire a database query to repopulate it. Under high concurrency this stampede can produce tens or hundreds of simultaneous queries for the same resource, overloading the backing database before any single query has had a chance to respond and repopulate the cache. The standard fix is a single-flight or promise-coalescing pattern: when the first request misses the cache it stores an in-flight Promise in the cache map rather than the resolved value; all subsequent requests that arrive before the first resolves find that Promise and await the same result rather than issuing their own queries.
// VULNERABLE: no coalescing — 50 concurrent misses fire 50 DB queries
const { LRUCache } = require('lru-cache');
const cache = new LRUCache({ max: 100, ttl: 300_000 });
async function getAuditReport(auditId) {
if (cache.has(auditId)) return cache.get(auditId);
// 50 concurrent requests all reach here simultaneously on cold start
// All 50 call db.reports.fetch(auditId) at the same time
const report = await db.reports.fetch(auditId); // ← stampede
cache.set(auditId, report);
return report;
}
// FIXED: promise coalescing — first miss stores the Promise; others await it
const { LRUCache } = require('lru-cache');
// Separate caches: one for resolved values, one for in-flight Promises
const resolved = new LRUCache({ max: 100, ttl: 300_000 });
const inFlight = new Map(); // keyed by auditId, value = Promise
async function getAuditReport(auditId) {
// 1. Resolved value already in cache
if (resolved.has(auditId)) return resolved.get(auditId);
// 2. Another request is already fetching this — coalesce onto it
if (inFlight.has(auditId)) return inFlight.get(auditId);
// 3. First miss: create the fetch Promise and register it
const fetchPromise = db.reports.fetch(auditId).then(report => {
resolved.set(auditId, report); // populate resolved cache
inFlight.delete(auditId); // remove in-flight entry
return report;
}).catch(err => {
inFlight.delete(auditId); // clean up on error so next call retries
throw err;
});
inFlight.set(auditId, fetchPromise); // all concurrent misses coalesce here
return fetchPromise; // only one DB query fires
}
// For production, use the 'async-singleflight' npm package rather than a hand-rolled Map
Promise in the cache on the first miss, so all concurrent requests for the same key await the same single database query rather than each issuing their own.SkillAudit detection summary — SA-SKL-MEMCACHE
| Finding | Severity | Root Cause | Fix |
|---|---|---|---|
| MEMCACHE-001 | CRITICAL | Module-level LRUCache singleton; cache key is route path only, omitting user identity — authenticated responses served across user boundaries | Skip cache for authenticated user-specific resources; restrict to public resources; include userId in any key where caching is required |
| MEMCACHE-002 | HIGH | LRUCache configured with no ttl; cached payload includes API keys or session tokens — secrets live in process heap until LRU eviction | Never cache API keys or session tokens; separate sensitive from cacheable fields at the model level; set ttl: 60_000 on all caches touching authenticated data |
| MEMCACHE-003 | HIGH | Cache key built by concatenating route path with unvalidated req.query.format — attacker crafts value to collide with or overwrite another user's cache entry | Validate every query parameter used in key construction against an explicit allowlist Set; reject non-allowlisted values with 400 Bad Request |
| MEMCACHE-004 | MEDIUM | No mutex or Promise coalescing around cache-miss handler — concurrent cold-start misses all fire simultaneous DB queries, overloading the database | Implement promise-coalescing single-flight pattern: store in-flight Promise in a Map on first miss; subsequent concurrent misses await the same Promise |
Related patterns: For cache poisoning attacks that target HTTP reverse-proxy caches rather than in-process LRU caches, see SA-SKL-CACHEPOISON. For secrets exposed in environment variables or logs rather than heap memory, see SA-SKL-SECRETEXPOSE. For rate-limiting gaps that allow an attacker to amplify a stampede through repeated cold requests, see SA-SKL-RATELIMIT.