agentleFS
zahidoverflowzahidoverflow/viperclaw/skills/viper-race-logic/SKILL.md

viper-race-logic

Skill22 starsChanged 15 days agoMITView on GitHub

Concurrency, Idempotency & Business Logic Auditor. Reviews state-changing transactions, database locking, and multi-step workflow integrity to prevent TOCTOU race conditions.

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 4 are distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Run the following discovery commands across the target repository before manual code review:

    line 30
  2. Distinctive:

    Verify whether an upstream API Gateway, global middleware, or ORM hook already enforces the control before flagging a controller.

    line 62
  3. Distinctive:

    Write a Positive Unit Test confirming authorized, schema-valid requests succeed.

    line 102
  4. Distinctive:

    Write a Negative Security Regression Test confirming unauthorized, cross-tenant, or malformed inputs are deterministically rejected.

    line 103

≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Concurrency, TOCTOU Race Condition & Business Logic Auditor (viper-race-logic)

1. Executive Scope, Standards & CWE/OWASP Mapping

  • Frameworks & Standards: OWASP Top 10:2025 A04 (Insecure Design), OWASP API6:2023, CWE-362, CWE-841
  • Primary CWE Mapping: CWE-362 (Concurrent Execution using Shared Resource with Improper Synchronization / Race Condition), CWE-367 (TOCTOU), CWE-841 (Improper Enforcement of Behavioral Workflow)
  • ViperClaw MCP Tools: viper_race_burst, viper_diff_oracle, viper_verify_and_report
  • ViperClaw CLI Command: viperclaw race https://api.example.com/v1/redeem -X POST -d "code=PROMO" -c 15

2. Threat Model & Root-Cause Architecture

flowchart LR
  Burst["Concurrent Requests (t=0.00ms)"] --> Lock["Pessimistic Lock / Atomic UPDATE"] --> Idemp["Idempotency Key Store"] --> Ledger[("Consistent Ledger State")]

Root-Cause Analysis

Applications read a state value (SELECT balance, redeemed FROM ...), validate it in application memory (if balance >= amount), and issue a separate UPDATE statement without a row lock (FOR UPDATE) or atomic WHERE predicate, allowing parallel requests arriving within the same 5–50ms DB round-trip window to pass the check simultaneously.


3. Deterministic Discovery & Grep/AST Audit Commands

Run the following discovery commands across the target repository before manual code review:

# 1. Automated ViperClaw analysis
viperclaw race https://api.example.com/v1/redeem -X POST -d "code=PROMO" -c 15

# 2. Rapid static pattern discovery (ripgrep)
rg -n "(SELECT\s+.*balance|with_for_update|FOR UPDATE|select_for_update|SERIALIZABLE)"
rg -n "(idempotency_key|Idempotency-Key|redis\.setnx|SET .* NX)"
rg -n "(coupon|redeem|withdraw|transfer|vote|credit|quota)"

4. Senior Security Engineer 8-Point Audit Checklist

Control IDAudit Verification TargetPass CriteriaFail / Vulnerability Indicator
RACE-01Atomic Conditional SQL UpdatesBalance/inventory deductions execute UPDATE accounts SET balance = balance - :amt WHERE id = :id AND balance >= :amt and check rowcount == 1.Separate SELECT balance followed by unconditional UPDATE accounts SET balance = :new_bal.
RACE-02Pessimistic Row Locking (FOR UPDATE)Multi-query read-modify-write transactions lock rows with SELECT ... FOR UPDATE (with_for_update()).Read-Committed transaction reads mutable state without row locking before writing.
RACE-03Database Unique Constraints on One-Time ActionsCoupon redemptions, likes, referrals, and invite claims enforce a composite UNIQUE(user_id, coupon_id) DB index.Uniqueness checked only in application code (if not Redeemed.exists(...)) before INSERT.
RACE-04Idempotency Key EnforcementFinancial/mutation endpoints require an Idempotency-Key header locked atomically via INSERT ... ON CONFLICT DO NOTHING or Redis SET NX.Retried or parallel POST requests execute duplicate charges or state transitions.
RACE-05Multi-Step Workflow State VerificationStep 3 of a checkout/KYC/reset flow verifies in the server session that Steps 1 and 2 were completed for the same transaction.Client can call POST /checkout/confirm directly without completing POST /checkout/pay.
RACE-06Negative & Zero Boundary ValidationQuantities, transfer amounts, and pagination offsets enforce val > 0 and upper bounds.Transferring -100 credits increases the sender's balance.
RACE-07Distributed Lock Lease SafetyRedis/distributed locks use unique lock tokens and Lua compare-and-delete scripts with sufficient TTL.Worker A's lock expires mid-operation and Worker A deletes Worker B's newly acquired lock.
RACE-08Rate-Limit Counter AtomicityRate-limit counters increment atomically (INCR + EXPIRE in Lua) rather than GET then SET.Parallel burst requests read the same counter value (9/10) and exceed the rate limit.

5. False-Positive Elimination & CVSS v3.1 Triage Rubric

False-Positive Gate

  1. Verify whether an upstream API Gateway, global middleware, or ORM hook already enforces the control before flagging a controller.
  2. Confirm the code path is reachable from an external entrypoint (not dead code, CLI-only admin script, or unit-test fixture).
Severity TierBaseline CVSS v3.1 VectorQualifying Security Impact
CRITICAL (9.1)CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:HTOCTOU race condition allowing unlimited balance withdrawal, gift-card duplication, or privilege escalation.
HIGH (7.5)CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:NSingle-use coupon, referral bonus, or seat quota overrun via concurrent requests.
MEDIUM (5.3)CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:N/I:L/A:NNon-financial counter or vote/rating manipulation via parallel requests.

6. Production Remediation Patterns (Vulnerable vs. Hardened Code)

# ❌ VULNERABLE: Classic read-then-write TOCTOU window (no row lock, no atomic predicate)
def withdraw_funds(db: Session, account_id: int, amount: int):
    acct = db.query(Account).filter(Account.id == account_id).first()
    if acct.balance < amount:
        raise ValueError("Insufficient funds")
    acct.balance -= amount
    db.commit()

# ✅ HARDENED: Atomic conditional UPDATE + positive amount check inside transaction
def withdraw_funds(db: Session, account_id: int, amount: int):
    if amount <= 0:
        raise ValueError("Amount must be positive")
    updated = (
        db.query(Account)
        .filter(Account.id == account_id, Account.balance >= amount)
        .update({Account.balance: Account.balance - amount}, synchronize_session=False)
    )
    if updated != 1:
        db.rollback()
        raise ValueError("Insufficient funds or concurrent modification")
    db.commit()

7. Regression Testing & Continuous Verification

  1. Write a Positive Unit Test confirming authorized, schema-valid requests succeed.
  2. Write a Negative Security Regression Test confirming unauthorized, cross-tenant, or malformed inputs are deterministically rejected.
  3. Re-run viperclaw taint and viperclaw verify to confirm zero remaining unmitigated flows in .viperclaw/graph.db.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.