Claude skill rate limiting security — SA-SKL-RATELIMIT
MCP skills that expose audit submission, repository scanning, or AI-powered endpoints without enforced rate limits are exposed to four distinct abuse patterns: credit exhaustion via loop attacks, IP-based bypass via forged forwarded headers, distributed burst attacks that defeat single-counter limits, and account enumeration via timing differences in rate limit error responses. SA-SKL-RATELIMIT covers all four patterns with the attack mechanics and correct defenses for Claude skill deployments.
Why rate limiting failures are especially damaging for AI-powered skills
Conventional web applications suffer denial-of-service, spam, or brute force when rate limits are absent. MCP skills that call Claude APIs carry an additional cost dimension: each invocation triggers a metered API call. A single unprotected audit_repository handler with no per-user limit can drain hundreds of dollars of API credits in minutes via a scripted loop. The four SA-SKL-RATELIMIT patterns span the full attack surface from missing limits through bypass techniques that defeat naïve implementations.
SA-SKL-RATELIMIT in scope: RATELIMIT-001 (no limit on AI-powered endpoints), RATELIMIT-002 (X-Forwarded-For header injection), RATELIMIT-003 (non-atomic Redis race condition), RATELIMIT-004 (account enumeration via rate limit timing). Each pattern includes SkillAudit AST detection rules and remediation code.
RATELIMIT-001 — No rate limit on audit submission tool
The most direct pattern: an Express handler that processes audit_repository skill calls has no rate limit middleware and no per-user budget guard. Each call fans out to Claude’s API, costing real money on every invocation. An attacker with a valid account runs a tight bash loop and depletes the entire credit allocation.
Vulnerable code
// server.ts — no rate limiting on the audit_repository handler
import express from 'express';
import { Anthropic } from '@anthropic-ai/sdk';
const app = express();
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
app.use(express.json());
// No rate limit middleware, no per-user credit check
app.post('/api/skill/audit_repository', async (req, res) => {
const { repoUrl, userId } = req.body;
// Validate repo URL (shape only — no frequency check)
if (!repoUrl || typeof repoUrl !== 'string') {
return res.status(400).json({ error: 'repoUrl required' });
}
// Each call unconditionally triggers a Claude API call (~$0.01–$0.05)
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-6',
max_tokens: 4096,
messages: [
{ role: 'user', content: `Audit this repository for security issues: ${repoUrl}` }
]
});
return res.json({ auditId: crypto.randomUUID(), result: message.content });
});
app.listen(3000);
Attack: credit exhaustion via scripted loop
#!/usr/bin/env bash
# Attacker runs this after obtaining any valid session token
# 10,000 requests/minute, each triggers ~$0.01 Claude API call = $100/min
TOKEN="eyJhbGciOiJIUzI1NiJ9..." # valid auth token from attacker's own account
while true; do
for i in $(seq 1 200); do
curl -s -o /dev/null \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"repoUrl":"https://github.com/victim/repo","userId":"attacker"}' \
https://skillaudit.dev/api/skill/audit_repository &
done
wait # 200 parallel requests per iteration, ~3 seconds wall clock
done
# After 10 minutes: 2,000 requests × $0.05 avg = $100 credits gone
Fix: per-user Redis rate limit with monthly credit budget
// server.ts — rate limited with per-userId key and monthly budget
import express from 'express';
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
import { createClient } from 'redis';
import { Anthropic } from '@anthropic-ai/sdk';
import { db } from './db'; // your database client
const app = express();
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
app.use(express.json());
// Per-userId rate limit: 10 audits per minute per user
const auditRateLimit = rateLimit({
windowMs: 60_000, // 1 minute window
max: 10, // 10 requests per window
standardHeaders: true, // Return RateLimit-* headers
legacyHeaders: false,
// Key by authenticated userId, NOT by IP
keyGenerator: (req) => {
const userId = req.user?.id; // set by auth middleware
if (!userId) throw new Error('unauthenticated');
return `ratelimit:audit:${userId}`;
},
store: new RedisStore({
sendCommand: (...args: string[]) => redis.sendCommand(args),
}),
handler: (req, res) => {
const retryAfter = Math.ceil(
(res.getHeader('RateLimit-Reset') as number) - Date.now() / 1000
);
res.set('Retry-After', String(retryAfter));
res.status(429).json({
error: 'rate_limit_exceeded',
message: 'You have exceeded the audit rate limit. Try again later.',
retryAfter,
});
},
});
// Separate monthly credit budget guard
async function checkCreditBudget(userId: string): Promise {
const monthKey = new Date().toISOString().slice(0, 7); // "2026-11"
const usageKey = `credit:usage:${userId}:${monthKey}`;
const usage = await redis.incrBy(usageKey, 1);
if (usage === 1) {
await redis.expire(usageKey, 60 * 60 * 24 * 32); // ~32 days TTL
}
const plan = await db.getUserPlan(userId);
if (usage > plan.monthlyAuditLimit) {
throw Object.assign(new Error('monthly_budget_exceeded'), { status: 402 });
}
}
app.post('/api/skill/audit_repository',
authMiddleware, // sets req.user
auditRateLimit, // per-minute limit keyed by userId
async (req, res) => {
const { repoUrl } = req.body;
const userId = req.user!.id;
if (!repoUrl || typeof repoUrl !== 'string') {
return res.status(400).json({ error: 'repoUrl required' });
}
try {
await checkCreditBudget(userId);
} catch (err: any) {
return res.status(err.status ?? 402).json({ error: err.message });
}
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-6',
max_tokens: 4096,
messages: [
{ role: 'user', content: `Audit this repository for security issues: ${repoUrl}` }
]
});
return res.json({ auditId: crypto.randomUUID(), result: message.content });
}
);
app.listen(3000);
Key point: Rate limit key must be userId, not IP address. IP-based limits are trivially bypassed (see RATELIMIT-002). The monthly credit budget is a second, orthogonal defense that caps total damage even if the per-minute limit is somehow bypassed.
express-rate-limit with a Redis store keyed by authenticated userId and enforce a per-user monthly credit budget in a separate DB-backed check. Detection: SkillAudit finds route handlers that call anthropic.messages.create or openai.chat.completions.create without a preceding rateLimit() or equivalent middleware in the handler chain.RATELIMIT-002 — X-Forwarded-For header injection bypasses IP-based limits
When a skill uses the client IP as the rate limit key, attackers rotate the X-Forwarded-For header to present a different IP on every request. The counter never increments past 1 for any single IP, so the limit is never enforced.
Vulnerable code
// rateLimitMiddleware.ts — keyed on untrusted X-Forwarded-For
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
export async function ipRateLimit(req: any, res: any, next: any) {
// VULNERABLE: X-Forwarded-For is attacker-controlled
const clientIp =
req.headers['x-forwarded-for']?.split(',')[0].trim() ||
req.socket.remoteAddress;
const key = `ratelimit:${clientIp}`;
const count = await redis.incr(key);
if (count === 1) {
await redis.expire(key, 60); // 1-minute window
}
if (count > 10) {
return res.status(429).json({ error: 'Too many requests' });
}
next();
}
// In server.ts — this limit is completely ineffective
app.post('/api/skill/audit_repository', ipRateLimit, auditHandler);
Attack: rotating X-Forwarded-For defeats IP-based limit
#!/usr/bin/env bash
# Each request presents a fresh IP via X-Forwarded-For
# Rate limit key is always new, counter never reaches 10
TOKEN="eyJhbGciOiJIUzI1NiJ9..."
COUNTER=0
while true; do
COUNTER=$((COUNTER + 1))
# Generate a new spoofed IP for every request
FAKE_IP="$(shuf -i 1-254 -n1).$(shuf -i 1-254 -n1).$(shuf -i 1-254 -n1).$(shuf -i 1-254 -n1)"
curl -s -o /dev/null \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-H "X-Forwarded-For: $FAKE_IP" \
-d '{"repoUrl":"https://github.com/victim/repo"}' \
https://skillaudit.dev/api/skill/audit_repository
echo "Request $COUNTER sent from spoofed IP $FAKE_IP"
done
# Every request passes the limit check — the counter stays at 1 for each fake IP
Fix: use TCP connection IP as rate limit key; configure trust proxy correctly
// rateLimitMiddleware.ts — correct IP extraction
import express from 'express';
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
// Option A: Behind a trusted load balancer (AWS ALB, Nginx, Cloudflare)
// Configure trust proxy to trust exactly 1 hop (the load balancer).
// Express will then set req.ip to the first untrusted IP from X-Forwarded-For,
// which is the actual client IP as seen by the load balancer.
const app = express();
app.set('trust proxy', 1); // trust only the immediately upstream proxy
// express-rate-limit uses req.ip by default when trust proxy is set correctly
export const auditRateLimit = rateLimit({
windowMs: 60_000,
max: 10,
standardHeaders: true,
legacyHeaders: false,
store: new RedisStore({
sendCommand: (...args: string[]) => redis.sendCommand(args),
}),
// keyGenerator defaults to req.ip — correct when trust proxy is set
// Explicitly set for clarity:
keyGenerator: (req) => {
// req.ip is set by Express using trust proxy logic — NOT req.headers['x-forwarded-for']
return `ratelimit:ip:${req.ip}`;
},
});
// Option B: Not behind a proxy (direct internet exposure)
// Use req.socket.remoteAddress — the actual TCP-level peer address,
// completely controlled by the kernel, cannot be forged by an attacker.
export function directIpRateLimit(req: any, res: any, next: any) {
// req.socket.remoteAddress is the kernel-reported peer IP — always accurate
const realIp = req.socket.remoteAddress;
// ... rest of limit logic using realIp as key
}
// What NOT to do — never read X-Forwarded-For directly for rate limit keys:
// const clientIp = req.headers['x-forwarded-for'] // WRONG: attacker-controlled
// const clientIp = req.headers['x-real-ip'] // WRONG: also spoofable
// const clientIp = req.ips[0] // WRONG if trust proxy is too broad
Trust proxy misconfiguration creates the same vulnerability: Setting app.set('trust proxy', true) (instead of a specific hop count like 1) trusts the entire X-Forwarded-For chain, including attacker-appended values. Always set trust proxy to the exact number of proxy hops in your infrastructure.
req.headers['x-forwarded-for'] or req.headers['x-real-ip'] allows unlimited bypass by rotating the header value on each request. Fix: use req.socket.remoteAddress for direct connections or configure app.set('trust proxy', 1) and use req.ip (Express’s trust-proxy-aware property). Detection: SkillAudit AST rule flags any string expression reading req.headers['x-forwarded-for'] that feeds into a Redis key used for rate limiting.RATELIMIT-003 — Non-atomic Redis increment enables distributed burst
A common hand-rolled rate limiter reads the current count with GET, checks it against the limit, and only then increments it with INCR. Under concurrent load, many requests pass the GET check before any single INCR completes. The window between read and write is a classic time-of-check / time-of-use (TOCTOU) race condition.
Vulnerable code: non-atomic get-then-incr
// nonAtomicRateLimit.ts — TOCTOU race between GET and INCR
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const WINDOW_SECS = 60;
const LIMIT = 10;
export async function nonAtomicRateLimit(
userId: string
): Promise<{ allowed: boolean; count: number }> {
const key = `ratelimit:audit:${userId}`;
// Step 1: read current count
const raw = await redis.get(key); // <-- async, yields to event loop
const count = raw ? parseInt(raw, 10) : 0;
// RACE WINDOW: between this check and the INCR below, N parallel requests
// all pass this check because they all read count=0 (or count < LIMIT)
if (count >= LIMIT) {
return { allowed: false, count };
}
// Step 2: increment (happens after the check — not atomic with step 1)
const newCount = await redis.incr(key); // <-- separate round-trip to Redis
if (newCount === 1) {
await redis.expire(key, WINDOW_SECS); // <-- third round-trip
}
return { allowed: true, count: newCount };
}
// Result: if 50 concurrent requests arrive while count=0, all 50 pass the
// GET check before any INCR completes. All 50 are allowed, then count
// jumps to 50. LIMIT=10 is completely ineffective under concurrent load.
Attack: parallel requests exploit the race window
#!/usr/bin/env bash
# Burst 50 requests simultaneously — all arrive while Redis count=0
# All pass the GET check before any INCR completes
# LIMIT=10 is bypassed: all 50 are served
TOKEN="eyJhbGciOiJIUzI1NiJ9..."
echo "Sending 50 parallel requests..."
for i in $(seq 1 50); do
curl -s -w "%{http_code}" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"repoUrl":"https://github.com/victim/repo"}' \
https://skillaudit.dev/api/skill/audit_repository &
done
wait
# Expected with correct limit: 10x 200, 40x 429
# Actual with TOCTOU bug: 50x 200 — all 50 succeed
Fix: Lua EVAL for atomic INCR + EXPIRE, or sliding window with ZADD
// atomicRateLimit.ts — atomic Lua script eliminates the race window
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
// Lua script: INCR and conditional EXPIRE in a single atomic Redis transaction.
// Redis executes Lua scripts as a single operation — no other command can
// interleave between the INCR and EXPIRE calls.
const INCR_WITH_EXPIRE_SCRIPT = `
local c = redis.call('INCR', KEYS[1])
if c == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[1])
end
return c
`;
const WINDOW_SECS = 60;
const LIMIT = 10;
export async function atomicFixedWindowRateLimit(
userId: string
): Promise<{ allowed: boolean; count: number }> {
const key = `ratelimit:audit:${userId}`;
const count = await redis.eval(
INCR_WITH_EXPIRE_SCRIPT,
{ keys: [key], arguments: [String(WINDOW_SECS)] }
) as number;
return { allowed: count <= LIMIT, count };
}
// Alternative: sliding window with ZADD + ZCOUNT (no race, true sliding window)
// More accurate than fixed window but uses more memory.
export async function slidingWindowRateLimit(
userId: string
): Promise<{ allowed: boolean; count: number }> {
const key = `ratelimit:sliding:${userId}`;
const now = Date.now();
const windowStart = now - WINDOW_SECS * 1000;
const requestId = `${now}-${Math.random()}`;
// Pipeline: remove expired entries, add current, count window, set TTL
const results = await redis
.multi()
.zRemRangeByScore(key, '-inf', String(windowStart))
.zAdd(key, { score: now, value: requestId })
.zCount(key, String(windowStart), '+inf')
.expire(key, WINDOW_SECS * 2)
.exec();
const count = results[2] as number;
return { allowed: count <= LIMIT, count };
}
// Middleware wrapper
export async function rateLimit(req: any, res: any, next: any) {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ error: 'unauthenticated' });
const { allowed, count } = await atomicFixedWindowRateLimit(userId);
if (!allowed) {
res.set('Retry-After', String(WINDOW_SECS));
return res.status(429).json({
error: 'rate_limit_exceeded',
count,
limit: LIMIT,
});
}
next();
}
Fixed vs. sliding window: Fixed window (Lua INCR + EXPIRE) is simpler and cheaper but allows up to 2× the limit at window boundaries (last request of window N + first of window N+1). Sliding window (ZADD + ZCOUNT) is accurate but stores one entry per request. For AI-powered endpoints where cost matters, sliding window is recommended.
redis.get then redis.incr calls has a TOCTOU race condition allowing distributed burst attacks to send up to N×limit requests simultaneously. Fix: replace with a Lua EVAL script that performs INCR + EXPIRE atomically, or use a sliding window with ZADD + ZCOUNT. Detection: SkillAudit AST rule flags any code path where redis.get() and redis.incr() share a key variable with a conditional branch between them.RATELIMIT-004 — Timing-based account enumeration via rate limit error order
When rate limit middleware is applied after authentication middleware, the two code paths produce measurably different response times. An attacker can distinguish “account does not exist” (slow DB lookup + 404) from “account exists but is rate limited” (fast counter check + 429), enabling silent account enumeration without triggering authentication alerts.
Vulnerable code: rate limit runs after auth
// server.ts — wrong middleware ordering exposes timing side-channel
import express from 'express';
const app = express();
app.use(express.json());
// WRONG ORDER: auth middleware runs first, then rate limit
// - Non-existent user: auth middleware queries DB (15–30ms), returns 401/404
// - Existing rate-limited user: auth succeeds, rate limit check (~2ms), returns 429
// Timing difference reveals account existence
async function authMiddleware(req: any, res: any, next: any) {
const token = req.headers.authorization?.slice(7);
if (!token) return res.status(401).json({ error: 'missing token' });
// DB lookup: 15–30ms for non-existent user (index miss or not found)
const user = await db.users.findOne({ apiKey: token });
if (!user) return res.status(401).json({ error: 'invalid credentials' });
req.user = user;
next();
}
async function rateLimitMiddleware(req: any, res: any, next: any) {
const userId = req.user.id;
const { allowed } = await checkRedisLimit(userId); // 1–3ms Redis round-trip
if (!allowed) return res.status(429).json({ error: 'rate_limit_exceeded' });
next();
}
// WRONG: auth first (slow for non-existent users), then rate limit (fast)
app.post('/api/skill/audit_repository',
authMiddleware, // 15–30ms if user doesn't exist
rateLimitMiddleware, // 1–3ms if user exists but is rate-limited
auditHandler
);
Attack: timing-based account enumeration
#!/usr/bin/env python3
# Enumerate valid accounts by measuring response time difference
# 429 (fast: ~3ms) = account exists and is rate-limited
# 401 (slow: ~20ms) = account does not exist (DB miss)
import asyncio
import time
import aiohttp
CANDIDATES = [
"user_alice@example.com",
"user_bob@example.com",
"user_charlie@example.com",
# ... thousands of candidates from LinkedIn scraping
]
async def probe(session: aiohttp.ClientSession, candidate: str):
headers = {"Authorization": f"Bearer {candidate}", "Content-Type": "application/json"}
payload = {"repoUrl": "https://github.com/test/test"}
# First exhaust the rate limit by sending 11 requests with the real token
# Then probe candidate tokens and measure response time
start = time.perf_counter()
async with session.post(
"https://skillaudit.dev/api/skill/audit_repository",
headers=headers,
json=payload,
) as resp:
elapsed_ms = (time.perf_counter() - start) * 1000
status = resp.status
return candidate, status, elapsed_ms
async def main():
async with aiohttp.ClientSession() as session:
tasks = [probe(session, c) for c in CANDIDATES]
results = await asyncio.gather(*tasks)
for candidate, status, elapsed in sorted(results, key=lambda x: x[2]):
label = "EXISTS (rate-limited)" if elapsed < 8 else "not found"
print(f"{elapsed:6.1f}ms HTTP {status} {label} {candidate}")
asyncio.run(main())
# Output example:
# 2.3ms HTTP 429 EXISTS (rate-limited) user_alice@example.com
# 3.1ms HTTP 429 EXISTS (rate-limited) user_bob@example.com
# 18.7ms HTTP 401 not found user_charlie@example.com
Fix: rate limit before auth; constant-time rejection responses
// server.ts — correct ordering: rate limit first, then auth
import express from 'express';
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
import { createClient } from 'redis';
const app = express();
app.use(express.json());
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
// Rate limit keyed on IP *before* we know the user identity.
// Once inside auth, switch to userId-keyed limits.
const preAuthRateLimit = rateLimit({
windowMs: 60_000,
max: 30, // generous limit for pre-auth (covers login probing too)
standardHeaders: true,
legacyHeaders: false,
store: new RedisStore({ sendCommand: (...a) => redis.sendCommand(a) }),
keyGenerator: (req) => `ratelimit:preauth:${req.ip}`,
handler: (req, res) => {
// Always return 429 immediately — no DB lookup
res.set('Retry-After', '60');
return res.status(429).json({ error: 'rate_limit_exceeded' });
},
});
// Auth middleware: constant-time response for all failures
async function authMiddleware(req: any, res: any, next: any) {
const token = req.headers.authorization?.slice(7);
if (!token) {
// Even for missing token, do a fake timing delay to normalize response time
await db.users.findOne({ apiKey: '__nonexistent__' }); // normalize timing
return res.status(401).json({ error: 'unauthorized' });
}
const user = await db.users.findOne({ apiKey: token });
if (!user) return res.status(401).json({ error: 'unauthorized' });
req.user = user;
next();
}
// Per-userId rate limit applied after auth
const postAuthRateLimit = rateLimit({
windowMs: 60_000,
max: 10,
store: new RedisStore({ sendCommand: (...a) => redis.sendCommand(a) }),
keyGenerator: (req) => `ratelimit:audit:${req.user?.id}`,
handler: (_req, res) => {
res.set('Retry-After', '60');
return res.status(429).json({ error: 'rate_limit_exceeded' });
},
});
// CORRECT ORDER: IP rate limit → auth → userId rate limit → handler
app.post('/api/skill/audit_repository',
preAuthRateLimit, // fast, keyed by IP, no DB involved
authMiddleware, // DB lookup — but already past the IP gate
postAuthRateLimit, // per-userId limit after auth succeeds
auditHandler
);
app.listen(3000);
Consistent error bodies matter too: Even with correct ordering, returning different error message strings for “rate limited” vs. “not found” can enable enumeration if an attacker can distinguish rate_limit_exceeded from unauthorized. Use a uniform unauthorized response for all pre-auth rejections, and reserve rate_limit_exceeded only for post-auth paths.
rateLimit() appears after a middleware that performs a database lookup on the credentials.SA-SKL-RATELIMIT summary findings
| Finding ID | Severity | Pattern | Root cause |
|---|---|---|---|
| SA-SKL-RATELIMIT-001 | HIGH | No rate limit on AI-powered endpoint | Missing middleware allows unlimited API calls; each call burns Claude API credits. Fix: express-rate-limit with Redis store keyed by userId; enforce monthly credit budget in DB. |
| SA-SKL-RATELIMIT-002 | HIGH | IP rate limit bypassable via X-Forwarded-For injection | Rate limit key read from req.headers['x-forwarded-for'] is attacker-controlled. Fix: use req.socket.remoteAddress or configure trust proxy correctly and use req.ip. |
| SA-SKL-RATELIMIT-003 | HIGH | Non-atomic Redis GET + INCR race condition | Separate redis.get and redis.incr calls allow distributed burst through the TOCTOU window. Fix: atomic Lua EVAL or ZADD + ZCOUNT sliding window. |
| SA-SKL-RATELIMIT-004 | MEDIUM | Account enumeration via rate limit response timing | Rate limit middleware after auth creates timing difference between existing and non-existing accounts. Fix: IP rate limit before auth; constant-time auth rejection paths. |
SkillAudit detects all four SA-SKL-RATELIMIT patterns through static analysis of your MCP skill’s Express middleware chain, Redis usage patterns, and route handler structure. Run a full audit at skillaudit.dev.