Claude skill async race condition security — SA-SKL-ASYNCRACE
MCP skills that handle billing, job creation, session management, and event-driven audit writes expose four async race conditions that go beyond the Redis rate-limit races covered in SA-SKL-RATELIMIT. ASYNCRACE-001 covers the classic TOCTOU credit-budget race where two parallel tool calls both pass the balance check then both deduct, sending credits negative. ASYNCRACE-002 covers non-idempotent audit job creation that double-charges users. ASYNCRACE-003 covers the session invalidation lag window in Redis-cached auth. ASYNCRACE-004 covers concurrent webhook and manual audit result writes that corrupt the audit record via last-write-wins. Each pattern requires a different atomic primitive: SQL check-and-update, DB unique constraint, session versioning, and advisory locking.
Why async races are a distinct risk category for MCP skills
MCP tools execute asynchronously. Claude may call the same tool concurrently for efficiency, or a user may open multiple browser tabs triggering parallel API calls. GitHub webhooks fire independently of user-initiated audits. Session invalidation in one request does not synchronously invalidate all in-flight requests that have already passed auth middleware. These are not edge cases — they are normal operating conditions for any skill with more than a few active users, and they expose business logic that was written assuming sequential execution.
SA-SKL-ASYNCRACE in scope: ASYNCRACE-001 (credit budget TOCTOU), ASYNCRACE-002 (double-spend on audit job creation), ASYNCRACE-003 (session token reuse window after logout), ASYNCRACE-004 (concurrent webhook/manual audit result write race). Each pattern includes SkillAudit detection rules and atomic SQL or Redis fixes.
ASYNCRACE-001 — Check-then-act race on credit budget
The pattern if (user.creditsRemaining > 0) { await deductCredit(userId) } is a textbook TOCTOU race: two simultaneous requests both execute the check while credits is 1, both see 1 > 0 = true, both proceed to deduct, and credits become -1. The fix is to make the check and the deduction a single atomic operation using a SQL UPDATE ... WHERE credits > 0 RETURNING credits expression. If the returned row count is zero (no row matched the credits > 0 condition), the deduction was rejected atomically — no race possible.
// VULNERABLE: check-then-act — two parallel calls both pass the check
app.post('/api/skill/run_audit', authMiddleware, async (req, res) => {
const user = await db.users.findById(req.user.id);
// VULNERABLE: check and deduction are separate operations
// Two parallel requests both read creditsRemaining=1, both pass check
if (user.creditsRemaining <= 0) {
return res.status(402).json({ error: 'No credits remaining' });
}
// Both deduct — credits goes to -1
await db.users.update({ id: req.user.id, creditsRemaining: user.creditsRemaining - 1 });
const audit = await runAudit(req.body.repoUrl);
return res.json(audit);
});
// FIXED: single atomic SQL UPDATE with conditional WHERE
app.post('/api/skill/run_audit', authMiddleware, async (req, res) => {
// Atomic check-and-deduct: only succeeds if credits > 0 at the moment of deduction
// PostgreSQL: UPDATE ... RETURNING guarantees atomicity via row-level locking
const result = await db.query(
`UPDATE users
SET credits_remaining = credits_remaining - 1
WHERE id = $1 AND credits_remaining > 0
RETURNING credits_remaining`,
[req.user.id]
);
if (result.rows.length === 0) {
// Either no such user, or credits was already 0 — both are 402
return res.status(402).json({ error: 'No credits remaining' });
}
// Credit deducted atomically — proceed with audit
const audit = await runAudit(req.body.repoUrl);
return res.json({ ...audit, creditsRemaining: result.rows[0].credits_remaining });
});
UPDATE ... WHERE credits > 0 RETURNING credits SQL expression; check the returned row count — zero rows means deduction rejected. Detection: SkillAudit flags patterns of the form if (user.X > 0) { update(user.X - 1) } where the check and the update are on separate await expressions with no database transaction wrapping them.ASYNCRACE-002 — Double-spend on audit job creation
When a skill creates an audit job on each API call without an idempotency constraint, two parallel requests for the same repository in the same minute create two separate audit jobs, charge the user twice, and queue two parallel audit runs of the same target. The fix is a database UNIQUE constraint on the natural key (user_id, repo_url, minute_bucket) combined with INSERT ... ON CONFLICT DO NOTHING RETURNING id. If the INSERT returns no rows (conflict), the existing job ID is fetched and returned — the user gets exactly one audit and one charge.
// VULNERABLE: audit job creation without idempotency constraint
app.post('/api/skill/create_audit', authMiddleware, async (req, res) => {
const { repoUrl } = req.body;
// No uniqueness check — two parallel requests both create audit jobs
// Two credits deducted, two jobs queued, user charged twice
const auditJob = await db.auditJobs.create({
userId: req.user.id,
repoUrl,
createdAt: new Date(),
});
await creditService.deduct(req.user.id, 1);
await auditQueue.enqueue(auditJob.id);
return res.json({ jobId: auditJob.id });
});
// FIXED: DB unique constraint + INSERT ... ON CONFLICT DO NOTHING
// Migration: CREATE UNIQUE INDEX uniq_audit_per_minute
// ON audit_jobs(user_id, repo_url, date_trunc('minute', created_at));
app.post('/api/skill/create_audit', authMiddleware, async (req, res) => {
const { repoUrl } = req.body;
const minuteBucket = new Date();
minuteBucket.setSeconds(0, 0); // truncate to minute
// Atomic: insert only if no existing job for this user+repo in this minute
const result = await db.query(
`INSERT INTO audit_jobs (user_id, repo_url, created_at)
VALUES ($1, $2, $3)
ON CONFLICT (user_id, repo_url, date_trunc('minute', created_at))
DO NOTHING
RETURNING id`,
[req.user.id, repoUrl, minuteBucket]
);
if (result.rows.length === 0) {
// Conflict: existing job for this minute — return it
const existing = await db.query(
`SELECT id FROM audit_jobs
WHERE user_id = $1 AND repo_url = $2
AND date_trunc('minute', created_at) = $3`,
[req.user.id, repoUrl, minuteBucket]
);
return res.json({ jobId: existing.rows[0].id, deduplicated: true });
}
// New job created — deduct credit and enqueue
await creditService.deductAtomic(req.user.id); // uses ASYNCRACE-001 pattern
await auditQueue.enqueue(result.rows[0].id);
return res.json({ jobId: result.rows[0].id });
});
UNIQUE constraint on (user_id, repo_url, minute_bucket) + INSERT ... ON CONFLICT DO NOTHING RETURNING id; return existing job ID on conflict without charging. Detection: SkillAudit flags audit or job creation endpoints that call db.create() or INSERT without an ON CONFLICT clause and without a preceding SELECT for deduplication, where the creation includes a billing or credit deduction call.ASYNCRACE-003 — Session token reuse window after logout
When session validation is cached in Redis with a 5-minute TTL for performance, a user who logs out invalidates their session in the database — but all in-flight requests and any new requests made within the 5-minute Redis TTL window continue to pass authentication, because the auth middleware reads from the Redis cache and finds a valid (but now stale) session record. An attacker who obtains a session token (via XSS, network interception, or shoulder surfing) has a 5-minute guaranteed exploitation window after the victim logs out. The fix is to include a session version number in the token; logout increments the version in the database; the Redis cache stores the version; every request validates the version matches the database — not just the token presence.
// VULNERABLE: Redis cache with TTL 5m creates 5-minute exploit window after logout
async function validateSession(token: string): Promise<User | null> {
// Check Redis cache first (TTL = 5 minutes)
const cached = await redis.get(`session:${token}`);
if (cached) {
return JSON.parse(cached); // Returns user even if session was invalidated in DB
}
// Cache miss: check database
const session = await db.sessions.findByToken(token);
if (!session || session.invalidatedAt) return null;
// Cache for 5 minutes — but invalidatedAt may be set before TTL expires
await redis.setex(`session:${token}`, 300, JSON.stringify(session.user));
return session.user;
}
// Logout sets invalidatedAt in DB — but Redis still has valid cached entry for up to 5m
async function logout(token: string) {
await db.sessions.update({ token, invalidatedAt: new Date() });
// Redis cache NOT cleared — attacker can still use the token for 5 minutes
}
// FIXED: session versioning — version bump on logout invalidates cache immediately
// DB schema: sessions table has 'version' integer column (default 1)
// JWT or session token includes the version at time of issue
async function validateSession(token: string): Promise<User | null> {
// Decode token to get userId and version (not signature-verification, just parsing)
const { userId, sessionVersion } = decodeSessionToken(token);
// Check Redis cache: key includes userId (not full token) for atomic invalidation
const cached = await redis.get(`session_version:${userId}`);
const currentVersion = cached ? parseInt(cached) : null;
if (currentVersion !== null && currentVersion !== sessionVersion) {
// Version mismatch: session has been invalidated (logout bumped version)
return null;
}
// Full validation against DB on cache miss
const session = await db.sessions.findValid({ userId, version: sessionVersion });
if (!session) return null;
// Cache the current version for 5 minutes
await redis.setex(`session_version:${userId}`, 300, String(session.version));
return session.user;
}
async function logout(userId: string): Promise<void> {
// Atomically bump version in DB
const { rows } = await db.query(
`UPDATE sessions SET version = version + 1 WHERE user_id = $1 RETURNING version`,
[userId]
);
// Update Redis cache immediately — no waiting for TTL expiry
await redis.setex(`session_version:${userId}`, 300, String(rows[0].version));
}
ASYNCRACE-004 — Concurrent webhook and manual audit result writes corrupt data
When a GitHub push webhook and a user-triggered manual re-audit both attempt to write to the same audit_results row simultaneously, last-write-wins semantics mean one of the writes is silently discarded. If the webhook's result arrives 50ms after the manual audit starts writing, the manual audit's result is overwritten by the webhook result, and the user sees stale (or incomplete) audit data. With more than a few users, this race fires regularly. The fix is a PostgreSQL advisory lock that serializes writes for a given audit job, or an optimistic locking pattern with a version column that forces a retry on conflict.
// VULNERABLE: two concurrent writers to the same audit_results row — last wins
// Webhook handler:
async function handleWebhook(jobId: string, webhookResult: AuditResult) {
await db.query(
`UPDATE audit_results SET result = $1, updated_at = NOW() WHERE job_id = $2`,
[JSON.stringify(webhookResult), jobId]
);
}
// Manual re-audit handler (concurrent with webhook):
async function saveManualAudit(jobId: string, manualResult: AuditResult) {
await db.query(
`UPDATE audit_results SET result = $1, updated_at = NOW() WHERE job_id = $2`,
[JSON.stringify(manualResult), jobId]
);
}
// Race: webhook writes at T+50ms, manual writes at T+100ms → manual wins (last write)
// But if webhook writes at T+100ms, manual writes at T+50ms → webhook wins
// Either way, one result is silently discarded
// FIXED option A: PostgreSQL advisory lock serializes writes for a given job
async function saveAuditResult(jobId: string, result: AuditResult) {
// Advisory lock key: hash jobId to a bigint
// pg_advisory_xact_lock holds for the duration of the transaction
const lockKey = hashToBigInt(jobId);
await db.query('BEGIN');
try {
// Acquire advisory lock — blocks until any other transaction releases it
await db.query('SELECT pg_advisory_xact_lock($1)', [lockKey]);
await db.query(
`UPDATE audit_results SET result = $1, updated_at = NOW() WHERE job_id = $2`,
[JSON.stringify(result), jobId]
);
await db.query('COMMIT');
} catch (err) {
await db.query('ROLLBACK');
throw err;
}
}
// FIXED option B: optimistic locking with version column
// Schema: audit_results has 'version' integer column
async function saveAuditResultOptimistic(
jobId: string, result: AuditResult, expectedVersion: number
): Promise<boolean> {
const { rowCount } = await db.query(
`UPDATE audit_results
SET result = $1, updated_at = NOW(), version = version + 1
WHERE job_id = $2 AND version = $3`, // only updates if version matches
[JSON.stringify(result), jobId, expectedVersion]
);
return rowCount === 1; // false = conflict — caller should retry with fresh version
}
pg_advisory_xact_lock) per job ID to serialize writes, OR optimistic locking with a version column + UPDATE WHERE version = expected and retry on conflict. Detection: SkillAudit flags UPDATE operations on shared result tables where the same row can be targeted by both webhook-triggered and user-triggered code paths without a transaction-level locking mechanism.