leoyeai/openclaw-master-skills/phy-concurrency-audit

Claude Code and agent skill by leoyeai/openclaw-master-skills

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Static concurrency and race-condition auditor for Go, Java, Python, Node.js/TypeScript. Detects shared-state mutations without locks (Go map races, Java non-atomic increments, Python thread/asyncio shared lists), TOCTOU (time-of-check-time-of-use) patterns across all languages, sync.Mutex copied by value, WaitGroup.Add inside goroutines, SimpleDateFormat as instance field, double-checked locking without volatile, asyncio shared state without Lock. Maps findings to CWE-362 (race condition) and CWE-367 (TOCTOU). Zero competitors on ClawHub — not a single concurrency-audit SKILL.md in 13,700+ files.

Install

npx vskill@latest install leoyeai/openclaw-master-skills/phy-concurrency-audit

SKILL.md

The same SKILL.md was published earlier as leoyeai/openclaw-master-skills/phy-concurrency-audit.

phy-concurrency-audit

Static scanner for race conditions (CWE-362) and TOCTOU vulnerabilities (CWE-367) in Go, Java, Python, and Node.js/TypeScript codebases. Finds shared-state mutations without synchronization, unsafe concurrency patterns, and check-then-act anti-patterns. Zero external API calls, zero dependencies beyond Python 3 stdlib.

Why Concurrency Bugs Are Special

  • Non-deterministic: reproduce only under load, on multi-core machines, or on specific OS schedulers
  • Silent corruption: data races don't crash immediately — they corrupt state silently for hours
  • Security impact: TOCTOU races in file ops enable symlink attacks and privilege escalation (CWE-367)
  • Hard to test: even go test -race only finds races that actually execute during the test run
  • Static analysis catches the ones that never trigger in testing

What It Detects

Go Race Conditions
PatternSeverityCWE
Global map variable read/written in concurrent functionsCRITICALCWE-362
sync.Mutex or sync.RWMutex copied by value after first useHIGHCWE-362
sync.WaitGroup.Add() called inside a goroutineHIGHCWE-362
Package-level slice/map mutated without mutexHIGHCWE-362
atomic.Value used without checking type consistencyMEDIUMCWE-362
Missing sync.Once for lazy singleton initializationMEDIUMCWE-362
Struct fields accessed in goroutines without receiver mutexHIGHCWE-362
Java Thread-Safety Violations
PatternSeverityCWE
count++ / i++ on shared instance/static field without synchronized or AtomicIntegerHIGHCWE-362
HashMap or ArrayList as instance field in class with concurrent methodsHIGHCWE-362
SimpleDateFormat as static or instance field (not thread-safe)HIGHCWE-362
Double-checked locking without volatile keywordHIGHCWE-362
synchronized block on non-final field (lock can change)MEDIUMCWE-362
Vector/Hashtable used (thread-safe but deprecated, miss modern happens-before)LOWCWE-362
Calendar.getInstance() result stored as fieldMEDIUMCWE-362
Python Threading & Asyncio
PatternSeverityCWE
Thread function mutating module-level list/dict without threading.LockHIGHCWE-362
counter += 1 / list.append() on global var in thread without lockHIGHCWE-362
asyncio coroutine mutating shared object without asyncio.LockHIGHCWE-362
multiprocessing.Process sharing mutable list/dict without ManagerHIGHCWE-362
threading.Thread target accessing global without lockHIGHCWE-362
Node.js / TypeScript Async Races
PatternSeverityCWE
Module-level object/array mutated inside async request handlerHIGHCWE-362
TOCTOU: await cache.has(key) followed by await cache.get(key)HIGHCWE-367
Counter increment count++ in async handler (non-atomic)MEDIUMCWE-362
Promise chain modifying shared closure variableMEDIUMCWE-362
TOCTOU Patterns (All Languages)
PatternSeverityCWE
os.path.exists(path) followed by open(path) without lockHIGHCWE-367
os.path.isdir(d) then os.makedirs(d) without exist_ok=TrueMEDIUMCWE-367
os.path.exists then os.rename/remove/chmodHIGHCWE-367
if not User.exists() then User.create() — DB check-then-insertHIGHCWE-367
Java File.exists() then new FileOutputStream(file)HIGHCWE-367
Node.js fs.existsSync() then fs.writeFileSync()HIGHCWE-367
Go os.Stat(path) check then os.Open(path)HIGHCWE-367

Implementation

python
#!/usr/bin/env python3
"""
phy-concurrency-audit — Race condition & TOCTOU static scanner
Usage: python3 audit_concurrency.py [path] [--json] [--ci]
"""
import argparse
import json
import os
import re
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
CRITICAL, HIGH, MEDIUM, LOW = "CRITICAL", "HIGH", "MEDIUM", "LOW"
SEV_ORDER = {CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3}
ICONS = {CRITICAL: "🔴", HIGH: "🟠", MEDIUM: "🟡", LOW: "⚪"}
@dataclass
class Finding:
file: str
line: int
pattern_name: str
matched_text: str
severity: str
cwe: str
title: str
detail: str
fix: str
# ─── Pattern registry ────────────────────────────────────────────────────────
PATTERNS: dict[str, list] = {
".go": [
("GO_GLOBAL_MAP_RACE",
re.compile(r'^var\s+\w+\s*=\s*(?:map\[|make\s*\(\s*map)', re.MULTILINE),
HIGH, "CWE-362",
"Package-level map — likely shared across goroutines without mutex",
"Go maps are NOT goroutine-safe. Any concurrent read+write is a data race that can panic.",
"Protect with sync.RWMutex or replace with sync.Map for concurrent access."),
("GO_MUTEX_COPY",
re.compile(r'\b(?:sync\.Mutex|sync\.RWMutex)\b'),
HIGH, "CWE-362",
"sync.Mutex/RWMutex — verify it is not copied after first use",
"Copying a Mutex after first Lock/Unlock produces a copy of a locked mutex — deadlock.",
"Always pass Mutex by pointer (*sync.Mutex) or embed in struct accessed via pointer."),
("GO_WAITGROUP_ADD_IN_GOROUTINE",
re.compile(r'go\s+func\s*\([^)]*\)\s*\{[^}]*wg\.Add\s*\(', re.DOTALL),
HIGH, "CWE-362",
"WaitGroup.Add() inside goroutine — race between Add and Wait",
"If wg.Wait() is called before wg.Add() completes, Wait returns prematurely.",
"Always call wg.Add(n) BEFORE launching goroutines, not inside them."),
("GO_ATOMIC_VALUE_MISUSE",
re.compile(r'\batomic\.Value\b'),
MEDIUM, "CWE-362",
"atomic.Value — verify consistent type across Store/Load calls",
"Storing different types in the same atomic.Value panics at runtime.",
"Ensure all Store() calls use the same concrete type; document the stored type in a comment."),
],
".java": [
("JAVA_NON_ATOMIC_INCREMENT",
re.compile(r'(?:private|protected|public|static)\s+(?:int|long|volatile\s+int|volatile\s+long)\s+\w+\s*(?:=\s*\d+)?\s*;'),
HIGH, "CWE-362",
"Shared numeric field — verify increments use AtomicInteger/AtomicLong",
"count++ on a shared field is a read-modify-write that is NOT atomic — silently loses updates.",
"Replace int count with AtomicInteger count = new AtomicInteger(0); use count.incrementAndGet()."),
("JAVA_SHARED_HASHMAP",
re.compile(r'(?:private|protected|public)\s+(?:final\s+)?HashMap\s*<'),
HIGH, "CWE-362",
"HashMap as instance field — not thread-safe for concurrent access",
"Concurrent reads+writes to HashMap can cause infinite loop (Java 7) or data loss (Java 8+).",
"Replace with ConcurrentHashMap or wrap access with synchronized blocks."),
("JAVA_SHARED_ARRAYLIST",
re.compile(r'(?:private|protected|public)\s+(?:final\s+)?ArrayList\s*<'),
HIGH, "CWE-362",
"ArrayList as instance field — not thread-safe for concurrent modification",
"Concurrent modification throws ConcurrentModificationException or silently drops elements.",
"Replace with CopyOnWriteArrayList or Collections.synchronizedList(new ArrayList<>())."),
("JAVA_SIMPLE_DATE_FORMAT",
re.compile(r'(?:private|protected|public|static)\s+(?:final\s+)?SimpleDateFormat\b'),
HIGH, "CWE-362",
"SimpleDateFormat as instance/static field — not thread-safe",
"SimpleDateFormat maintains mutable state internally — concurrent use causes wrong dates or exceptions.",
"Use ThreadLocal<SimpleDateFormat> or replace with thread-safe DateTimeFormatter (Java 8+)."),
("JAVA_DOUBLE_CHECKED_LOCKING",
re.compile(r'if\s*\(\s*\w+\s*==\s*null\s*\)\s*\{\s*synchronized\s*\('),
HIGH, "CWE-362",
"Double-checked locking without volatile — broken without memory barrier",
"Without volatile, the JIT can reorder writes; the second thread sees a partially constructed object.",
"Add 'volatile' to the field declaration: private volatile MyClass instance;"),
("JAVA_SYNC_ON_NONFINAL",
re.compile(r'synchronized\s*\(\s*(?!this|class)\w+\s*\)'),
MEDIUM, "CWE-362",
"synchronized() on potentially non-final field — lock can change",
"If the locked object's reference changes between synchronized blocks, protection is lost.",
"Only synchronize on final fields, 'this', or class literals."),
],
".py": [
("PY_THREAD_GLOBAL_MUTATION",
re.compile(r'def\s+\w+\s*\([^)]*\)\s*:\s*(?:[^\n]*\n\s*)*?global\s+\w+', re.MULTILINE),
HIGH, "CWE-362",
"Thread function using 'global' — likely shared state without lock",
"Global mutations in threads (counter += 1, list.append) are not atomic in CPython despite the GIL.",
"Protect with threading.Lock(): with lock: global_var += 1"),
("PY_THREAD_LIST_MUTATION",
re.compile(r'threading\.Thread\s*\([^)]*target\s*=\s*\w+'),
MEDIUM, "CWE-362",
"threading.Thread — verify shared list/dict access is protected by threading.Lock()",
"Compound operations on shared containers (check-then-modify) are not atomic under GIL.",
"Use threading.Lock() or queue.Queue for thread-safe producer/consumer patterns."),
("PY_ASYNCIO_SHARED_MUTATION",
re.compile(r'async\s+def\s+\w+.*?(?:\n.*?){0,10}(?:shared|cache|results|state)\s*[\[.]=', re.DOTALL),
HIGH, "CWE-362",
"asyncio coroutine mutating shared variable — TOCTOU risk at await boundaries",
"Between two await points, another coroutine can run and modify the same shared state.",
"Use asyncio.Lock() to protect read-modify-write sequences across await boundaries."),
("PY_TOCTOU_EXISTS_OPEN",
re.compile(r'os\.path\.exists\s*\([^)]+\)(?:[^\n]*\n){0,5}[^\n]*\bopen\s*\(', re.MULTILINE),
HIGH, "CWE-367",
"TOCTOU: os.path.exists() followed by open() — race window for file swap",
"An attacker can replace the file with a symlink between exists() check and open() call.",
"Remove exists() check; use try/except FileNotFoundError on open() directly (atomic)."),
("PY_TOCTOU_ISDIR_MAKEDIRS",
re.compile(r'os\.path\.isdir\s*\([^)]+\)(?:[^\n]*\n){0,5}[^\n]*os\.makedirs\s*\('),
MEDIUM, "CWE-367",
"TOCTOU: isdir() + makedirs() — another process can create dir between checks",
"Race causes FileExistsError even though the directory now exists.",
"Use os.makedirs(path, exist_ok=True) — single atomic operation."),
("PY_TOCTOU_EXISTS_RENAME",
re.compile(r'os\.path\.exists\s*\([^)]+\)(?:[^\n]*\n){0,5}[^\n]*(?:os\.rename|os\.remove|os\.chmod|shutil\.move)\s*\('),
HIGH, "CWE-367",
"TOCTOU: exists() check then file operation — file can be replaced between calls",
"Symlink attack: attacker replaces target file with symlink to sensitive file before chmod/rename.",
"Use try/except on the operation directly; or use os.open() with O_NOFOLLOW flag for security-sensitive ops."),
],
".js": _build_js_concurrency_patterns(),
".ts": _build_js_concurrency_patterns(),
}

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 90 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
2,157
Repository forks
324
7-day trend score
43

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/leoyeai/openclaw-master-skills/phy-concurrency-audit/badge)](https://verified-skill.com/skills/leoyeai/openclaw-master-skills/phy-concurrency-audit)

Something wrong with this skill or its page? Tell us.