← Blog

File upload race conditions and storage atomicity vulnerabilities in Claude MCP skills — SA-SKL-MULTIPART3

File upload handlers in MCP skills are a common source of race condition vulnerabilities that standard code review misses. The root issue is non-atomic storage: a window exists between when a file is validated and when it is moved to its final location, between when two concurrent uploads target the same path, and between when a file is first written and when it is fully validated. SA-SKL-MULTIPART3 covers four storage atomicity race conditions and their fixes.

By SkillAudit  |  6 Nov 2026

Why file upload race conditions are hard to find in code review

Race conditions in file upload handlers do not appear in a linear reading of the code. The vulnerable code looks correct: it validates the file, then moves it. The race window is in the gap between those two steps — a window measured in milliseconds that an attacker can exploit by sending a second concurrent request timed to replace the temp file just after validation passes. Static analysis tools catch injection vulnerabilities and missing authentication checks, but they typically cannot model the interleaving of concurrent requests that creates the TOCTOU window. MCP skills that accept file uploads (source code archives, configuration files, plugin ZIPs, model weights) need explicit atomicity guarantees in their storage layer, not just per-step validation.

SA-SKL-MULTIPART3 in scope: MULTIPART3-001 (TOCTOU between validation and move), MULTIPART3-002 (concurrent same-filename overwrite), MULTIPART3-003 (partial upload public exposure), MULTIPART3-004 (cleanup TTL race). Each pattern includes SkillAudit detection rules and correct fixes.

MULTIPART3-001 — TOCTOU between upload validation and atomic move

Time-of-check to time-of-use (TOCTOU) is the canonical file upload race condition. The upload handler receives a file to a temporary path, runs validation (antivirus scan, MIME type check, content inspection), and if validation passes, moves the file to its final storage location. An attacker who can send two concurrent requests can time the second request to replace the temp file on disk between the validation pass and the move operation. The antivirus scanner approved the first (clean) file; the file at the temp path is now the malicious payload; the move copies the malicious file to the final path. The fix is to treat the validated file and the final stored file as the same inode: validate after the rename or validate in-place at the final path, never validate a path that the attacker can overwrite.

// VULNERABLE — TOCTOU: attacker replaces temp file between validation and move
import multer from 'multer';
import path from 'path';
import fs from 'fs/promises';
import { scanForMalware } from './antivirus';

const upload = multer({ dest: '/tmp/uploads/' });

app.post('/api/upload', upload.single('file'), async (req, res) => {
  const tempPath = req.file.path; // e.g. /tmp/uploads/abc123

  // STEP 1: validate — antivirus approves the clean file
  const scanResult = await scanForMalware(tempPath);
  if (!scanResult.clean) {
    await fs.unlink(tempPath);
    return res.status(400).json({ error: 'Malware detected' });
  }

  // RACE WINDOW HERE: attacker replaces /tmp/uploads/abc123 with malicious file
  // between scan completion and the rename below

  // STEP 2: move to permanent storage — moves attacker's file, not the scanned one
  const finalPath = path.join('/var/skills/uploads/', req.file.originalname);
  await fs.rename(tempPath, finalPath);
  res.json({ path: finalPath });
});
// FIXED — rename to final path FIRST, then validate in-place; delete on failure
import multer from 'multer';
import path from 'path';
import fs from 'fs/promises';
import { randomUUID } from 'crypto';
import { scanForMalware } from './antivirus';

const upload = multer({ dest: '/tmp/uploads/' });

app.post('/api/upload', upload.single('file'), async (req, res) => {
  const tempPath = req.file.path;

  // Move to final location FIRST using a UUID filename (attacker cannot predict it)
  const finalName = `${randomUUID()}${path.extname(req.file.originalname)}`;
  const finalPath = path.join('/var/skills/uploads/', finalName);

  // Atomic rename: file is now at a UUID path the attacker cannot replace
  await fs.rename(tempPath, finalPath);

  // Validate at the final path — no race window possible
  const scanResult = await scanForMalware(finalPath);
  if (!scanResult.clean) {
    // Clean up the already-moved file
    await fs.unlink(finalPath);
    return res.status(400).json({ error: 'Malware detected' });
  }

  // Store only the UUID filename in DB — never store user-supplied original name
  await db.insertUpload({ filename: finalName, originalName: req.file.originalname, userId: req.user.id });
  res.json({ id: finalName });
});
CRITICAL
SA-SKL-MULTIPART3-001 — Upload handlers that validate a file at a temp path and then move it to a final location have a race window where an attacker can replace the temp file between the validation check and the rename; fix by moving to a UUID final path first, then validating at the final path where the attacker has no write access. Detection: SkillAudit flags upload handlers where a scanForMalware(), MIME check, or content validation call precedes an fs.rename() or fs.copyFile() in the same handler without an intervening UUID path assignment.

MULTIPART3-002 — Concurrent upload of same filename silently overwrites

When two concurrent upload requests target the same final storage path — because the storage path is derived from the user-supplied filename — the second write silently overwrites the first. This is not just a data-loss bug: it is a privilege escalation path. If user A uploads a legitimate plugin to /uploads/plugin.zip and user B sends a concurrent request with the same filename targeting the same shared storage, the final file is B's content attributed to A's upload record. In a skill that serves uploaded files to other users (e.g. a shared plugin repository), B has injected content under A's identity. The fix is to use UUID-based storage paths independent of the original filename for all uploaded content.

// VULNERABLE — storage path derived from original filename; concurrent requests overwrite
app.post('/api/upload', upload.single('file'), async (req, res) => {
  // Two concurrent requests with file.name = "plugin.zip" land at same path
  const finalPath = path.join('/var/uploads/', req.file.originalname);
  await fs.rename(req.file.path, finalPath); // Last write wins — silent overwrite
  res.json({ url: `/uploads/${req.file.originalname}` });
});
// FIXED — UUID path is unique per upload; original filename stored separately in DB
import { randomUUID } from 'crypto';

app.post('/api/upload', upload.single('file'), async (req, res) => {
  const ext = path.extname(req.file.originalname).toLowerCase();
  const storageKey = `${randomUUID()}${ext}`;
  const finalPath = path.join('/var/uploads/', storageKey);

  await fs.rename(req.file.path, finalPath);

  const record = await db.createUpload({
    storageKey,                        // UUID path — used to serve the file
    originalFilename: req.file.originalname, // Display name only — never used as path
    mimeType: req.file.mimetype,
    sizeBytes: req.file.size,
    uploadedBy: req.user.id,
    uploadedAt: new Date(),
  });

  res.json({ id: record.id, url: `/uploads/${storageKey}` });
});
HIGH
SA-SKL-MULTIPART3-002 — Upload handlers that derive the storage path from the user-supplied original filename allow concurrent requests to silently overwrite each other's files; fix by assigning UUID-based storage keys independent of the original filename for all uploaded content and storing the original filename as metadata only. Detection: SkillAudit flags path.join(uploadDir, req.file.originalname) or equivalent patterns where the storage path incorporates any user-supplied value.

MULTIPART3-003 — Partial upload public exposure window

Many upload handlers write directly to the final public storage path and serve files via a URL that maps to that path. During the write operation — which may take seconds for large files — the file at the public URL is partially written: the first N bytes are real content, the remainder is either zeros or prior file content (if overwriting). An attacker who monitors upload traffic and immediately fetches the URL can retrieve a partially written file, bypass content validation (which hasn't run yet), or observe a snapshot of the file mid-write that leaks structural information. The fix is to write to a hidden staging path (by convention: a filename prefixed with a dot, or a directory that is not served), atomically rename to the final path after validation, and only then serve the URL.

// VULNERABLE — file written directly to public path; accessible during write
app.post('/api/upload', upload.single('file'), async (req, res) => {
  const publicPath = path.join('/var/public/uploads/', req.file.originalname);

  // During this copy, GET /uploads/file.zip returns partial content
  await fs.copyFile(req.file.path, publicPath);

  await validateContent(publicPath); // Validation happens after file is already public
  res.json({ url: `/uploads/${req.file.originalname}` });
});
// FIXED — write to staging path, validate, then atomic rename to public path
import { randomUUID } from 'crypto';

app.post('/api/upload', upload.single('file'), async (req, res) => {
  const ext = path.extname(req.file.originalname).toLowerCase();
  const stagingKey = `.staging-${randomUUID()}${ext}`;
  const finalKey = `${randomUUID()}${ext}`;
  const stagingPath = path.join('/var/staging/', stagingKey); // Not served publicly
  const finalPath = path.join('/var/public/uploads/', finalKey);

  // Move temp file to staging — still not publicly reachable
  await fs.rename(req.file.path, stagingPath);

  // Validate at staging path — no public exposure window
  const result = await validateContent(stagingPath);
  if (!result.ok) {
    await fs.unlink(stagingPath);
    return res.status(400).json({ error: result.reason });
  }

  // Atomic rename to public path — file appears fully formed from first byte
  await fs.rename(stagingPath, finalPath);
  res.json({ url: `/uploads/${finalKey}` });
});
HIGH
SA-SKL-MULTIPART3-003 — Upload handlers that write directly to publicly accessible storage paths expose partially written files during the write operation; fix by writing to a non-public staging directory, validating at the staging path, and using an atomic rename (fs.rename() on the same filesystem) to move to the final public path only after full validation. Detection: SkillAudit flags upload handlers where the temp file path is renamed or copied directly to a path under a publicly served directory before a validation call.

MULTIPART3-004 — Cleanup race deletes temp file before processing

Many skill deployments run a periodic background job that removes stale temp files from the upload staging directory to prevent disk exhaustion. If the cleanup job uses file ctime or mtime for its age calculation and deletes files older than N minutes, a slow upload or slow validation step can push the temp file's age past the cleanup threshold between upload completion and processing. The background job deletes the temp file; the upload handler then fails to open the file for the next processing step, returning a 500 error to the user. In adversarial conditions, an attacker can deliberately delay processing (e.g., by flooding the validation queue) to cause cleanup to delete legitimate files and deny service. The fix is to calculate the cleanup TTL from a database record's uploaded_at column, not from filesystem metadata, and to only clean up files that have an explicit processed_at timestamp or that have been in staging for more than a generous threshold (e.g., 30 minutes).

// VULNERABLE — cleanup uses mtime; slow processing can race with cleanup
// Background cleanup job:
async function cleanupStagingDir() {
  const files = await fs.readdir('/var/staging/');
  for (const file of files) {
    const stat = await fs.stat(path.join('/var/staging/', file));
    const ageMinutes = (Date.now() - stat.mtime.getTime()) / 60000;
    if (ageMinutes > 5) { // Delete files older than 5 minutes
      await fs.unlink(path.join('/var/staging/', file)); // May delete mid-processing file
    }
  }
}
// Upload handler:
// 1. File lands in /var/staging/ at T=0 (mtime = T=0)
// 2. Validation queue is busy — processing starts at T=4 minutes
// 3. Cleanup job runs at T=5 — deletes the file (mtime > 5 min threshold)
// 4. Processing step at T=4+N tries to open file → ENOENT → 500 error
// FIXED — cleanup uses DB record age; generous threshold; skip unprocessed files
// Upload handler: insert DB record on arrival
async function handleUpload(tempPath: string, userId: string) {
  const uploadId = randomUUID();
  await db.createStagingRecord({
    id: uploadId,
    path: tempPath,
    uploadedAt: new Date(),
    processedAt: null,
  });
  return uploadId;
}

// Background cleanup job: use DB uploadedAt; skip records with null processedAt
async function cleanupStagingDir() {
  const thirtyMinutesAgo = new Date(Date.now() - 30 * 60 * 1000);
  const staleRecords = await db.query(
    `SELECT id, path FROM staging_uploads
     WHERE processed_at IS NULL AND uploaded_at < $1`,
    [thirtyMinutesAgo]
  );
  for (const record of staleRecords) {
    try {
      await fs.unlink(record.path);
    } catch (e) {
      // File may already be gone — log and continue
    }
    await db.deleteStagingRecord(record.id);
  }
}

// Processing step: mark processedAt before returning, to prevent double-cleanup
async function processUpload(uploadId: string) {
  const record = await db.getStagingRecord(uploadId);
  if (!record) throw new Error('Upload record not found — cleanup may have run');
  // ... process ...
  await db.markProcessed(uploadId);
}
MEDIUM
SA-SKL-MULTIPART3-004 — Staging directory cleanup jobs that use filesystem mtime/ctime with short TTLs (under 15 minutes) can delete temp files that are still being actively processed when the validation queue is slow; fix by using a database record's uploaded_at column for cleanup age calculation with a generous threshold (30+ minutes), and by skipping any record where processed_at is still null. Detection: SkillAudit flags cleanup scripts that use stat.mtime or stat.ctime as the deletion criterion for files in directories also used as upload staging areas.