business-logic-flaws-ai-generated-code
БесплатноБез исполняемых скриптовНе проверенUnderstand business logic vulnerabilities in AI code including race conditions, integer overflow, and calculation errors that pass functional tests but create…
Об этом скилле
Business Logic Vulnerabilities in AI-Generated Code
The Subtlety of Logic Flaws
According to Contrast Security:
"Business logic flaws in AI-generated code are particularly insidious because they often pass all functional tests while creating significant security vulnerabilities."
These vulnerabilities arise from the AI's lack of understanding of business context and security implications.
1.5.1 Race Conditions
The Problem
Race conditions occur when multiple requests access shared resources simultaneously without proper synchronization. The AI generates "correct" code for single-user scenarios but fails to consider concurrent access.
AI-Generated Vulnerable Code
// Prompt: "Implement flash sale with limited quantity"
let availableStock = 100;
app.post('/api/purchase', async (req, res) => {
const { userId, quantity } = req.body;
// ❌ VULNERABLE: Race condition - multiple requests can pass this check
if (availableStock >= quantity) {
// Time window where multiple requests see stock as available
availableStock -= quantity;
// ❌ VULNERABLE: Database update happens after check
await db.orders.create({
userId,
quantity,
timestamp: Date.now()
});
await db.products.update(
{ id: 'flash-sale-item' },
{ stock: availableStock }
);
res.json({ success: true, remaining: availableStock });
} else {
res.status(400).json({ error: 'Insufficient stock' });
}
});
// Attack: Send 100 concurrent requests for 1 item each
// Result: Could sell 200+ items when only 100 available
Why This Is Vulnerable
The Race Condition Timeline:
Time Request A Request B Stock
T0 Read stock: 100 Read stock: 100 100
T1 Check: 100 >= 1 ✓ Check: 100 >= 1 ✓ 100
T2 stock = 99 stock = 99 100
T3 Update DB: 99 - 99
T4 - Update DB: 99 99
Result: Both purchases succeed, but stock should be 98!
With 100 concurrent requests:
- All read stock = 100 at T0
- All pass check at T1
- All decrement to 99 at T2
- Final stock = 99 (should be 0)
- Oversold by 99 items!
Real-World Impact
Flash Sale Scenarios:
- Limited edition product: 100 units
- 1000 customers try to purchase
- Race condition allows 200+ purchases
- Company must fulfill or refund
- Loss: product cost × oversold quantity
- Reputation damage
Financial Services:
- Account balance: $1000
- Concurrent withdrawals of $800 each
- Both succeed (race condition)
- Account balance: -$600
- Bank loses money
Documented Incident:
- Major retailer flash sale: 100 units
- 10,000 customers rushed to buy
- Race condition allowed 1,500 purchases
- Loss: $500,000 (product cost + shipping + reputation)
Secure Implementation
Option 1: Database Transactions with Locking
// ✅ SECURE: Using database transactions and locks
const { Sequelize, Transaction } = require('sequelize');
app.post('/api/purchase', async (req, res) => {
const { userId, quantity } = req.body;
// ✅ SECURE: Use database transaction with row locking
const transaction = await sequelize.transaction({
isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE
});
try {
// ✅ SECURE: Lock the product row during read
const product = await Product.findOne({
where: { id: 'flash-sale-item' },
lock: transaction.LOCK.UPDATE,
transaction
});
if (product.stock >= quantity) {
// ✅ SECURE: Atomic update
await product.decrement('stock', {
by: quantity,
transaction
});
// Create order
const order = await Order.create({
userId,
productId: product.id,
quantity,
price: product.price * quantity,
timestamp: Date.now()
}, { transaction });
// ✅ SECURE: Commit only if all operations succeed
await transaction.commit();
res.json({
success: true,
orderId: order.id,
remaining: product.stock - quantity
});
} else {
await transaction.rollback();
res.status(400).json({
error: 'Insufficient stock',
available: product.stock
});
}
} catch (error) {
await transaction.rollback();
// ✅ SECURE: Log error securely
logger.error('Purchase failed', {
userId,
error: error.code,
timestamp: new Date().toISOString()
});
res.status(500).json({ error: 'Purchase failed' });
}
});
Option 2: Redis Distributed Locking
// ✅
Установить business-logic-flaws-ai-generated-code в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл business-logic-flaws-ai-generated-code?
Understand business logic vulnerabilities in AI code including race conditions, integer overflow, and calculation errors that pass functional tests but create security holes. Use this skill when you need to learn about race conditions in AI code, understand integer overflow vulnerabilities, recognize business logic security flaws, or identify calculation errors. Triggers include "race conditions", "business logic vulnerabilities", "integer overflow", "race condition AI", "flash sale security", "concurrent access", "negative totals", "calculation errors".
Как установить скилл business-logic-flaws-ai-generated-code?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл business-logic-flaws-ai-generated-code запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic