← Blog

Race Conditions and TOCTOU Vulnerabilities in MCP Skill File Operations and State Mutation

Time-of-check to time-of-use bugs are among the hardest vulnerabilities to spot in MCP skill code — the check succeeds, the action looks safe, but a concurrent request or a filesystem observer exploits the gap between them. This post covers four concrete TOCTOU patterns found in production MCP servers, with wrong and right Node.js code for each.

By SkillAudit  |  7 Nov 2026
CVSS 9.1 — TOCTOU-001 Symlink swap to arbitrary write  |  CVSS 8.1 — TOCTOU-002 Double-spend

Model Context Protocol skills run in environments that are fundamentally concurrent. Multiple LLM sessions may invoke the same skill handler simultaneously, the Node.js event loop interleaves I/O callbacks across requests, and the host filesystem is accessible to other processes running under the same OS user. This combination makes Time-of-Check to Time-of-Use (TOCTOU) vulnerabilities not just a theoretical concern but a practical exploit class that shows up in real MCP server audits.

TOCTOU bugs share a common structure: the code performs a check (does this file exist? does this user have enough credits? is this session still valid?), then trusts the result of that check when performing a subsequent action. Between the check and the action, the world can change. An attacker who controls the timing — by racing a concurrent request, by manipulating the filesystem with inotify listeners, or simply by exploiting the latency of an async database call — can cause the action to execute in a state that the check would have rejected.

The four patterns below are drawn from the TOCTOU rule family tracked by SkillAudit's AST scanner. Each pattern has a vulnerability identifier, a description of the check-action gap, a WRONG code example showing the vulnerable pattern, a RIGHT code example showing the fix, and a prose explanation of why the fix closes the gap.

TOCTOU-001: File Permission Check

fs.access() check then fs.writeFile() action. Attacker swaps file with symlink to /etc/cron.d/backdoor in the gap.

TOCTOU-002: Concurrent Credit Debit

Two concurrent requests both read balance=10, both deduct 5, leaving balance 5 instead of 0. Classic double-spend via non-atomic read-modify-write.

TOCTOU-003: Session Validation Gap

Role check on cached session object; session revoked in DB between check and DB mutation. Revoked admin can still trigger privileged writes.

TOCTOU-004: Tmp File Symlink Swap

Antivirus scans temp file, attacker replaces it with a symlink before the move. Malicious payload lands at final destination with AV-approved status.

Node.js does not protect you: JavaScript's single-threaded event loop eliminates data races on in-memory objects within a single turn of the loop. It does not eliminate TOCTOU races that span async boundaries (await points), database round-trips, or filesystem operations — which is exactly where these vulnerabilities live.

1. TOCTOU-001 — File Permission Check Before Write

The most direct TOCTOU pattern in MCP skill file handling is the check-then-write sequence: call fs.access(filePath, fs.constants.W_OK) to confirm the target is writable, then call fs.writeFile(filePath, data) to write it. The check and the write are two separate syscalls with an await between them. On a Linux system, an attacker who can observe filesystem activity — using inotify_add_watch on the containing directory — can detect the access check and immediately replace the file with a symbolic link pointing to a sensitive target such as /etc/cron.d/backdoor or /root/.ssh/authorized_keys.

The exploit window is small — typically microseconds to low milliseconds — but it is real. Tools like inotify-based filesystem watchers (the same mechanism used by development hot-reload tools) can react in well under a millisecond on a lightly loaded system. Containerised MCP server deployments are particularly at risk because the attacker may control a sibling container sharing the same host filesystem namespace, or the MCP skill itself may process user-supplied filenames that point into shared directories.

Wrong
// TOCTOU-001 WRONG — fs.access() check then fs.writeFile() action
// The gap between the two await points is an exploitable race window.
const fs   = require("fs/promises");
const path = require("path");

async function saveSkillOutput(filePath, data) {
  // CHECK: confirm the path is writable
  try {
    await fs.access(filePath, fs.constants.W_OK);
  } catch {
    throw new Error(`Path is not writable: ${filePath}`);
  }

  // << TOCTOU GAP >>
  // Another process can run here and replace filePath with a symlink
  // to /etc/cron.d/backdoor.  The access() check already passed.

  // ACTION: write the data — now writes to the symlink target
  await fs.writeFile(filePath, data, { encoding: "utf8" });
}

The fs.access() call completes successfully because filePath is writable at that instant. By the time fs.writeFile() executes, an attacker has replaced the file with a symlink. fs.writeFile() follows symlinks by default, so it writes data to /etc/cron.d/backdoor. The process may have the privileges to do so if it runs as root or as a user with write access to system directories — a common configuration in poorly hardened MCP server deployments.

Right
// TOCTOU-001 RIGHT — atomic open with O_CREAT|O_EXCL, or O_WRONLY|O_NOFOLLOW
// No separate access() check; the open() call is both the check and the action.
const fs      = require("fs/promises");
const fsCb    = require("fs");
const path    = require("path");
const O_FLAGS = fsCb.constants;

async function saveSkillOutput(filePath, data) {
  let fh;
  try {
    // For new files: O_CREAT | O_EXCL atomically creates-or-fails.
    // O_EXCL causes open() to fail if the path already exists (including
    // if it is a symlink), so there is no gap for a swap.
    fh = await fs.open(filePath, "wx");   // 'wx' = O_WRONLY|O_CREAT|O_EXCL
  } catch (err) {
    if (err.code === "EEXIST") {
      // File already exists — open it without following symlinks.
      // O_NOFOLLOW causes open() to fail if the final path component is a symlink.
      try {
        fh = await fs.open(filePath, fsCb.constants.O_WRONLY | fsCb.constants.O_NOFOLLOW);
      } catch (innerErr) {
        throw new Error(
          `Refusing to write: ${filePath} is a symlink or not writable (${innerErr.code})`
        );
      }
    } else {
      throw err;
    }
  }

  try {
    await fh.writeFile(data, { encoding: "utf8" });
  } finally {
    await fh.close();
  }
}

// Alternative for strictly new files (simpler):
async function createNewSkillOutput(filePath, data) {
  // 'wx' fails atomically if file exists — no prior access() check needed.
  const fh = await fs.open(filePath, "wx");
  try {
    await fh.writeFile(data, { encoding: "utf8" });
  } finally {
    await fh.close();
  }
}

The key insight is that fs.open(filePath, 'wx') (which maps to O_WRONLY | O_CREAT | O_EXCL) is a single atomic syscall that both checks for existence and creates the file. The kernel guarantees that no other process can create the same path between the check and the creation — it is a single operation at the VFS layer. If the file already exists (including as a symlink target), open() returns EEXIST immediately. For overwriting existing files, O_NOFOLLOW causes open() to fail with ELOOP if the final path component is a symbolic link, eliminating the swap attack entirely.

Why not just use fs.lstat() first? Checking with lstat() before open() does not close the race — it widens it by adding a third syscall. The only way to eliminate the TOCTOU gap is to combine the check and the action into a single atomic kernel operation. O_CREAT|O_EXCL and O_NOFOLLOW are the POSIX primitives designed for exactly this purpose.

2. TOCTOU-002 — Concurrent Credit Debit with Non-Atomic Read-Modify-Write

MCP skills that manage user credits, token budgets, rate limit counters, or any numeric account balance are vulnerable to a classic double-spend race condition when the read and the write are separate database operations. The pattern is: read the current balance, check that it is sufficient, then update it. When two requests execute concurrently and both read before either writes, both see the pre-deduction balance, both pass the sufficiency check, and both apply their deduction — resulting in the balance being reduced by only one deduction instead of two.

In Node.js, this race does not require threading. The await on the first SELECT releases the event loop, and the second concurrent request's SELECT can execute in that gap. By the time both requests have read the balance, neither has written yet. Both then write, and the later write overwrites the earlier one — or, if using balance - deductionAmount arithmetic in the application layer rather than in SQL, both deductions apply to the same starting balance.

Wrong
// TOCTOU-002 WRONG — read balance in app, check in app, update in separate query
// Two concurrent POST /use-credit requests will both see balance=10,
// both pass the check, and each will update balance to 5 instead of one
// updating to 5 and the other failing.

const { Pool } = require("pg");
const pool = new Pool();

async function useCredit(userId, amount) {
  const client = await pool.connect();
  try {
    // CHECK: read current balance
    const result = await client.query(
      "SELECT balance FROM accounts WHERE id = $1",
      [userId]
    );
    const { balance } = result.rows[0];

    // << TOCTOU GAP >>
    // Another request for the same userId runs here and also reads balance=10.

    if (balance < amount) {
      throw new Error(`Insufficient balance: ${balance} < ${amount}`);
    }

    // ACTION: deduct — but the other concurrent request will also deduct
    // from the same starting balance of 10, resulting in balance=5 for both.
    await client.query(
      "UPDATE accounts SET balance = balance - $2 WHERE id = $1",
      [userId, amount]
    );
  } finally {
    client.release();
  }
}

The root cause is that the check (reading the balance) and the action (updating it) are executed as two independent SQL statements without any locking between them. PostgreSQL's default isolation level (Read Committed) does not prevent this race: each statement sees a fresh snapshot, so the second concurrent SELECT reads the unmodified balance even after the first request's UPDATE has begun (but not yet committed).

Right
// TOCTOU-002 RIGHT — two approaches:
// Option A: SELECT ... FOR UPDATE within a transaction (advisory row lock)
// Option B: single atomic UPDATE ... WHERE balance >= amount RETURNING balance

const { Pool } = require("pg");
const pool = new Pool();

// --- Option A: SELECT FOR UPDATE ---
// The FOR UPDATE lock prevents any other transaction from reading or
// modifying the row until this transaction commits or rolls back.
// Use when you need the balance value in application logic before writing.
async function useCreditForUpdate(userId, amount) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    const result = await client.query(
      // FOR UPDATE acquires a row-level exclusive lock on the accounts row.
      // Any concurrent transaction that also tries SELECT ... FOR UPDATE
      // will block until this transaction finishes.
      "SELECT balance FROM accounts WHERE id = $1 FOR UPDATE",
      [userId]
    );

    if (!result.rows.length) throw new Error("Account not found");
    const { balance } = result.rows[0];

    if (balance < amount) {
      await client.query("ROLLBACK");
      throw new Error(`Insufficient balance: ${balance} < ${amount}`);
    }

    await client.query(
      "UPDATE accounts SET balance = balance - $2 WHERE id = $1",
      [userId, amount]
    );

    await client.query("COMMIT");
  } catch (err) {
    await client.query("ROLLBACK").catch(() => {});
    throw err;
  } finally {
    client.release();
  }
}

// --- Option B: atomic UPDATE with WHERE guard ---
// No separate SELECT; the UPDATE only applies if balance is sufficient.
// Check rowCount to detect the race — zero rows means insufficient balance
// or the row was already claimed by another concurrent request.
async function useCreditAtomic(userId, amount) {
  const result = await pool.query(
    `UPDATE accounts
       SET balance = balance - $2
     WHERE id = $1
       AND balance >= $2
     RETURNING balance`,
    [userId, amount]
  );

  if (result.rowCount === 0) {
    // Either insufficient balance or concurrent deduction claimed it first.
    // Re-read to distinguish:
    const check = await pool.query(
      "SELECT balance FROM accounts WHERE id = $1", [userId]
    );
    const bal = check.rows[0]?.balance ?? 0;
    throw new Error(
      bal < amount
        ? `Insufficient balance: ${bal} < ${amount}`
        : "Concurrent update conflict — please retry"
    );
  }

  return result.rows[0].balance;  // remaining balance after deduction
}

Both approaches eliminate the TOCTOU gap. Option A uses a pessimistic row-level lock: SELECT ... FOR UPDATE blocks any concurrent transaction from acquiring the same lock, serialising access to the row. Option B uses an optimistic approach: the single UPDATE ... WHERE balance >= amount statement is atomic at the database engine level — either all rows matching the predicate are updated or none are, with no gap between the check and the write. Option B is generally preferred for high-throughput MCP skills because it avoids long-held locks and naturally supports retry semantics.

Node.js mutex alternative: For in-memory state (not backed by a database), use the async-mutex library. const mutex = new Mutex(); const release = await mutex.acquire(); try { /* check and act */ } finally { release(); } serialises concurrent access within a single Node.js process. This does not help for multi-process or multi-instance deployments — only database-level locking works in distributed scenarios.

3. TOCTOU-003 — Session Validation Gap Between Permission Check and DB Mutation

MCP skills that enforce role-based access control commonly load a session object at the start of a request handler, check the role on that object, then use the session's user ID in a subsequent database mutation. The session object is fetched once and cached in the request closure. The problem is that sessions are mutable state that lives in the database — a session can be revoked, a role can be downgraded, or a user can be suspended at any time. If the check and the mutation are not co-located in a single atomic database operation, a window exists where an action is authorised based on session state that is no longer valid.

Consider a scenario where an MCP skill allows admin users to perform bulk mutations. An administrator's session token is compromised and the security team revokes it by deleting the row from the sessions table. If a request using that token is in-flight at the moment of revocation — having passed the role check but not yet reached the database mutation — the mutation will execute using the revoked admin's user ID, even though the session no longer exists.

Wrong
// TOCTOU-003 WRONG — role check on cached session object, then separate DB mutation
// If the session is revoked or the role is downgraded between the check and
// the mutation, the mutation executes with stale authorisation.

async function performAdminMutation(token, resourceId, newValue) {
  // CHECK: load session and verify role
  const session = await getSession(token);  // SELECT * FROM sessions WHERE token = $1
  if (!session) throw new Error("Invalid session");

  if (session.role !== "admin") {
    throw new Error("Admin role required");
  }

  // << TOCTOU GAP >>
  // Security team revokes the session here (DELETE FROM sessions WHERE token = $1).
  // session.role is still "admin" in the in-memory object, but the DB row is gone.
  // Any further await gives the event loop a chance to process the revocation event
  // (if using a pub/sub session invalidation mechanism).

  // ACTION: perform the mutation using session.userId from the stale object
  await db.query(
    "UPDATE resource SET value = $1 WHERE id = $2",
    [newValue, resourceId]
  );

  // Audit log uses session.userId — may reference a revoked/deleted user
  await auditLog(session.userId, "admin_mutation", resourceId);
}
Right
// TOCTOU-003 RIGHT — combine the permission check and the mutation in a single
// atomic DB statement using a CTE (Common Table Expression).
// The UPDATE only executes if the session exists AND has role='admin' at the
// exact moment the statement runs — no gap between check and action.

async function performAdminMutation(token, resourceId, newValue) {
  const result = await db.query(
    // The CTE re-validates the session at mutation time.
    // If the session is revoked between request receipt and this query,
    // the EXISTS() subquery returns false and rowCount is 0.
    `WITH session_check AS (
       SELECT user_id
         FROM sessions
        WHERE token = $1
          AND role   = 'admin'
          AND expires_at > NOW()
     )
     UPDATE resource
        SET value      = $2,
            updated_at = NOW()
      WHERE id = $3
        AND EXISTS (SELECT 1 FROM session_check)
     RETURNING id, (SELECT user_id FROM session_check) AS actor_id`,
    [token, newValue, resourceId]
  );

  if (result.rowCount === 0) {
    // Either the session is revoked/expired, role was downgraded,
    // or the resource does not exist — all three cases are safe refusals.
    throw new Error(
      "Mutation rejected: session invalid, role insufficient, or resource not found"
    );
  }

  const { actor_id } = result.rows[0];
  await auditLog(actor_id, "admin_mutation", resourceId);
}

// Alternative: use a transaction with a re-read FOR UPDATE
async function performAdminMutationTx(token, resourceId, newValue) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    // Re-validate the session inside the transaction with a row lock
    const sessionResult = await client.query(
      `SELECT user_id, role
         FROM sessions
        WHERE token = $1
          AND expires_at > NOW()
       FOR UPDATE`,
      [token]
    );

    if (!sessionResult.rows.length || sessionResult.rows[0].role !== "admin") {
      await client.query("ROLLBACK");
      throw new Error("Session invalid or insufficient role at mutation time");
    }

    const { user_id } = sessionResult.rows[0];

    await client.query(
      "UPDATE resource SET value = $1, updated_at = NOW() WHERE id = $2",
      [newValue, resourceId]
    );

    await client.query("COMMIT");
    await auditLog(user_id, "admin_mutation", resourceId);
  } catch (err) {
    await client.query("ROLLBACK").catch(() => {});
    throw err;
  } finally {
    client.release();
  }
}

The CTE approach is elegant because it folds the permission check directly into the predicate of the UPDATE statement. The database engine evaluates the EXISTS (SELECT 1 FROM session_check) condition atomically as part of the update — if the session row is not present (because it was revoked) or does not have role = 'admin', the UPDATE affects zero rows and the application raises an error. The session validation and the resource mutation are co-located in a single round-trip, with no gap between them.

This pattern is especially important for MCP skills used in agentic pipelines, where a single LLM session may issue many tool calls over a period of minutes. Session revocation is a critical security control in such deployments — an operator who discovers that an AI agent is misbehaving needs to be able to terminate its authorisation immediately, and that termination must take effect on in-flight requests, not just future ones. See also the related discussion in our async/await race condition security guide for patterns where await boundaries introduce similar gaps in non-database state.

4. TOCTOU-004 — Tmp File Create-Write-Move Race Allowing Symlink Swap

Many MCP skills implement a write-then-verify pipeline: write an uploaded file to a temporary location, run a verification step (antivirus scan, format validation, content policy check), then move the verified file to its final destination. The design intent is sound — the verification happens before the file lands in the production path. But the pipeline has a critical TOCTOU gap between the verification step and the move: an attacker who can observe /tmp/ can replace the temp file with a symbolic link after the antivirus scan completes but before the rename() call, causing the move to overwrite an arbitrary target with the symlink's destination.

The exploit is particularly dangerous because the AV scan passes — the file that the scanner examined was the original upload, not the symlink. The move operation then copies the symlink (or follows it, depending on how rename is used) to the production path. If the move is implemented as a copy-then-delete (which fs.rename() falls back to on cross-device moves), the write will follow the symlink and overwrite the attacker's target with whatever the AV scan just cleared.

Wrong
// TOCTOU-004 WRONG — write to predictable /tmp path, scan, then move
// An inotify watcher on /tmp can replace the file with a symlink
// after the scan but before the rename.

const fs   = require("fs/promises");
const path = require("path");

async function processUpload(uploadBuffer, destPath) {
  // Predictable tmp path — easy to race
  const tmpPath = `/tmp/upload-${Date.now()}.zip`;

  // Write to tmp
  await fs.writeFile(tmpPath, uploadBuffer);

  // Scan — attacker watches for CLOSE_WRITE event on tmpPath via inotify
  const scanResult = await antivirusScan(tmpPath);
  if (!scanResult.clean) {
    await fs.unlink(tmpPath);
    throw new Error("Malware detected");
  }

  // << TOCTOU GAP >>
  // Attacker replaces tmpPath with symlink to /var/www/html/shell.php
  // The scan just cleared a legitimate file; the rename now moves a symlink.

  // ACTION: move to final destination — may follow the symlink
  await fs.rename(tmpPath, destPath);
}
Right
// TOCTOU-004 RIGHT — mkdtemp for isolation, inode check before rename,
// atomic rename within same filesystem.

const fs     = require("fs/promises");
const fsCb   = require("fs");
const path   = require("path");
const crypto = require("crypto");

async function processUpload(uploadBuffer, destPath) {
  // Create a private tmp directory owned by this process.
  // mkdtemp creates a directory with mode 0700 — no other user can
  // list or access the directory, eliminating the inotify attack surface.
  const tmpDir = await fs.mkdtemp("/tmp/skill-upload-");

  // Write inside the private directory
  const tmpFile = path.join(tmpDir, "upload.zip");
  await fs.writeFile(tmpFile, uploadBuffer, { mode: 0o600 });

  // Record the inode and size immediately after writing
  const statBefore = await fs.stat(tmpFile);

  try {
    // Scan the file
    const scanResult = await antivirusScan(tmpFile);
    if (!scanResult.clean) {
      throw new Error("Malware detected");
    }

    // Verify the file identity has not changed between write and scan.
    // A symlink replacement would change the inode number; a modified
    // file would change mtime and/or size.
    const statAfter = await fs.stat(tmpFile);
    if (
      statAfter.ino  !== statBefore.ino ||
      statAfter.size !== statBefore.size ||
      statAfter.mtimeMs !== statBefore.mtimeMs
    ) {
      throw new Error(
        "File identity changed between write and scan — possible symlink swap"
      );
    }

    // Use fs.rename for atomic move (works within same filesystem / tmpfs).
    // On Linux, rename(2) is atomic: it either succeeds fully or fails;
    // there is no partial state visible to other processes.
    await fs.rename(tmpFile, destPath);

  } finally {
    // Clean up the private tmp directory regardless of outcome
    await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
  }
}

// For cross-device moves (rename fails with EXDEV), use a secure copy:
async function secureMoveCrossDevice(src, dest) {
  // Open src with O_NOFOLLOW to refuse to read a symlink
  const srcFd = await fs.open(src, fsCb.constants.O_RDONLY | fsCb.constants.O_NOFOLLOW);
  try {
    const destFd = await fs.open(dest, "wx");  // O_CREAT|O_EXCL — fail if exists
    try {
      // Stream from src fd to dest fd without ever re-resolving the path
      const readStream  = srcFd.createReadStream();
      const writeStream = destFd.createWriteStream();
      await new Promise((resolve, reject) => {
        readStream.pipe(writeStream);
        writeStream.on("finish", resolve);
        writeStream.on("error",  reject);
        readStream.on("error",   reject);
      });
    } finally {
      await destFd.close();
    }
  } finally {
    await srcFd.close();
  }
  await fs.unlink(src);
}

The fix combines three independent protections. First, fs.mkdtemp() creates a directory with mode 0700 (owner-only read/write/execute). No other user on the system can list the directory or access files within it, which means inotify_add_watch on the containing /tmp/ will not reveal the directory's contents, and direct path guessing is infeasible because the suffix is randomly generated. Second, the inode check after the scan detects if the file was replaced between the write and the scan — a symlink swap creates a new inode number. Third, fs.rename() is an atomic POSIX operation: on the same filesystem it completes as a single syscall with no observable intermediate state. The O_NOFOLLOW flag on the cross-device copy path prevents the read from following a symlink if one were somehow present despite the mkdtemp isolation.

tmpfs and filesystem boundaries: fs.rename() is atomic only within a single filesystem. If /tmp/ is a tmpfs mount and your production path is on ext4, the rename will fail with EXDEV (cross-device link). Node.js's fs.rename() does not automatically fall back to copy-delete; it throws. Use the secureMoveCrossDevice function above for cross-device scenarios, or configure your MCP server to write temp files to the same filesystem as the destination.

5. Using async-mutex for In-Process TOCTOU Protection

The database-level fixes above handle the distributed case — multiple Node.js processes or multiple server instances. For MCP skills that manage state entirely in memory (caches, counters, in-memory session stores), the async-mutex library provides the Node.js equivalent of a mutex: a primitive that serialises access to a critical section across concurrent async operations within a single process.

// In-process TOCTOU protection with async-mutex
// npm install async-mutex

const { Mutex } = require("async-mutex");

// One mutex per protected resource identity
const userMutexes = new Map();

function getMutex(userId) {
  if (!userMutexes.has(userId)) {
    userMutexes.set(userId, new Mutex());
  }
  return userMutexes.get(userId);
}

async function useCreditInMemory(userId, amount) {
  const mutex   = getMutex(userId);
  const release = await mutex.acquire();

  try {
    // This entire block executes atomically relative to other callers
    // using the same userId — the await points inside do not release
    // the mutex, only the outer await on acquire() does.
    const account = inMemoryStore.get(userId);
    if (!account) throw new Error("Account not found");

    if (account.balance < amount) {
      throw new Error(`Insufficient balance: ${account.balance} < ${amount}`);
    }

    // No TOCTOU gap here — the mutex holds across this entire try block
    account.balance -= amount;
    inMemoryStore.set(userId, account);

    return account.balance;
  } finally {
    release();
  }
}

The async-mutex Mutex.acquire() returns a release function. Any concurrent call to acquire() on the same mutex will await (suspend, returning control to the event loop) until the first caller invokes release(). Critically, the mutex is held even across await points inside the critical section — unlike raw async code where every await releases the event loop and allows other callbacks to run. This is the semantic gap that makes in-memory TOCTOU bugs possible in Node.js: the event loop's concurrency model gives the appearance of single-threaded execution but allows interleaving at every await boundary.

For file-system-backed state, consider pairing the mutex with the atomic file operations from TOCTOU-001. The mutex serialises Node.js-level access; the O_NOFOLLOW flag handles OS-level races from other processes outside the Node.js runtime. See also the file read path traversal and static file security guide for related patterns where file path construction creates similar check-action gaps in read operations.

6. SkillAudit Detection — TOCTOU Rule Family

SkillAudit's AST scanner detects all four TOCTOU patterns through dataflow analysis of MCP skill JavaScript and TypeScript source. For each pattern, the scanner traces the data flow from the check operation to the action operation, identifies await boundaries between them, and flags the gap as a potential TOCTOU vulnerability. The scanner understands the following call patterns:

For MCP skills that handle concurrent requests in multi-agent pipelines, these patterns represent an elevated risk compared to conventional web applications. The LLM orchestration layer may issue thousands of tool calls per hour against a single MCP server, dramatically increasing the probability that two concurrent calls land in the same TOCTOU window. See our MCP server SSRF security guide for related patterns where the check-action gap appears in URL validation before outbound HTTP requests — a structurally identical TOCTOU pattern applied to network egress rather than filesystem or database state.

7. Detection Summary

Rule ID Vulnerability Severity Vulnerable Pattern Fix
TOCTOU-001 File permission check before write Critical 9.1 fs.access(path, W_OK) then fs.writeFile(path, ...) across await fs.open(path, 'wx') (O_CREAT|O_EXCL) or O_NOFOLLOW on existing file
TOCTOU-002 Non-atomic credit debit / double-spend Critical 8.1 Separate SELECT balance and UPDATE balance without transaction lock SELECT ... FOR UPDATE in transaction, or atomic UPDATE ... WHERE balance >= amount RETURNING
TOCTOU-003 Stale session permission at DB mutation High 7.5 getSession(token) check then separate DB mutation using session.userId CTE or transaction re-validates session at mutation time; UPDATE ... WHERE EXISTS (SELECT 1 FROM sessions WHERE token = $1 AND role = 'admin')
TOCTOU-004 Tmp file symlink swap after AV scan High 7.3 Write to predictable /tmp/name, scan, then fs.rename() without inode check fs.mkdtemp() for isolated 0700 dir; inode check before rename; O_NOFOLLOW on cross-device copy

Related patterns: TOCTOU vulnerabilities in async/await code share root causes with broader async race conditions — see SA-SKL-ASYNCRACE2: async/await race condition security in MCP skills for patterns that do not involve filesystem or database state. For file read operations where the path itself is user-controlled, see SA-SKL-FILEREAD2: path traversal in static file and template serving. For server-side request forgery via URL check-then-fetch gaps, see the MCP server SSRF security guide.

Related rule
SA-SKL-ASYNCRACE2: async/await Race Condition Security in MCP Skills
Related rule
SA-SKL-FILEREAD2: Path Traversal in Static File and Template Serving