Claude skill memory cache security — SA-SKL-MEMCACHE
Caching is the most effective performance optimization available to MCP skills — and one of the most reliable ways to introduce cross-user data leakage or stale authorization bugs. MEMCACHE-001 covers the classic cache-key scoping failure: a private audit result cached by repoUrl alone is served to any user who queries the same URL. MEMCACHE-002 covers plan-tier permission caching that survives subscription downgrade. MEMCACHE-003 covers the counter-intuitive problem of caching negative results (404s) for permission-sensitive resources. MEMCACHE-004 covers the cold-cache population race where two parallel cache misses both execute the expensive database query and the second write silently overwrites the first.
Why caching is a security boundary in MCP skills
Cache keys define the data isolation boundary. If the key does not include every dimension of the authorization context (user ID, plan tier, permission scope), the cache collapses security boundaries that the database enforces correctly. The database query runs authorization checks on every call; the cache does not. Any data served from cache bypasses the authorization path entirely — which is exactly what cache designers intend for performance. The security requirement is that the cache key be as specific as the authorization context requires.
SA-SKL-MEMCACHE in scope: MEMCACHE-001 (response cache without user-scoping), MEMCACHE-002 (permission tier cached past revocation), MEMCACHE-003 (negative 404 cache cross-user), MEMCACHE-004 (cold-cache population race). Each includes SkillAudit detection rules and cache-key or single-flight fixes.
MEMCACHE-001 — User response cached without user-scoping
When a skill caches audit results using only the repository URL as the cache key, the first user to audit a private repository populates the cache with their authenticated result. The second user to query the same URL receives the first user's private audit data — without any authorization check — because the cache hit bypasses the database query that enforces per-user access control. This is especially severe for private GitHub repos where the audit report contains code snippets, vulnerability details, and dependency graphs that the second user has no authorization to see.
// VULNERABLE: cache key is repoUrl only — first user's result served to all subsequent users
const redisCache = require('./redis');
async function getAuditResult(userId: string, repoUrl: string) {
// VULNERABLE: cache key does not include userId
const cacheKey = `audit:${repoUrl}`;
const cached = await redisCache.get(cacheKey);
if (cached) {
// Returns user A's private result to user B — no auth check on cache hit
return JSON.parse(cached);
}
// DB query enforces per-user access control — but only on cache miss
const result = await db.query(
`SELECT r.* FROM audit_results r
JOIN audit_jobs j ON r.job_id = j.id
WHERE j.repo_url = $1 AND j.user_id = $2`,
[repoUrl, userId]
);
if (result.rows.length > 0) {
// Caches user A's result under a key that any user can hit
await redisCache.setex(cacheKey, 3600, JSON.stringify(result.rows[0]));
}
return result.rows[0] || null;
}
// FIXED: cache key includes userId — each user gets their own cache entry
async function getAuditResult(userId: string, repoUrl: string) {
// Cache key scoped to (userId, repoUrl) — user B's cache miss never hits user A's data
const cacheKey = `audit:${userId}:${repoUrl}`;
const cached = await redisCache.get(cacheKey);
if (cached) return JSON.parse(cached);
const result = await db.query(
`SELECT r.* FROM audit_results r
JOIN audit_jobs j ON r.job_id = j.id
WHERE j.repo_url = $1 AND j.user_id = $2`,
[repoUrl, userId]
);
if (result.rows.length > 0) {
await redisCache.setex(cacheKey, 3600, JSON.stringify(result.rows[0]));
}
return result.rows[0] || null;
}
userId (and any other authorization scope) as a component of the cache key: cacheKey = \`resource:${userId}:${resourceId}\`. Detection: SkillAudit flags cache SET calls where the key is derived solely from request parameters (URL, query string) without incorporating the authenticated user identity from req.user.id or the session.MEMCACHE-002 — Permission check cached past revocation
When a skill caches the result of a plan-tier permission check (e.g., "does this user have Team access?"), an admin who downgrades a user's subscription from Team to Free finds that the user continues to access Team-tier features for the duration of the cache TTL. If the TTL is 1 hour, the downgraded user has 1 free hour of elevated access after their subscription ends. The same failure applies in reverse for security: if a user is suspended or their account is flagged for abuse, the cached permission check continues to allow their requests until the TTL expires. The fix is to include the plan tier in the cache key so that a plan change forces a cache miss, or to use a short TTL (60 seconds or less) for security-sensitive permission checks.
// VULNERABLE: plan permission cached by userId only — plan changes don't invalidate cache
async function hasTeamAccess(userId: string): Promise<boolean> {
const cacheKey = `permission:team:${userId}`;
const cached = await redisCache.get(cacheKey);
if (cached !== null) {
return cached === 'true'; // Stale Team=true served after downgrade to Free
}
const user = await db.users.findById(userId);
const hasAccess = user?.plan === 'team' || user?.plan === 'enterprise';
// Cache for 1 hour — plan change in DB won't be reflected for up to 60 minutes
await redisCache.setex(cacheKey, 3600, String(hasAccess));
return hasAccess;
}
// FIXED option A: include plan tier in cache key — plan change → cache miss
async function hasTeamAccess(userId: string): Promise<boolean> {
// Fetch current plan from DB (not from cache — this is the authorization source of truth)
const user = await db.users.findById(userId);
if (!user) return false;
const hasAccess = user.plan === 'team' || user.plan === 'enterprise';
// Cache the result scoped to (userId, plan) — downgrade changes plan → different key → miss
const cacheKey = `permission:team:${userId}:${user.plan}`;
await redisCache.setex(cacheKey, 3600, String(hasAccess));
return hasAccess;
}
// FIXED option B: short TTL for security-sensitive permission checks
async function hasTeamAccess(userId: string): Promise<boolean> {
const cacheKey = `permission:team:${userId}`;
const cached = await redisCache.get(cacheKey);
if (cached !== null) return cached === 'true';
const user = await db.users.findById(userId);
const hasAccess = user?.plan === 'team' || user?.plan === 'enterprise';
// 60 seconds TTL: at most 1 minute of stale permission after plan change
await redisCache.setex(cacheKey, 60, String(hasAccess));
return hasAccess;
}
MEMCACHE-003 — Negative cache for permission-sensitive 404s
Caching 404 responses is a common optimization: if a resource doesn't exist, there's no point querying the database again on each repeated request. But for permission-sensitive resources (private audit results, private repo scans), a 404 is not simply "this resource doesn't exist" — it may mean "this resource exists but you don't have permission to see it." If the 404 is cached by resource ID alone, an attacker who probes private repo IDs gets cached 404 responses, but so does the legitimate owner — who now sees a "not found" response served from the attacker's cache population instead of the actual resource. The fix is to never cache permission-sensitive 404 responses, or to scope 404 caches to the user ID.
// VULNERABLE: 404 cached by resourceId — attacker probe poisons cache for legitimate owner
async function getAuditResult(userId: string, jobId: string) {
const cacheKey = `audit_result:${jobId}`;
const cached = await redisCache.get(cacheKey);
if (cached !== null) {
if (cached === 'NOT_FOUND') return null; // Stale 404 from attacker probe
return JSON.parse(cached);
}
const result = await db.query(
`SELECT * FROM audit_results WHERE job_id = $1 AND user_id = $2`,
[jobId, userId]
);
if (result.rows.length === 0) {
// VULNERABLE: caches NOT_FOUND by jobId alone
// If attacker probes first, legitimate owner gets 404 from cache
await redisCache.setex(cacheKey, 300, 'NOT_FOUND');
return null;
}
await redisCache.setex(cacheKey, 3600, JSON.stringify(result.rows[0]));
return result.rows[0];
}
// FIXED: scope 404 cache to (userId, jobId) — attacker probe doesn't affect other users
async function getAuditResult(userId: string, jobId: string) {
// Both hit and miss keys are scoped to userId
const cacheKey = `audit_result:${userId}:${jobId}`;
const cached = await redisCache.get(cacheKey);
if (cached !== null) {
if (cached === 'NOT_FOUND') return null;
return JSON.parse(cached);
}
const result = await db.query(
`SELECT * FROM audit_results WHERE job_id = $1 AND user_id = $2`,
[jobId, userId]
);
if (result.rows.length === 0) {
// 404 scoped to this user — attacker's probe only poisons their own cache entry
// Short TTL for negative cache: resource may become accessible after permission grant
await redisCache.setex(cacheKey, 60, 'NOT_FOUND');
return null;
}
await redisCache.setex(cacheKey, 3600, JSON.stringify(result.rows[0]));
return result.rows[0];
}
(userId, resourceId) and use a short TTL (60 seconds) so permission grants take effect quickly. Detection: SkillAudit flags cache SET calls that store a negative/NOT_FOUND sentinel where the key does not include the authenticated user identity.MEMCACHE-004 — Race on cold cache population
When a Redis key expires or a new resource is created, the first request misses the cache and starts a potentially expensive database query. If two requests arrive simultaneously on a cold cache, both miss the cache check at the same time (before either has populated it), both execute the expensive query, and both attempt to write the result. The second write silently overwrites the first. For simple read queries this is harmless (both results should be identical), but for queries that have side effects — audit job queuing, analytics increment, rate-limit counter update — the double execution causes data integrity problems. The fix is single-flight (promise deduplication): coalesce parallel cache-miss requests into one database call and fan out the result to all waiters.
// VULNERABLE: parallel cache misses both execute the DB query
// For expensive or side-effectful queries, this causes double execution
async function getOrFetchAuditSummary(repoUrl: string) {
const cacheKey = `audit_summary:${repoUrl}`;
const cached = await redisCache.get(cacheKey);
if (cached) return JSON.parse(cached);
// VULNERABLE: two parallel calls both reach here on cold cache
// Both execute the expensive aggregation query
// For side-effectful queries (e.g., incrementing scan counters), both side effects fire
const summary = await db.query(
`SELECT repo_url, COUNT(*) AS scan_count, MAX(score) AS best_score
FROM audit_jobs WHERE repo_url = $1`,
[repoUrl]
);
await redisCache.setex(cacheKey, 300, JSON.stringify(summary.rows[0]));
return summary.rows[0];
}
// FIXED: single-flight (promise deduplication) prevents parallel DB queries on cold cache
const inFlight = new Map<string, Promise<any>>();
async function getOrFetchAuditSummary(repoUrl: string) {
const cacheKey = `audit_summary:${repoUrl}`;
const cached = await redisCache.get(cacheKey);
if (cached) return JSON.parse(cached);
// Check if another request is already fetching this key
if (inFlight.has(cacheKey)) {
// Wait for the in-flight request — reuse its result, no second DB query
return inFlight.get(cacheKey);
}
// Start the DB query and register the promise so parallel requests can coalesce
const fetchPromise = db.query(
`SELECT repo_url, COUNT(*) AS scan_count, MAX(score) AS best_score
FROM audit_jobs WHERE repo_url = $1`,
[repoUrl]
).then(async (result) => {
await redisCache.setex(cacheKey, 300, JSON.stringify(result.rows[0]));
inFlight.delete(cacheKey);
return result.rows[0];
}).catch((err) => {
inFlight.delete(cacheKey);
throw err;
});
inFlight.set(cacheKey, fetchPromise);
return fetchPromise;
}
// For production, use the 'async-singleflight' npm package rather than a hand-rolled Map
async-singleflight npm package for production. Detection: SkillAudit flags async cache-miss handlers where no in-flight deduplication guard exists and the query has side effects (INSERT, UPDATE, or external API calls).SkillAudit detection summary — SA-SKL-MEMCACHE
| Pattern ID | Severity | What SkillAudit flags | Fix |
|---|---|---|---|
| MEMCACHE-001 | HIGH | Cache SET for user data where key omits userId | Cache key: resource:${userId}:${id} |
| MEMCACHE-002 | HIGH | Permission check cached with TTL ≥300s and key omits plan tier | Include plan in key; or TTL ≤60s |
| MEMCACHE-003 | MEDIUM | NOT_FOUND sentinel cached by resource ID without user scope | Scope negative cache to (userId, resourceId) |
| MEMCACHE-004 | MEDIUM | Cache miss handler has no in-flight deduplication for side-effectful queries | Single-flight promise deduplication |
Related patterns: For async race conditions in business logic beyond caching, see SA-SKL-ASYNCRACE. For session auth caching that creates a logout exploit window, see SA-SKL-ASYNCRACE-003. For memory state leakage between MCP tool calls, see SA-SKL-MEMSTATE.