← Blog

Claude skill race condition security

MCP skills are called concurrently by multiple Claude instances, background jobs, and CI integrations simultaneously. A skill that appears correct in sequential testing can expose critical race conditions under concurrent load: permission checks that pass before resources are consumed, file existence checks exploitable by symlink swap, counters that read-modify-write without atomicity, and budget deductions that allow double-spending under simultaneous calls. SA-SKL-RACE covers four race condition patterns that are particularly common in Node.js MCP skill codebases.

By SkillAudit  |  4 Nov 2026

Race conditions are among the most difficult vulnerability classes to catch in code review because the vulnerable code is individually correct — each line does exactly what it says. The problem is the gap between lines: a check that was valid at line N is no longer valid by the time line N+2 acts on it. In MCP skills the concurrent call model makes these gaps wide. When two Claude instances invoke the same skill tool simultaneously, the Node.js event loop interleaves their await points freely. Any skill that does check-then-act across two separate database queries, two separate file system calls, or two separate arithmetic operations is vulnerable if those operations are not wrapped in an atomic primitive. The fixes are not complex — a single SQL expression, a try/catch that replaces an existence check, an atomic SQL increment — but they require knowing which patterns to look for.

SA-SKL-RACE-001: Check-then-act without atomic operation — permission consumed twice

The most common race condition in MCP skill authorization logic is a two-step check-then-act pattern: first verify that the user has permission or a resource available, then perform the operation that consumes it. When two concurrent calls execute this pattern, both can pass the permission check before either has updated the state that the check reads. The result is that a one-use resource is used twice, a quota that should block is bypassed, or an exclusive operation runs in parallel with itself. The window is as short as a single await point but that is enough for the event loop to interleave a second concurrent call:

// VULNERABLE: check-then-act with no atomicity guarantee
import { db } from './db.js';

async function runAudit(userId: string, resourceId: string): Promise<AuditResult> {
  // Step 1: check permission — returns true if user has >= 1 audit credit
  const allowed = await hasPermission(userId);  // reads credits from DB

  // <-- RACE WINDOW: another concurrent runAudit(userId, resourceId) call
  //     also awaits hasPermission(userId) and also reads credits >= 1
  //     Both calls are now past the check; both will proceed to useResource

  if (!allowed) {
    throw new Error('Insufficient audit credits');
  }

  // Step 2: consume the resource — deducts 1 credit
  return await useResource(resourceId, userId);  // deducts credit in separate query
}

// ATTACK SCENARIO:
// User has exactly 1 audit credit remaining.
// Attacker (or concurrent Claude instance) fires two simultaneous runAudit calls:
//
//   Call A: await hasPermission(userId)  → reads credits=1 → returns true
//   Call B: await hasPermission(userId)  → reads credits=1 → returns true
//   Call A: proceeds to useResource → deducts 1 credit → credits now 0
//   Call B: proceeds to useResource → deducts 1 credit → credits now -1
//
// Both calls succeed. User consumed 2 credits while having only 1.
// Same pattern applies to: exclusive resource locks, one-time-use tokens,
//   rate limit checks, quota gates, feature flags with per-user limits.

// SECURE: atomic conditional update — the check and the deduction are one operation
async function runAuditSafe(userId: string, resourceId: string): Promise<AuditResult> {
  // Single atomic SQL: deduct 1 credit only if credits >= 1
  // The WHERE clause IS the permission check; rowsAffected IS the authorization result
  const result = await db.run(
    'UPDATE user_credits SET credits = credits - 1 WHERE userId = ? AND credits >= 1',
    userId
  );

  if (result.changes === 0) {
    // Either user doesn't exist or credits were already 0
    // No race: if two concurrent calls both attempt this, only one can win
    throw new Error('Insufficient audit credits');
  }

  // We hold a committed deduction — safe to proceed
  return await performAudit(resourceId, userId);
}

// ALTERNATIVE: pessimistic lock via SELECT FOR UPDATE inside a transaction
// Use when the permission check logic is too complex for a WHERE clause
async function runAuditWithLock(userId: string, resourceId: string): Promise<AuditResult> {
  return await db.transaction(async (trx) => {
    // Lock the row for this transaction — concurrent calls block here until we commit
    const user = await trx.get(
      'SELECT credits FROM user_credits WHERE userId = ? FOR UPDATE',
      userId
    );

    if (!user || user.credits < 1) {
      throw new Error('Insufficient audit credits');
    }

    await trx.run(
      'UPDATE user_credits SET credits = credits - 1 WHERE userId = ?',
      userId
    );

    return await performAudit(resourceId, userId);
  });
}

The race window exists even when the gap looks small: A check-then-act race requires only that the event loop yields to another coroutine between the check and the act. In Node.js, every await is a yield point. A skill handler that does await hasPermission() followed by await useResource() has an unconditional yield between them — the event loop will process other callbacks, including other incoming tool call requests, during that gap. The fix is not to reduce the gap but to eliminate it entirely by collapsing check and act into a single atomic database operation.

HIGH
SA-SKL-RACE-001 — Check-then-act without atomic operation: two concurrent skill calls both pass a permission or quota check before either updates the guarding state; both proceed to consume a resource that should only be consumed once. Fix: replace the two-step check-then-act with a single atomic conditional UPDATE ... WHERE condition and check rowsAffected = 1; or use SELECT FOR UPDATE inside a database transaction. Detection: await hasPermission / await checkQuota followed by a separate await use / await deduct without wrapping transaction → HIGH.

SA-SKL-RACE-002: File TOCTOU — existsSync then readFileSync exploitable by symlink swap

Time-of-check to time-of-use (TOCTOU) is the file system manifestation of check-then-act. A skill that checks whether a file exists before reading or writing it has a race window between the two calls. An attacker who can write to the directory containing the target path can swap a legitimate file for a symlink to a sensitive file between the existence check and the read. The existsSync / readFileSync pattern is widespread in MCP skills that serve files from a workspace directory, and it is the root cause of several published directory traversal escalations in file-serving tools:

// VULNERABLE: existsSync check followed by separate readFileSync
import { existsSync, readFileSync, writeFileSync } from 'fs';
import path from 'path';

async function readWorkspaceFile(relativePath: string): Promise<string> {
  const resolvedPath = path.resolve('/workspace', relativePath);

  // Step 1: check existence
  if (!existsSync(resolvedPath)) {
    throw new Error('File not found');
  }

  // <-- RACE WINDOW: attacker replaces resolvedPath with a symlink
  //     e.g. replaces /workspace/report.txt with a symlink to /etc/passwd

  // Step 2: read — follows the symlink silently
  return readFileSync(resolvedPath, 'utf8');  // reads /etc/passwd
}

// ALSO VULNERABLE: existence check before write
async function writeWorkspaceFile(relativePath: string, data: string): Promise<void> {
  const resolvedPath = path.resolve('/workspace', relativePath);

  if (existsSync(resolvedPath)) {
    // "safe" — only write if file already exists (don't create new files)
    // RACE: another process creates a symlink at resolvedPath between check and write
    writeFileSync(resolvedPath, data);  // overwrites symlink target
  }
}

// ATTACK SCENARIO (read):
// 1. Attacker has write access to /workspace/ directory
// 2. Attacker creates /workspace/report.txt (legitimate file — check passes)
// 3. existsSync('/workspace/report.txt') returns true — check passes
// 4. Attacker: unlink('/workspace/report.txt'); symlink('/etc/passwd', '/workspace/report.txt')
// 5. readFileSync('/workspace/report.txt') follows symlink → returns /etc/passwd contents
// Attack succeeds within the microseconds between existsSync and readFileSync

// ATTACK SCENARIO (write):
// 1. Attacker has no /workspace/sensitive.conf initially
// 2. Skill has logic: if /workspace/output.txt exists, overwrite it with new data
// 3. existsSync returns true for attacker-created output.txt
// 4. Attacker: unlink output.txt; symlink('/etc/cron.d/skill-backdoor', 'output.txt')
// 5. writeFileSync overwrites /etc/cron.d/skill-backdoor with attacker-influenced data

// SECURE: eliminate the existence check — let the error be the check
async function readWorkspaceFileSafe(relativePath: string): Promise<string> {
  const resolvedPath = path.resolve('/workspace', relativePath);

  // No existence pre-check — open and read atomically
  // If file doesn't exist, ENOENT is thrown; handle it as "not found"
  try {
    return readFileSync(resolvedPath, 'utf8');
  } catch (err: any) {
    if (err.code === 'ENOENT') throw new Error('File not found');
    throw err;  // re-throw unexpected errors (EACCES, EISDIR, etc.)
  }
}

// SECURE: use O_NOFOLLOW to refuse symlinks entirely
import { openSync, readSync, closeSync, constants } from 'fs';

async function readWorkspaceFileNoFollow(relativePath: string): Promise<string> {
  const resolvedPath = path.resolve('/workspace', relativePath);

  let fd: number;
  try {
    // O_NOFOLLOW: throw ELOOP if resolvedPath is a symlink — refuse to follow
    fd = openSync(resolvedPath, constants.O_RDONLY | constants.O_NOFOLLOW);
  } catch (err: any) {
    if (err.code === 'ENOENT') throw new Error('File not found');
    if (err.code === 'ELOOP') throw new Error('Symlinks are not permitted in workspace paths');
    throw err;
  }

  try {
    const buf = Buffer.alloc(1024 * 1024);  // 1 MB max
    const bytesRead = readSync(fd, buf, 0, buf.length, null);
    return buf.subarray(0, bytesRead).toString('utf8');
  } finally {
    closeSync(fd);
  }
}

Why existsSync is the wrong tool for access control: existsSync is a convenience function that answers the question "did this path exist at this exact instant?" The answer is stale the moment the function returns. For security decisions the correct question is "can I open this path right now under the security constraints I require?" — and the answer to that question is obtained by attempting the open and inspecting the error code. The try/catch pattern is not just cleaner; it is the only race-free way to combine access checking and file opening in a single operation.

HIGH
SA-SKL-RACE-002 — File TOCTOU via existsSync then readFileSync or writeFileSync: attacker swaps target path with a symlink to a sensitive file between the existence check and the file operation; skill reads or overwrites the symlink target. Fix: remove the existsSync pre-check; wrap the file operation in try/catch and handle ENOENT as "not found"; use O_NOFOLLOW flag via openSync to refuse symlinks entirely. Detection: existsSync immediately preceding readFileSync or writeFileSync on the same path → HIGH.

SA-SKL-RACE-003: Increment race condition — read-modify-write without atomicity

Counter-based rate limiting and usage tracking in MCP skills frequently use a read-modify-write pattern: read the current counter value, increment it in application code, write the new value back. When multiple concurrent calls execute this sequence, they all read the same stale value and all write the same incremented result. The effective increment across N concurrent calls is 1, not N. This collapses a rate limit counter: an attacker who fires 10 concurrent requests all increment the same read value and the counter advances by 1 instead of 10, allowing 10× the permitted rate before the limit triggers:

// VULNERABLE: read-modify-write counter increment
import { db } from './db.js';

async function trackAndCheckUsage(userId: string): Promise<void> {
  // Step 1: read current count
  const row = await db.get<{ count: number }>(
    'SELECT count FROM usage WHERE userId = ?',
    userId
  );
  const currentCount = row?.count ?? 0;

  // <-- RACE WINDOW: 10 concurrent calls all read currentCount = 42

  // Step 2: check limit
  if (currentCount >= 100) {
    throw new Error('Rate limit exceeded');
  }

  // Step 3: write count + 1
  await db.run(
    'UPDATE usage SET count = ? WHERE userId = ?',
    currentCount + 1,  // all 10 concurrent calls write 43
    userId
  );
  // After 10 concurrent calls: count = 43 (should be 52)
}

// ATTACK SCENARIO:
// Rate limit: 100 requests per hour per user.
// Attacker fires 100 concurrent requests when count = 0:
//
//   All 100 calls: SELECT count → 0
//   All 100 calls: check 0 < 100 → pass
//   All 100 calls: UPDATE count = 1
//   Final state: count = 1
//
// Attacker has made 100 requests; counter shows 1.
// Attacker repeats: fires another 100 concurrent requests.
// Effective rate limit is now infinity — counter never reaches 100.

// ALSO VULNERABLE: same pattern with Redis get/set (not atomic)
// const count = await redis.get(`rate:${userId}`);
// await redis.set(`rate:${userId}`, parseInt(count ?? '0') + 1);

// SECURE: atomic SQL increment — the entire check-and-increment is one statement
async function trackAndCheckUsageSafe(userId: string): Promise<void> {
  // Insert or increment atomically
  await db.run(
    `INSERT INTO usage (userId, count) VALUES (?, 1)
     ON CONFLICT(userId) DO UPDATE SET count = count + 1`,
    userId
  );

  // Read back the post-increment value to enforce the limit
  const row = await db.get<{ count: number }>(
    'SELECT count FROM usage WHERE userId = ?',
    userId
  );

  if (row && row.count > 100) {
    // Undo the increment — we should not have allowed this call
    await db.run('UPDATE usage SET count = count - 1 WHERE userId = ?', userId);
    throw new Error('Rate limit exceeded');
  }
}

// BETTER: enforce limit inside the atomic update — no compensating transaction needed
async function trackAndCheckUsageBest(userId: string): Promise<void> {
  const result = await db.run(
    `UPDATE usage SET count = count + 1
     WHERE userId = ? AND count < 100`,
    userId
  );

  if (result.changes === 0) {
    throw new Error('Rate limit exceeded');
  }
}

// SECURE with Redis: use INCR (atomic) then check the returned value
async function trackAndCheckUsageRedis(userId: string, redis: Redis): Promise<void> {
  const newCount = await redis.incr(`rate:${userId}`);
  // Set expiry on first increment
  if (newCount === 1) {
    await redis.expire(`rate:${userId}`, 3600);  // 1 hour window
  }
  if (newCount > 100) {
    throw new Error('Rate limit exceeded');
  }
}

Why read-modify-write is the wrong pattern for any shared counter: The count + 1 arithmetic in a SQL UPDATE statement is evaluated by the database engine while it holds the row lock — it is atomic with respect to concurrent writers. The same arithmetic done in application code after a SELECT is not: the value you read is from before you held any lock, and by the time you write it back, other writers may have already updated the row. The rule is simple: never read a counter, increment it in code, and write it back. Always increment it inside the database or cache using an atomic primitive (count = count + 1 in SQL, INCR in Redis).

HIGH
SA-SKL-RACE-003 — Increment race condition via read-modify-write: concurrent calls all read the same stale counter value and all write the same incremented result; effective increment across N concurrent calls is 1 instead of N; rate limit and quota counters are bypassed entirely. Fix: use UPDATE usage SET count = count + 1 WHERE userId = ? atomic SQL increment; use Redis INCR for in-memory counts; never read-increment-write across two separate queries. Detection: SELECT count followed by UPDATE SET count = ? with application-side arithmetic on the same column → HIGH.

SA-SKL-RACE-004: Double-spend via concurrent budget check — balance goes negative

Billing and credit systems in MCP skills commonly implement spending gates as a two-step balance check and deduction: first read the current balance and verify it is sufficient, then subtract the cost. When two requests arrive simultaneously for a cost that individually fits within the balance but together exceeds it, both pass the balance check and both deduct, sending the balance negative. This is the classic double-spend race condition and it maps directly to the concurrent tool call model: a user with $5 of credit making two simultaneous $4 audit requests ends up with a $−3 balance after both calls are charged:

// VULNERABLE: balance check and deduction are two separate queries
import { db } from './db.js';

async function chargeForAudit(userId: string, cost: number): Promise<void> {
  // Step 1: read current balance
  const row = await db.get<{ balance: number }>(
    'SELECT balance FROM budgets WHERE userId = ?',
    userId
  );
  const balance = row?.balance ?? 0;

  // <-- RACE WINDOW: two concurrent $4 charges both read balance = $5

  if (balance < cost) {
    throw new Error('Insufficient credit balance');
  }

  // Step 2: deduct cost
  await db.run(
    'UPDATE budgets SET balance = ? WHERE userId = ?',
    balance - cost,  // both concurrent calls write $5 - $4 = $1
    userId
  );
  // After two concurrent $4 charges: balance = $1 (should be -$3, or first charge blocked)
}

// ATTACK SCENARIO:
// User has $5.00 credit. Two concurrent $4.00 audit requests arrive.
//
//   Call A: SELECT balance → $5.00
//   Call B: SELECT balance → $5.00
//   Call A: check $5.00 >= $4.00 → pass
//   Call B: check $5.00 >= $4.00 → pass
//   Call A: UPDATE balance = $5.00 - $4.00 = $1.00
//   Call B: UPDATE balance = $5.00 - $4.00 = $1.00
//
// Final balance: $1.00 (attacker received $8.00 worth of service for $5.00)
// Or: Call B executes after Call A commits → balance = -$3.00
// In either case the invariant "balance never goes negative" is violated.

// ALSO VULNERABLE: same pattern with coupon/voucher redemption
// if (await isCouponValid(code)) { await markCouponUsed(code); }
// Two concurrent redemptions both pass isCouponValid before either marks used.

// SECURE: atomic conditional deduction — balance check IS the WHERE clause
async function chargeForAuditSafe(userId: string, cost: number): Promise<void> {
  // Single atomic statement: deduct cost only if balance >= cost
  // If balance is insufficient, the WHERE clause fails and changes = 0
  const result = await db.run(
    'UPDATE budgets SET balance = balance - ? WHERE userId = ? AND balance >= ?',
    cost, userId, cost
  );

  if (result.changes === 0) {
    throw new Error('Insufficient credit balance');
  }
  // If two concurrent calls both execute this: one wins (rowsAffected = 1),
  // the other loses (rowsAffected = 0, balance after first deduction is < cost).
}

// ALTERNATIVE: pessimistic lock with SELECT FOR UPDATE inside a transaction
// Use when the charge logic involves multiple tables or complex calculations
async function chargeForAuditWithLock(userId: string, cost: number): Promise<void> {
  await db.transaction(async (trx) => {
    // Lock the budget row — concurrent calls serialize here
    const row = await trx.get<{ balance: number }>(
      'SELECT balance FROM budgets WHERE userId = ? FOR UPDATE',
      userId
    );

    if (!row || row.balance < cost) {
      throw new Error('Insufficient credit balance');
    }

    await trx.run(
      'UPDATE budgets SET balance = balance - ? WHERE userId = ?',
      cost, userId
    );

    // Any additional charge-related inserts go inside the same transaction
    await trx.run(
      'INSERT INTO charge_log (userId, amount, createdAt) VALUES (?, ?, ?)',
      userId, cost, Date.now()
    );
  });
}

// STARTUP CHECK: verify the budgets table has a CHECK constraint
// This is a database-level safety net that rejects the row update entirely
// if balance goes negative, regardless of application logic:
//
// CREATE TABLE budgets (
//   userId TEXT PRIMARY KEY,
//   balance REAL NOT NULL DEFAULT 0,
//   CHECK (balance >= 0)   <-- database enforces the invariant
// );

A database CHECK (balance >= 0) constraint is a safety net, not a fix: A CHECK constraint on the balance column will cause the second concurrent deduction to fail with a constraint violation instead of silently going negative. This is valuable defense-in-depth, but it is not a substitute for the atomic UPDATE ... WHERE balance >= cost fix — a constraint violation surfaces as an unhandled database error rather than a clean "insufficient balance" response. The correct fix is the atomic conditional update; the constraint provides an additional backstop that prevents silent corruption if the application logic is ever bypassed.

HIGH
SA-SKL-RACE-004 — Double-spend via concurrent budget check: two simultaneous skill calls both read the same balance, both pass the balance ≥ cost check, and both deduct the cost; balance goes negative; user receives service beyond their credit limit. Fix: replace the two-step check-and-deduct with UPDATE budgets SET balance = balance - ? WHERE userId = ? AND balance >= ? and check rowsAffected = 1; or use SELECT FOR UPDATE inside a transaction; add a database CHECK (balance >= 0) constraint as a safety net. Detection: SELECT balance followed by a separate UPDATE SET balance = ? using application-computed value → HIGH.

Remediation summary

FindingSeverityFix
RACE-001: Check-then-act without atomic operationHIGHReplace two-step check-then-act with a single atomic UPDATE ... WHERE condition; check rowsAffected = 1; or use SELECT FOR UPDATE inside a transaction for complex checks
RACE-002: File TOCTOU — existsSync then readFileSyncHIGHRemove the existsSync pre-check; wrap the file operation in try/catch and handle ENOENT as "not found"; use O_NOFOLLOW flag to refuse symlinks entirely
RACE-003: Increment race — read-modify-write counterHIGHUse atomic SQL UPDATE SET count = count + 1; never read a counter, increment in code, and write back; use Redis INCR for in-memory counters
RACE-004: Double-spend via concurrent budget checkHIGHUse UPDATE budgets SET balance = balance - ? WHERE userId = ? AND balance >= ?; check rowsAffected = 1; add database CHECK (balance >= 0) constraint as a safety net

SkillAudit detects all four SA-SKL-RACE-001 through RACE-004 patterns through static analysis of skill source code and database query patterns: check-then-act sequences across separate await calls, existsSync preceding file operations on the same path, read-modify-write counter patterns, and two-step balance check and deduction queries. For related security patterns see SA-SKL-SESS session management security, SA-SKL-ERR error handling security, and SA-SKL-LOG logging security. See the complete SA-SKL attack surface reference for the full vulnerability taxonomy.

Scan your Claude skill for race condition vulnerabilities

SkillAudit detects check-then-act races, file TOCTOU patterns, increment race conditions, and double-spend vulnerabilities across the full SA-SKL-RACE family in 60 seconds.

Get your free audit