Claude skill rate limiting bypass via account sharing and long-window attacks — SA-SKL-RATELIMIT5
Rate limiting in MCP skills is commonly implemented with the right intent but the wrong key: IP address. When a skill serves enterprise customers, dozens of users from the same office share a single NAT IP, collapsing them all into one counter that exhausts the limit for everyone — a denial-of-service caused by the rate limiter itself. SA-SKL-RATELIMIT5 covers four patterns beyond the basic IP-injection bypass: shared NAT IP key failure on authenticated endpoints; fixed-window burst that allows 1000 requests in one second of an hourly window; GraphQL mutations that bypass rate limits applied only at the REST layer; and rate limit reset or status endpoints that are themselves unprotected.
Why rate limit key selection matters as much as the limit itself
The choice of rate limit key determines what the limit actually protects. IP-based limits work for anonymous endpoints where there is no other identifier — they prevent one network address from overwhelming the server. But for authenticated endpoints, IP is the wrong key: an attacker with a valid account key uses one IP, so IP limits don't constrain them. Meanwhile, an enterprise customer with 50 employees on a shared corporate NAT shares a single IP counter, causing legitimate traffic to exhaust the limit and trigger blocks.
The correct key for authenticated endpoints is the user or API key identifier. The correct key for unauthenticated endpoints (login, registration, password reset) is a combination of IP address and the target value (email or username) to prevent both volumetric attacks and email enumeration. SA-SKL-RATELIMIT5 focuses on the structural errors — wrong key type, fixed-window burst, missing coverage — that allow an attacker to consume a service beyond the intended limits while legitimate users are blocked.
SA-SKL-RATELIMIT5 in scope: RATELIMIT5-001 (rate limit keyed on IP behind shared NAT — collapses 50 office users to one counter, blocks legitimate traffic while failing to constrain per-account abuse), RATELIMIT5-002 (fixed hourly window allows 1000-request burst in the first second — sliding window or token bucket needed), RATELIMIT5-003 (rate limit not applied to GraphQL mutations — only REST endpoints covered), RATELIMIT5-004 (rate limit reset or status endpoint not rate-limited — attacker loops reset to restore budget). Each finding includes SkillAudit detection and correct Node.js fixes.
RATELIMIT5-001 — Rate limit keyed on IP behind shared NAT collapses office users
An MCP skill's API uses express-rate-limit with keyGenerator: (req) => req.ip (or the default, which is equivalent). The skill has a Pro plan limit of 1000 audits per day. A team of 50 engineers at a customer company all work from an office with a single corporate NAT IP address. All 50 users' requests arrive at the server with the same req.ip. The first engineer to reach 1000 requests triggers a 429 response for all 50 engineers simultaneously — even though each individual user has only consumed 20 requests on average. The rate limit is simultaneously too strict (blocks legitimate individual use) and too permissive (a single attacker with a valid API key uses a residential proxy to rotate IPs, bypassing the limit entirely).
The fix for authenticated endpoints is to key the rate limit on the authenticated user or API key identifier. This correctly scopes the limit to the entity that owns the quota. For unauthenticated endpoints that must use IP, supplement with a per-email or per-username key to prevent enumeration attacks even when an attacker uses IP rotation.
// VULNERABLE — rate limit keyed on IP; wrong for authenticated endpoints
import rateLimit from 'express-rate-limit';
import express from 'express';
const app = express();
// IP-based limit applied globally — wrong key for authenticated API
const globalLimiter = rateLimit({
windowMs: 24 * 60 * 60 * 1000, // 24 hours
max: 1000,
// keyGenerator defaults to req.ip — collapses all users behind shared NAT
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Rate limit exceeded' },
});
app.use('/api/', globalLimiter);
// Now: 50 engineers at a company all share one NAT IP.
// Engineer 1 makes 50 requests → counter at 50 (for the IP)
// Engineers 2-20 each make 50 requests → counter at 1000 (for the IP)
// Engineer 21 makes first request → 429 for ALL 50 users on that IP
// Meanwhile, an attacker with 1000 residential proxies rotates IPs
// and never hits the limit at all
// FIXED — user ID key for authenticated endpoints; IP+email for auth endpoints
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
import { createClient } from 'redis';
const redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();
// Authenticated endpoints: key on user ID or API key — correct per-account limit
const authenticatedLimiter = rateLimit({
windowMs: 24 * 60 * 60 * 1000, // 24 hours
max: 1000,
// Key on the authenticated user/API key — not IP
// This correctly scopes the limit to the quota-owning entity
keyGenerator: (req) => {
// req.user is set by authentication middleware before this limiter runs
const userId = (req as any).user?.userId;
if (!userId) {
// Unauthenticated request to an authenticated endpoint — 401, don't rate limit
// (the 401 response from auth middleware will handle this)
return 'unauthenticated';
}
return `user:${userId}`;
},
store: new RedisStore({
// @ts-expect-error — RedisStore types
sendCommand: (...args: string[]) => redisClient.sendCommand(args),
}),
handler: (req, res) => {
res.status(429).json({
error: 'Rate limit exceeded for your account',
limit: 1000,
resetAt: new Date(Date.now() + (res.getHeader('RateLimit-Reset') as number) * 1000).toISOString(),
});
},
});
// Unauthenticated auth endpoints (login, signup): key on IP + email
// to prevent both volumetric and enumeration attacks
const authEndpointLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10,
keyGenerator: (req) => {
// Combine IP and target email for per-identity protection even with IP rotation
const email = (req.body?.email || '').toLowerCase().trim();
const ip = req.ip || 'unknown';
// Hash the combination — prevents logging sensitive email addresses in rate limit keys
const { createHash } = require('crypto');
return createHash('sha256').update(`${ip}:${email}`).digest('hex').slice(0, 32);
},
store: new RedisStore({
// @ts-expect-error
sendCommand: (...args: string[]) => redisClient.sendCommand(args),
}),
skipSuccessfulRequests: false, // Count successful logins (enumeration via success/failure timing)
});
req.user.userId or the API key identifier set by authentication middleware, reserving IP-based limits for unauthenticated endpoints, and combining IP with the target email for auth endpoints to prevent enumeration. Detection: SkillAudit flags express-rate-limit configurations on authenticated route groups that use req.ip as the key without also checking for an authenticated user identifier.RATELIMIT5-002 — Fixed hourly window allows full quota burst in first second
An MCP skill's free plan allows 100 audits per hour. The rate limit is implemented as a fixed-window counter: at the start of each clock hour, the counter resets to 0. This allows an attacker to make all 100 requests in the first second of the hour, then make another 100 requests in the first second of the next hour — effectively sustaining a rate of 200 requests per 2 seconds while technically staying "within the limit." For a service with per-audit LLM API costs, this burst behavior creates sudden cost spikes and can exhaust upstream API quotas. For services with database-backed storage, bursts at the second scale can exceed connection pool capacity.
The fix is to replace the fixed-window counter with a sliding window or token bucket algorithm. The rate-limiter-flexible library provides a Redis-backed sliding window counter that distributes the limit evenly across time: a 100/hour limit with a sliding window means 100 requests in any 60-minute window, not 100 in the first second of a fixed clock-hour window.
// VULNERABLE — fixed-window counter allows burst
import rateLimit from 'express-rate-limit';
const auditLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour window — FIXED window (resets on the clock hour)
max: 100, // 100 requests per window
// VULNERABLE to burst:
// - Hour starts at 00:00:00
// - Attacker makes 100 requests at 00:00:00.001 — counter = 100, limit reached
// - Attacker waits for window reset at 01:00:00.000
// - Attacker makes 100 more requests at 01:00:00.001
// - Net rate: 200 requests in ~2ms (100 at end of window + 100 at start of next)
// Also: skipFailedRequests means failed audits don't count against limit
// so an attacker that intentionally submits invalid input never depletes their budget
skipFailedRequests: true, // BAD: attacker submits 1000 invalid requests for free
});
// FIXED — sliding window counter via rate-limiter-flexible
import { RateLimiterRedis } from 'rate-limiter-flexible';
import { createClient } from 'redis';
import type { Request, Response, NextFunction } from 'express';
const redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();
// Sliding window: a request at time T consumes 1 point from the window [T-3600s, T]
// No burst is possible — the window moves continuously with each request
const slidingWindowLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: 'audit_limit',
points: 100, // 100 audits allowed
duration: 3600, // Per 3600 seconds (1 hour)
// duration is in seconds, not milliseconds — rate-limiter-flexible uses seconds
// IMPORTANT: do not use inmemoryBlockOnConsumed — that creates a fixed-window behavior
// for the in-memory block. The Redis sliding window is the correct mechanism.
});
// Token bucket variant (alternative) — allows controlled burst up to bucket capacity
// then refills at a steady rate. Use this if some burst is acceptable.
const tokenBucketLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: 'audit_bucket',
points: 10, // Bucket capacity: 10 requests can burst
duration: 360, // Refill rate: 10 points per 360 seconds = ~1.67/min steady rate
// Over 1 hour: (3600/360)*10 = 100 requests if evenly spaced
// But allows bursting up to 10 at once — explicit, documented allowance
});
export function auditRateLimitMiddleware(
req: Request, res: Response, next: NextFunction
) {
const userId = (req as any).user?.userId;
if (!userId) return res.status(401).json({ error: 'Authentication required' });
slidingWindowLimiter.consume(userId, 1)
.then((rateLimiterRes) => {
// Set standard rate limit response headers
res.setHeader('RateLimit-Limit', 100);
res.setHeader('RateLimit-Remaining', rateLimiterRes.remainingPoints);
res.setHeader('RateLimit-Reset', new Date(Date.now() + rateLimiterRes.msBeforeNext).toISOString());
next();
})
.catch((rateLimiterRes) => {
res.setHeader('Retry-After', Math.round(rateLimiterRes.msBeforeNext / 1000));
res.setHeader('RateLimit-Limit', 100);
res.setHeader('RateLimit-Remaining', 0);
res.status(429).json({
error: 'Rate limit exceeded',
retryAfter: Math.round(rateLimiterRes.msBeforeNext / 1000),
});
});
}
express-rate-limit's fixed window with a sliding-window counter via RateLimiterRedis from rate-limiter-flexible, or a token bucket if limited burst is acceptable. Detection: SkillAudit flags express-rate-limit configurations with windowMs set to multiples of one hour without an accompanying sliding-window store that prevents fixed-window boundary bursts.RATELIMIT5-003 — Rate limit not applied to GraphQL mutations
An MCP skill exposes both a REST API (POST /api/audits) and a GraphQL endpoint (POST /graphql) that includes a runAudit mutation. The rate limiter is applied as Express middleware on the /api/ path prefix. The GraphQL endpoint at /graphql does not fall under this prefix and is therefore not rate-limited. An attacker who discovers the GraphQL endpoint can call the runAudit mutation without any per-user limit, consuming LLM API budget and storage at will. This is especially common when GraphQL is added after the initial REST API as an additional interface: the developer adds authentication middleware to the GraphQL handler but forgets to add the rate limiter, reasoning that "the data layer validates permissions."
The fix is to apply the rate limiter at the HTTP layer before any routing — not on a path-prefix basis — so that all endpoints including GraphQL mutations are covered. Alternatively, implement per-operation rate limiting inside the GraphQL resolver for mutation operations, counting each mutation call against the same per-user quota as REST audit calls.
// VULNERABLE — rate limit applied only to /api/; GraphQL mutations unprotected
import express from 'express';
import rateLimit from 'express-rate-limit';
import { createHandler } from 'graphql-http/lib/use/express';
import { schema } from './schema'; // GraphQL schema with runAudit mutation
const app = express();
// Rate limiter applied to REST API only
const auditLimiter = rateLimit({
windowMs: 60 * 60 * 1000,
max: 100,
keyGenerator: (req) => (req as any).user?.userId || req.ip,
});
app.use('/api/', auditLimiter); // REST endpoints: rate-limited
app.use('/api/audits', auditRouter); // POST /api/audits → limited
// GraphQL endpoint added later — rate limiter NOT applied here
app.use('/graphql', authenticate, createHandler({ schema }));
// mutation { runAudit(url: "...") { ... } } → unlimited!
// An attacker can call this 10,000 times/minute with no throttling
// FIXED — rate limiter at HTTP layer before routing; also GraphQL operation check
import express from 'express';
import { RateLimiterRedis } from 'rate-limiter-flexible';
import { createClient } from 'redis';
import { createHandler } from 'graphql-http/lib/use/express';
const redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();
const app = express();
// Option 1: Apply rate limiter globally at the HTTP layer — covers ALL endpoints
// including /graphql, /api/, /webhooks/, etc.
const globalAuditLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: 'global_audit',
points: 100,
duration: 3600,
});
// Global middleware — runs before ALL routes
app.use(authenticate); // Set req.user first
app.use(async (req, res, next) => {
const userId = (req as any).user?.userId;
if (!userId) return next(); // Unauthenticated — let auth middleware handle
try {
await globalAuditLimiter.consume(userId, 1);
next();
} catch {
res.status(429).json({ error: 'Rate limit exceeded' });
}
});
// Option 2: Per-operation rate limiting inside GraphQL resolvers
// Use this when different operations have different costs (e.g., runAudit costs more than getAudit)
const resolvers = {
Mutation: {
runAudit: async (parent: unknown, args: { url: string }, context: { userId: string; redis: typeof redisClient }) => {
// Rate check inside the resolver — covers all execution paths to this mutation
const limiter = new RateLimiterRedis({
storeClient: context.redis,
keyPrefix: 'mutation_runAudit',
points: 10, // 10 runAudit mutations per 10 minutes (more expensive operation)
duration: 600,
});
try {
await limiter.consume(context.userId, 1);
} catch {
throw new Error('Rate limit exceeded for runAudit — try again in a few minutes');
}
// Proceed with audit execution...
return runAuditImpl(args.url);
},
},
};
/api/), leaving the GraphQL endpoint at /graphql unprotected — an attacker who discovers the GraphQL endpoint can call runAudit mutations without any per-user quota, consuming LLM API budget and storage at arbitrary volume; fix by applying the rate limiter as global Express middleware before all routing (not on a path prefix), or by implementing per-operation rate limiting inside GraphQL mutation resolvers using the same Redis-backed counter as REST endpoints. Detection: SkillAudit flags Express applications that have both a /graphql route and a rate limiter applied only to a /api/ path prefix without also covering the GraphQL route.RATELIMIT5-004 — Rate limit reset endpoint not rate-limited
Some MCP skill implementations include a rate limit status or reset endpoint for administrative and debugging purposes — for example, GET /api/rate-limit/status to check remaining quota or POST /api/rate-limit/reset to clear a user's counter after a support complaint. If the reset endpoint is protected only by admin role authentication but not separately rate-limited, an attacker who obtains or escalates to admin access can call the reset endpoint in a loop — restoring their audit quota to zero instantly and running unlimited audits while the reset loop runs. The issue is not specific to reset endpoints: any endpoint that modifies rate limit state without its own rate limit is vulnerable to this pattern.
The fix is straightforward: apply a strict rate limit to the reset endpoint itself — for example, 10 resets per hour per admin user, enforced by a separate Redis key. Alternatively, remove the reset endpoint from the production API and implement quota resets as a backoffice operation that requires human review before execution.
// VULNERABLE — rate limit reset endpoint not rate-limited
import express from 'express';
import { RateLimiterRedis } from 'rate-limiter-flexible';
import { createClient } from 'redis';
const redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();
const auditLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: 'audit',
points: 100,
duration: 3600,
});
const router = express.Router();
// Admin auth middleware: checks for admin role in JWT
router.use(requireAdminRole);
// Status endpoint: OK to expose but could be used for timing analysis
router.get('/rate-limit/status/:userId', async (req, res) => {
const { userId } = req.params;
const limiterRes = await auditLimiter.get(userId);
res.json({
remainingPoints: limiterRes?.remainingPoints ?? 100,
msBeforeNext: limiterRes?.msBeforeNext ?? 0,
});
});
// VULNERABLE: reset endpoint has no rate limit of its own
// Attacker with admin access can call POST /api/admin/rate-limit/reset/victimUserId
// continuously, resetting their own counter before it depletes
router.post('/rate-limit/reset/:userId', async (req, res) => {
const { userId } = req.params;
// No limit on how many times this can be called — attacker loops it
await auditLimiter.delete(userId);
res.json({ message: `Rate limit reset for user ${userId}` });
});
// FIXED — strict rate limit on reset endpoint; audit log on use
import express from 'express';
import { RateLimiterRedis } from 'rate-limiter-flexible';
import { createClient } from 'redis';
const redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();
const auditLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: 'audit',
points: 100,
duration: 3600,
});
// Separate rate limiter for the reset endpoint itself
// Strict: 5 resets per hour per admin user — enough for support tickets, not for abuse
const resetLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: 'admin_reset_op',
points: 5,
duration: 3600,
});
const router = express.Router();
router.use(requireAdminRole);
router.post('/rate-limit/reset/:userId', async (req, res) => {
const adminId = (req as any).user.userId;
const { userId } = req.params;
// Rate-limit the reset operation itself — keyed on the admin performing the reset
try {
await resetLimiter.consume(adminId, 1);
} catch {
return res.status(429).json({
error: 'Rate limit reset quota exceeded — maximum 5 resets per hour per admin',
});
}
// Audit log — every reset is recorded with who did it and why
await db.query(
'INSERT INTO admin_audit_log (admin_id, action, target_user_id, reason, created_at) VALUES ($1, $2, $3, $4, NOW())',
[adminId, 'rate_limit_reset', userId, req.body.reason || 'no reason provided']
);
await auditLimiter.delete(userId);
res.json({
message: `Rate limit reset for user ${userId}`,
resetBy: adminId,
// Do not echo userId verbatim in response — prevents timing-based enumeration
// of which users have high audit usage
});
});
POST /rate-limit/reset endpoint protected only by admin role authentication without a rate limit on the reset operation itself — an attacker who gains admin access (via JWT3 algorithm confusion, privilege escalation, or compromised admin credential) can loop the reset endpoint to continuously restore their own audit quota to full, running unlimited audits at no cost; fix by applying a separate strict rate limiter (5 resets/hour per admin) to the reset endpoint, logging every reset with the admin identity and stated reason, and considering whether a production reset endpoint is necessary or should be replaced by a backoffice database operation. Detection: SkillAudit flags admin route handlers that call rate limiter delete() or resetKey() methods without a separate rate limiter middleware on the reset route itself.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| RATELIMIT5-001 | HIGH | IP key on authenticated endpoints — collapses 50 office users to one counter; blocks legitimate users, fails to constrain per-account abusers with rotating IPs | Key on req.user.userId for authenticated endpoints; IP+email hash for auth endpoints |
| RATELIMIT5-002 | HIGH | Fixed-window counter allows full quota burst at clock-hour boundary — 100 requests in 2ms then wait for reset | Sliding window via RateLimiterRedis from rate-limiter-flexible |
| RATELIMIT5-003 | HIGH | Rate limit on /api/ prefix only — GraphQL endpoint at /graphql is unprotected; runAudit mutations run without quota |
Global middleware before all routing, or per-operation limiter inside GraphQL mutation resolvers |
| RATELIMIT5-004 | HIGH | Rate limit reset endpoint unprotected — admin looping POST /rate-limit/reset restores quota continuously |
Separate strict limiter (5/hour) on reset endpoint; audit log all resets |
Related patterns: SA-SKL-RATELIMIT4 covers distributed bypass via IP rotation and X-Forwarded-For header injection — the complementary attack to RATELIMIT5-001's NAT collapse. SA-SKL-GRAPHQL3 covers GraphQL query depth and batch attack surfaces including per-operation limits. SA-SKL-ASYNCRACE3 covers async race conditions including check-then-act quota bypasses via concurrent requests.