Claude skill rate limit bypass via X-Forwarded-For header spoofing and batch endpoints — SA-SKL-RATELIMIT7
Rate limiting in MCP skill deployments is undermined in four distinct ways that are easy to miss during code review. SA-SKL-RATELIMIT7 covers the full set: the proxied-setup problem where the X-Forwarded-For header overrides req.ip so any client can rotate identity by cycling header values; the JWT sub rotation attack where unlimited free-account creation gives each account fresh quota; the missing Retry-After header that causes well-intentioned clients to hammer the server in a tight retry loop exhausting the connection pool; and the batch endpoint that accepts 50 audit items in a single request but was never wired to the same rate limit counter as the single-item endpoint. Each of these bypasses is independently exploitable and they can be combined for maximum impact.
Rate limit architecture in MCP skill deployments
An MCP skill's rate limiting sits at the intersection of three concerns: who the caller is (identity keying), how many requests constitute a quota window (counter storage), and what happens when the limit fires (response handling). In practice, most deployments use express-rate-limit with a Redis store and a keyGenerator function that extracts an identity from the request. The problems in SA-SKL-RATELIMIT7 all stem from one of two root causes: the identity extracted by keyGenerator is controllable by the caller, or the rate limit is applied to only a subset of the semantically equivalent request paths. Both root causes allow an attacker to consume unbounded quota on a resource-constrained backend — in a skill context that means unbounded LLM inference calls, database writes, or file processing operations that accrue direct cost.
keyGenerator uses req.ip on a proxied setup; X-Forwarded-For overrides req.ip; attacker rotates XFF values to get a fresh counter on every requestsub claim; attacker creates unlimited free accounts each with a new sub; every new account restores full quotaRetry-After header; conformant clients retry immediately in a tight loop exhausting the backend connection poolPOST /api/audits rate limited but POST /api/batch not rate limited; batch accepts 50 audit items per request; single-audit quota has no effect on batch callersRATELIMIT7-001 — X-Forwarded-For overrides req.ip on proxied setup
When Express runs behind a load balancer or reverse proxy, the client's true IP is forwarded in the X-Forwarded-For header. Express exposes this as req.ip only if app.set('trust proxy', N) is configured, where N is the number of trusted upstream hops. If trust proxy is set to true (or to a value greater than the actual proxy depth), Express trusts the entire X-Forwarded-For chain including the client-supplied leftmost value. An attacker who can send arbitrary headers simply sets X-Forwarded-For: 1.2.3.4, then X-Forwarded-For: 5.6.7.8, and so on — each request appears to come from a different IP address, so each one starts with a fresh rate limit counter. The fix is to disable trust proxy and use req.socket.remoteAddress as the rate limit key, which is the TCP-level IP that cannot be spoofed by the client. When a known proxy count is required, set trust proxy to the exact integer hop count so only the outermost forwarded IP is trusted.
// VULNERABLE — trust proxy true means req.ip follows X-Forwarded-For from client
import express from 'express';
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
const app = express();
// VULNERABLE: trust proxy true makes req.ip follow the full XFF chain
app.set('trust proxy', true);
const auditLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
store: new RedisStore({ sendCommand: (...args) => redisClient.sendCommand(args) }),
// VULNERABLE: keyGenerator uses req.ip which is overridden by XFF header
keyGenerator: (req) => req.ip,
handler: (req, res) => res.status(429).json({ error: 'Rate limit exceeded' }),
});
app.post('/api/audits', auditLimiter, handleAudit);
// FIXED — trust proxy false; keyGenerator uses req.socket.remoteAddress (TCP-level IP)
import express from 'express';
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
const app = express();
// FIXED: trust proxy false — req.ip is not overridden by XFF header
app.set('trust proxy', false);
// If you have exactly one trusted upstream proxy, use:
// app.set('trust proxy', 1); // trusts only the outermost XFF hop added by your proxy
const auditLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
store: new RedisStore({ sendCommand: (...args) => redisClient.sendCommand(args) }),
// FIXED: use TCP-level remote address which cannot be spoofed by the client
keyGenerator: (req) => req.socket.remoteAddress ?? 'unknown',
standardHeaders: true, // include RateLimit-* headers in responses
legacyHeaders: false,
handler: (req, res) => {
const retryAfter = Math.ceil(req.rateLimit.resetTime / 1000 - Date.now() / 1000);
res.set('Retry-After', String(Math.max(retryAfter, 1)));
res.status(429).json({ error: 'Rate limit exceeded', retryAfter });
},
});
app.post('/api/audits', auditLimiter, handleAudit);
RATELIMIT7-002 — JWT sub rotation via unlimited free-account creation
Using the JWT sub claim as the rate limit key is a natural choice — it identifies the authenticated user and prevents one user from consuming another user's quota. The flaw appears when account creation is free and unlimited. An attacker automates account registration, obtains a new JWT for each account, and makes exactly the allowed number of requests per account before rotating to the next. With 10 requests per minute per account, 100 accounts provide 1000 requests per minute. The rate limit counter never fires because each account's counter resets independently. The correct architecture is a two-layer check: a per-IP limit (using the socket address, not XFF) catches rapid account rotation from the same client, and a per-plan-tier limit governs the semantic quota (free, pro, team) so that free accounts as a class are collectively limited regardless of how many exist. Both checks must pass independently — neither alone is sufficient.
// VULNERABLE — rate limit key is JWT sub; rotating accounts bypasses quota
import rateLimit from 'express-rate-limit';
const auditLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
// VULNERABLE: keyed by JWT sub — create new account, get new sub, fresh counter
keyGenerator: (req) => req.user?.sub ?? req.ip,
handler: (req, res) => res.status(429).json({ error: 'Rate limit exceeded' }),
});
app.post('/api/audits', authenticate, auditLimiter, handleAudit);
// FIXED — dual-layer: per-IP limit + per-plan-tier limit; both must pass
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
const store = () => new RedisStore({ sendCommand: (...args) => redisClient.sendCommand(args) });
// Layer 1: per-IP limit — catches rapid account rotation from the same client
const ipLimiter = rateLimit({
windowMs: 60 * 1000,
max: 30, // generous enough for a single human, tight enough to block rotation
store: store(),
keyGenerator: (req) => req.socket.remoteAddress ?? 'unknown',
skipSuccessfulRequests: false,
});
// Layer 2: per-plan-tier limit — free tier collectively constrained
const planLimiter = rateLimit({
windowMs: 60 * 1000,
max: (req) => {
// Different quotas per plan — both sub and plan tier must be in JWT claims
const plan = req.user?.plan ?? 'free';
return plan === 'team' ? 500 : plan === 'pro' ? 100 : 10;
},
store: store(),
// Key by sub so each account gets its own counter, but plan-tier cap applies
keyGenerator: (req) => `${req.user?.plan ?? 'free'}:${req.user?.sub ?? 'anon'}`,
handler: (req, res) => {
const retryAfter = Math.ceil(req.rateLimit.resetTime / 1000 - Date.now() / 1000);
res.set('Retry-After', String(Math.max(retryAfter, 1)));
res.status(429).json({ error: 'Plan quota exceeded', plan: req.user?.plan });
},
});
// Both limits applied in series — either one can reject the request
app.post('/api/audits', authenticate, ipLimiter, planLimiter, handleAudit);
RATELIMIT7-003 — Retry-After header absent on 429 responses
RFC 6585 and RFC 7231 specify that a 429 Too Many Requests response should include a Retry-After header indicating when the client may retry. When this header is absent, a well-implemented client library that follows HTTP semantics — or a user clicking retry — will re-send the request immediately. If many clients are simultaneously rate-limited and all retry without backoff, the resulting burst can exhaust the server's available connection pool, triggering a denial-of-service condition that affects even clients who have not exceeded their quota. The impact is amplified in an MCP skill context where multiple Claude agent instances may be calling the same skill endpoint concurrently. The fix is straightforward: in the rate limiter's handler function, compute the seconds until the window resets and set res.set('Retry-After', retryAfterSeconds) before sending the 429 response. The express-rate-limit standardHeaders: true option also sets RateLimit-Reset which serves the same purpose for clients that check it.
// VULNERABLE — 429 handler omits Retry-After; clients retry immediately
const auditLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
store: new RedisStore({ sendCommand: (...args) => redisClient.sendCommand(args) }),
keyGenerator: (req) => req.socket.remoteAddress ?? 'unknown',
// VULNERABLE: handler sends 429 with no Retry-After header
handler: (req, res) => {
res.status(429).json({ error: 'Too many requests' });
// Missing: res.set('Retry-After', ...)
// Clients retry immediately; connection pool exhausted under load
},
});
// FIXED — Retry-After set in handler; standardHeaders exposes RateLimit-Reset
const auditLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
store: new RedisStore({ sendCommand: (...args) => redisClient.sendCommand(args) }),
keyGenerator: (req) => req.socket.remoteAddress ?? 'unknown',
// FIXED: expose standard RateLimit-* headers on all responses
standardHeaders: true,
legacyHeaders: false,
handler: (req, res) => {
// req.rateLimit.resetTime is a Date object set by express-rate-limit
const resetMs = req.rateLimit.resetTime?.getTime() ?? (Date.now() + 60_000);
const retryAfterSeconds = Math.max(1, Math.ceil((resetMs - Date.now()) / 1000));
// RFC 6585 §4: Retry-After in seconds (integer) or HTTP-date format
res.set('Retry-After', String(retryAfterSeconds));
res.status(429).json({
error: 'Too many requests',
retryAfter: retryAfterSeconds,
resetAt: new Date(resetMs).toISOString(),
});
},
});
RATELIMIT7-004 — Batch endpoint not sharing the rate limit counter
When a single-item audit endpoint is rate limited but a batch endpoint that accepts an array of audit items is not, the rate limit is entirely ineffective for callers who use the batch path. A free-tier account limited to 10 requests per minute on POST /api/audits can call POST /api/batch with an array of 50 audit items and consume 50 units of backend compute in a single HTTP request. If the batch endpoint's default page size is 100 items, a single batch call exceeds the per-minute quota by 10x. The correct fix is to treat each item in a batch as one unit of quota consumption — the same Redis counter used by the single-item endpoint is debited by the item count of the batch before processing begins. If the remaining quota is less than the requested batch size, the entire batch is rejected with a 429 indicating how many items could have been accepted in the remaining window.
// VULNERABLE — /api/audits rate limited; /api/batch not rate limited at all
import rateLimit from 'express-rate-limit';
const auditLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
keyGenerator: (req) => req.socket.remoteAddress ?? 'unknown',
});
// FIXED for single endpoint only — batch endpoint completely unprotected
app.post('/api/audits', authenticate, auditLimiter, handleAudit);
// VULNERABLE: no rate limit middleware — batch callers bypass quota entirely
app.post('/api/batch', authenticate, handleBatch);
// FIXED — batch endpoint debits the same Redis counter by item count
import { createClient } from 'redis';
const redisClient = createClient({ url: process.env.REDIS_URL });
const WINDOW_MS = 60 * 1000;
const MAX_PER_WINDOW = 10;
// Shared helper: atomically consume `cost` units from the rate limit counter
async function consumeQuota(key, cost) {
const windowKey = `rl:${key}:${Math.floor(Date.now() / WINDOW_MS)}`;
const pipeline = redisClient.multi();
pipeline.incrBy(windowKey, cost);
pipeline.pExpire(windowKey, WINDOW_MS);
const [current] = await pipeline.exec();
const remaining = Math.max(0, MAX_PER_WINDOW - current);
return { current, remaining, allowed: current <= MAX_PER_WINDOW };
}
// Single-item endpoint: costs 1 unit
app.post('/api/audits', authenticate, async (req, res, next) => {
const key = req.socket.remoteAddress ?? 'unknown';
const { allowed, remaining } = await consumeQuota(key, 1);
if (!allowed) {
res.set('Retry-After', String(Math.ceil(WINDOW_MS / 1000)));
return res.status(429).json({ error: 'Rate limit exceeded', remaining: 0 });
}
req.rateLimitRemaining = remaining;
next();
}, handleAudit);
// Batch endpoint: costs N units where N = items.length
app.post('/api/batch', authenticate, async (req, res, next) => {
const items = req.body?.items;
if (!Array.isArray(items) || items.length === 0) {
return res.status(400).json({ error: 'items must be a non-empty array' });
}
const MAX_BATCH = 50;
if (items.length > MAX_BATCH) {
return res.status(400).json({ error: `Batch size exceeds maximum of ${MAX_BATCH}` });
}
const key = req.socket.remoteAddress ?? 'unknown';
const { allowed, remaining } = await consumeQuota(key, items.length);
if (!allowed) {
const retryAfter = Math.ceil(WINDOW_MS / 1000);
res.set('Retry-After', String(retryAfter));
return res.status(429).json({
error: 'Rate limit exceeded for batch',
requestedItems: items.length,
remaining: 0,
retryAfter,
});
}
req.rateLimitRemaining = remaining;
next();
}, handleBatch);
Related patterns: The earlier SA-SKL-RATELIMIT6 covers sliding window implementation correctness in Redis Lua scripts and the race conditions that cause counter drift. For IP-based controls that interact with proxy headers more broadly, see the SSRF detection patterns in SA-SKL-SSRF9. JWT claim manipulation as an authentication bypass beyond rate limiting is covered in SA-SKL-JWT4.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
RATELIMIT7-001 | High | keyGenerator uses req.ip; trust proxy true makes req.ip follow attacker-controlled X-Forwarded-For | trust proxy false; use req.socket.remoteAddress as rate limit key; or set trust proxy 1 with known proxy count |
RATELIMIT7-002 | High | Rate limit keyed by JWT sub; unlimited free-account creation gives fresh counter per account | Per-IP limit (socket address) AND per-plan-tier limit; both checks applied in series |
RATELIMIT7-003 | Medium | 429 response omits Retry-After; clients retry immediately; connection pool exhausted under concurrent load | res.set('Retry-After', retryAfterSeconds) in handler; standardHeaders: true for RateLimit-Reset |
RATELIMIT7-004 | High | POST /api/batch not rate limited; accepts 50 items per request; single-audit quota has no effect | Batch debits same Redis counter by item count; reject entire batch if remaining quota insufficient |