Claude MCP skill WebSocket rate limit bypass, fixed-window boundary attack, and GraphQL complexity security — SA-SKL-RATELIMIT8
Rate limiting that covers HTTP endpoints but ignores semantically equivalent transport paths is a consistent source of unintentional quota bypass in MCP skill deployments. SA-SKL-RATELIMIT8 covers four distinct patterns: the WebSocket upgrade handshake that is not rate-limited even though the HTTP route it shares is; the fixed-window counter that allows a double burst at every window boundary; GraphQL query complexity that is not counted against the per-request quota so a single highly-nested query costs 10x the assumed amount; and the credential-stuffing hardening gap where rate limiting the username field but not the email field allows an attacker to alternate between both and effectively double the allowed attempts. Each pattern can be exploited independently; combined they allow an attacker to exceed the nominal quota by several orders of magnitude from a single client IP.
Rate limiting gaps across protocol transports and query complexity
Most MCP skills are exposed over HTTP and the standard response to abuse is to drop in express-rate-limit on the Express router. This is correct but incomplete. The problems in SA-SKL-RATELIMIT8 each represent a category of gap that is easy to introduce and hard to notice in a standard code review: protocol-level gaps (HTTP vs WebSocket), time-domain gaps (fixed window vs sliding window), semantic-unit gaps (request count vs query cost), and field-coverage gaps (single identifier field vs all identifier fields). A common thread across all four findings is that the rate limit appears to work in test because a simple linear test harness does not probe boundaries, alternate transports, or structure adversarial GraphQL documents. SkillAudit's SA-SKL-RATELIMIT8 rule detects each gap using static analysis of Express route registrations, ws server configuration, and GraphQL schema resolver definitions.
In a Claude MCP skill context, rate limit bypasses are particularly damaging because the resource being protected is usually LLM inference or database I/O that has direct per-unit cost. An attacker who can exceed the rate limit by 100x through WebSocket connection multiplexing is not just annoying; they are driving up infrastructure bills or triggering hard service limits on upstream providers. The GraphQL complexity bypass is especially subtle because a single heavily-nested query document can trigger N+1 resolver chains that issue dozens of downstream LLM calls, each of which the rate limiter counts as one.
username field but not on email field; attacker alternates between username=x and email=x@domain.com to double rate limit allowance per accountRATELIMIT8-001 — WebSocket upgrade not rate-limited on rate-limited HTTP route
When an MCP skill exposes both a REST API and a WebSocket endpoint on the same Express server, the common pattern is to register express-rate-limit as middleware on the HTTP routes. HTTP upgrade requests that initiate a WebSocket connection pass through the Express middleware stack on their initial HTTP handshake, but unless the rate limiter is applied before the upgrade is accepted, the upgrade itself is not counted. Once a WebSocket connection is open, messages flow bidirectionally without further HTTP middleware involvement. An attacker who knows the REST endpoint is rate-limited will instead open many WebSocket connections and send messages at high frequency over each one, achieving effective request rates far above the stated limit. The fix is to apply the rate limit counter to the upgrade handshake request — the req object on a WebSocket upgrade has a valid req.socket.remoteAddress and can be checked against the same Redis counter before calling wss.handleUpgrade().
// VULNERABLE — HTTP route rate-limited; WebSocket upgrade on same server bypasses it
import express from 'express';
import { WebSocketServer } from 'ws';
import http from 'http';
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
const app = express();
app.set('trust proxy', false);
const auditLimiter = rateLimit({
windowMs: 1000, // 1 second window
max: 10,
store: new RedisStore({ sendCommand: (...args) => redis.sendCommand(args) }),
keyGenerator: (req) => req.socket.remoteAddress ?? 'unknown',
handler: (req, res) => res.status(429).json({ error: 'Rate limit exceeded' }),
});
// VULNERABLE: rate limiter only applied to HTTP route
app.post('/api/audit', auditLimiter, handleAudit);
const server = http.createServer(app);
const wss = new WebSocketServer({ noServer: true });
// VULNERABLE: WebSocket upgrade handled without any rate limit check
server.on('upgrade', (req, socket, head) => {
if (req.url === '/ws/audit') {
// No rate limit counter checked here — attacker opens 100 connections freely
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
} else {
socket.destroy();
}
});
// FIXED — rate limit counter checked on upgrade handshake before connection is accepted
import express from 'express';
import { WebSocketServer } from 'ws';
import http from 'http';
import { createClient } from 'redis';
const app = express();
app.set('trust proxy', false);
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const WINDOW_MS = 1000; // 1 second
const MAX_CONNECTIONS = 5; // max concurrent WS connections per IP
const MAX_MSG_PER_SEC = 10; // max messages per second per IP (shared with REST)
// Shared atomic consume: returns { allowed, current }
async function consumeQuota(ip, cost = 1) {
const windowKey = `rl:${ip}:${Math.floor(Date.now() / WINDOW_MS)}`;
const pipeline = redis.multi();
pipeline.incrBy(windowKey, cost);
pipeline.pExpire(windowKey, WINDOW_MS * 2);
const [current] = await pipeline.exec();
return { allowed: current <= MAX_MSG_PER_SEC, current };
}
// Track open connections per IP to limit multiplexing
const connectionsByIp = new Map();
const server = http.createServer(app);
const wss = new WebSocketServer({ noServer: true });
// FIXED: rate limit checked on upgrade before accepting the connection
server.on('upgrade', async (req, socket, head) => {
if (req.url !== '/ws/audit') { socket.destroy(); return; }
const ip = req.socket.remoteAddress ?? 'unknown';
// 1. Connection count limit — prevent opening 100 idle connections
const openConns = connectionsByIp.get(ip) ?? 0;
if (openConns >= MAX_CONNECTIONS) {
socket.write('HTTP/1.1 429 Too Many Connections\r\nRetry-After: 1\r\n\r\n');
socket.destroy();
return;
}
// 2. Rate limit counter shared with the REST endpoint
const { allowed } = await consumeQuota(ip, 1);
if (!allowed) {
socket.write('HTTP/1.1 429 Too Many Requests\r\nRetry-After: 1\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(req, socket, head, (ws) => {
connectionsByIp.set(ip, (connectionsByIp.get(ip) ?? 0) + 1);
ws.on('close', () => {
const n = (connectionsByIp.get(ip) ?? 1) - 1;
if (n <= 0) connectionsByIp.delete(ip);
else connectionsByIp.set(ip, n);
});
// Per-message rate limit check inside the connection handler
ws.on('message', async (data) => {
const { allowed: msgAllowed } = await consumeQuota(ip, 1);
if (!msgAllowed) {
ws.send(JSON.stringify({ error: 'Rate limit exceeded', retryAfterMs: WINDOW_MS }));
return;
}
handleWsMessage(ws, data, req);
});
wss.emit('connection', ws, req);
});
});
Connection vs message limits: You need two separate controls. The connection count limit prevents an attacker from holding open hundreds of idle sockets that consume file descriptors and memory even when no messages are being sent. The per-message rate limit (shared with the REST counter) prevents an attacker with a single connection from sending messages faster than the REST limit allows. Both must be enforced; either alone is insufficient.
RATELIMIT8-002 — Fixed-window boundary burst attack
A fixed-window rate limit divides time into discrete windows (e.g., each 60-second epoch) and allows a fixed number of requests within each window. The counter resets to zero at the exact boundary between windows. This design has a well-known weakness: an attacker who times their requests to straddle the window boundary can send up to 2 * max requests in an interval as short as twice the timing jitter. For a 10-requests-per-minute limit, an attacker sends 10 requests at t=59.9s (consuming the full first window), then sends another 10 requests at t=0.1s in the next window (consuming the full second window). The 20 requests are delivered within 200ms, but no window counter ever exceeds 10. This is not a theoretical attack; it is straightforward to implement with any HTTP client that supports scheduling. The correct defense is a sliding window, implemented in Redis using a sorted set where members are request timestamps and the window is defined as "all timestamps within the last N milliseconds." The ZADD/ZREMRANGEBYSCORE/ZCARD pipeline runs atomically in a Lua script to avoid race conditions.
// VULNERABLE — fixed-window counter; boundary burst allows 2x quota in short interval
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
// windowMs = 60 000 ms, max = 10
// Counter key: rl:{ip}:{Math.floor(Date.now() / 60000)}
// At t=59.9s: key = rl:1.2.3.4:999 — counter goes 1..10 (window full)
// At t= 0.1s: key = rl:1.2.3.4:1000 — counter resets to 0, starts at 1..10 again
// 20 requests delivered in 200ms, no 429 ever returned
const auditLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
store: new RedisStore({ sendCommand: (...args) => redis.sendCommand(args) }),
keyGenerator: (req) => req.socket.remoteAddress ?? 'unknown',
});
// FIXED — sliding window using Redis sorted set; no boundary burst possible
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const WINDOW_MS = 60_000;
const MAX_REQUESTS = 10;
// Lua script: atomically remove expired entries, add current timestamp, count window
const slidingWindowLua = `
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local max = tonumber(ARGV[3])
local expire = tonumber(ARGV[4])
-- Remove all entries outside the sliding window
redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window)
-- Count remaining entries (requests already made in this window)
local count = redis.call('ZCARD', key)
if count < max then
-- Admit: add this request's timestamp as score and member
redis.call('ZADD', key, now, now .. ':' .. math.random(1, 1000000))
redis.call('PEXPIRE', key, expire)
return count + 1 -- current count after admission
else
return -1 -- rejected
end
`;
async function slidingWindowMiddleware(req, res, next) {
const ip = req.socket.remoteAddress ?? 'unknown';
const now = Date.now();
const key = \`rl:sw:\${ip}\`;
const result = await redis.eval(
slidingWindowLua,
{ keys: [key], arguments: [String(now), String(WINDOW_MS), String(MAX_REQUESTS), String(WINDOW_MS * 2)] }
);
if (result === -1) {
// Window full — compute earliest expiry from oldest entry in sorted set
const oldest = await redis.zRange(key, 0, 0, { BY: 'SCORE' });
const retryAfterMs = oldest.length
? Math.max(0, WINDOW_MS - (now - Number(oldest[0].split(':')[0])))
: WINDOW_MS;
res.set('Retry-After', String(Math.ceil(retryAfterMs / 1000)));
return res.status(429).json({
error: 'Rate limit exceeded',
retryAfterMs,
windowMs: WINDOW_MS,
max: MAX_REQUESTS,
});
}
res.set('X-RateLimit-Remaining', String(MAX_REQUESTS - result));
next();
}
app.post('/api/audit', slidingWindowMiddleware, handleAudit);
RATELIMIT8-003 — GraphQL query complexity not counted against rate limit quota
When an MCP skill exposes a GraphQL API, counting each HTTP POST to /graphql as one unit of quota is incorrect. A GraphQL document can request any number of fields in a single request, and each field resolver can independently issue database queries, external HTTP calls, or LLM inference. A query that requests 10 nested fields with 5 resolvers each — a valid structure in many skill APIs — can trigger 50 downstream calls per HTTP request. If the rate limit counts it as one, the effective cost rate is 50x the assumed amount. The graphql-query-complexity library solves this by assigning a complexity score to each field resolver and computing the total complexity of a query document before execution begins. The rate limit middleware is then written to debit complexity units from the Redis counter rather than request units. Fields with expensive resolvers (LLM calls, file I/O) receive higher complexity scores; simple scalar lookups receive lower scores. The total query complexity is validated before execution and rejected if it would exceed the remaining quota in the current window.
// VULNERABLE — each GraphQL POST counts as 1 unit regardless of nested resolver cost
import express from 'express';
import { graphqlHTTP } from 'express-graphql';
import rateLimit from 'express-rate-limit';
const auditLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10, // 10 requests per minute
keyGenerator: (req) => req.socket.remoteAddress ?? 'unknown',
});
// VULNERABLE: a single request with 10 nested resolvers (each calling LLM) = 1 unit
// Real cost can be 10–50x the assumed amount
app.use('/graphql', auditLimiter, graphqlHTTP({ schema, graphiql: false }));
// FIXED — query complexity computed pre-execution; complexity units charged to quota
import express from 'express';
import { graphql, parse, validate } from 'graphql';
import { createComplexityLimitRule, simpleEstimator, fieldExtensionsEstimator } from 'graphql-query-complexity';
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const WINDOW_MS = 60_000;
const MAX_COMPLEXITY_PER_WINDOW = 100; // total complexity units per IP per minute
// Complexity estimators: assign cost per field type
// LLM-calling resolvers cost 10; DB resolvers cost 3; scalar fields cost 1
function getFieldComplexity(field) {
const llmFields = new Set(['runAudit', 'analyzeCode', 'generateReport', 'explainFinding']);
const dbFields = new Set(['listAudits', 'getUser', 'searchSkills', 'fetchHistory']);
if (llmFields.has(field.fieldName)) return 10;
if (dbFields.has(field.fieldName)) return 3;
return 1; // default scalar cost
}
async function complexityRateLimitMiddleware(req, res, next) {
const ip = req.socket.remoteAddress ?? 'unknown';
const body = req.body;
if (!body?.query) return next();
let document;
try { document = parse(body.query); }
catch { return res.status(400).json({ error: 'Invalid GraphQL document' }); }
// Compute complexity before execution
let queryComplexity = 0;
const complexityRule = createComplexityLimitRule(MAX_COMPLEXITY_PER_WINDOW, {
estimators: [
fieldExtensionsEstimator(),
simpleEstimator({ defaultComplexity: 1 }),
],
onComplete: (complexity) => { queryComplexity = complexity; },
});
const validationErrors = validate(schema, document, [complexityRule]);
if (validationErrors.length) {
return res.status(400).json({ errors: validationErrors.map(e => e.message) });
}
// Charge complexity units against sliding window Redis counter
const windowKey = `rl:gql:${ip}:${Math.floor(Date.now() / WINDOW_MS)}`;
const pipeline = redis.multi();
pipeline.incrBy(windowKey, queryComplexity);
pipeline.pExpire(windowKey, WINDOW_MS * 2);
const [newTotal] = await pipeline.exec();
if (newTotal > MAX_COMPLEXITY_PER_WINDOW) {
// Roll back — atomically decrement so the counter reflects actual consumption
await redis.decrBy(windowKey, queryComplexity);
const retryAfter = Math.ceil(WINDOW_MS / 1000);
res.set('Retry-After', String(retryAfter));
return res.status(429).json({
error: 'Query complexity limit exceeded',
queryComplexity,
remainingComplexity: Math.max(0, MAX_COMPLEXITY_PER_WINDOW - (newTotal - queryComplexity)),
retryAfter,
});
}
req.graphqlComplexity = queryComplexity;
next();
}
app.use(express.json());
app.post('/graphql', complexityRateLimitMiddleware, async (req, res) => {
const result = await graphql({ schema, source: req.body.query, variableValues: req.body.variables });
res.json(result);
});
Complexity budget sizing: Start by profiling the actual downstream call count for each resolver type in your schema. If your most expensive resolver issues 3 LLM calls per invocation and each LLM call costs ~200ms, assigning it a complexity of 10 and setting a window budget of 100 gives each IP 10 heavy resolver calls per minute. Document the mapping in your schema via field extensions so the complexity estimator can read it programmatically instead of requiring manual updates to the estimator list as the schema evolves.
RATELIMIT8-004 — Login rate limit on username but not on email field
Credential-stuffing defenses commonly rate-limit the login endpoint by the submitted username to prevent an attacker from trying thousands of passwords against a single account. The gap appears when the login endpoint accepts either a username or an email address as the identifier — a common UX pattern. If the rate limiter only inspects req.body.username for the per-account key, an attacker who knows a target's email address can alternate: request 1 uses username=alice, request 2 uses email=alice@example.com. Each path uses a different Redis key so neither counter reaches the limit. The attacker can try twice as many passwords against the same account before triggering a lockout. The correct fix is to normalize the identifier at middleware entry — look up the user record once to resolve the canonical account ID, then use that account ID as the rate limit key regardless of which field was submitted. This ensures that all login attempts targeting the same account, regardless of whether they arrive via username or email, consume the same counter.
// VULNERABLE — rate limit key is req.body.username; email-keyed attempts uncounted
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10,
store: new RedisStore({ sendCommand: (...args) => redis.sendCommand(args) }),
// VULNERABLE: only username keyed — email field bypasses this counter entirely
keyGenerator: (req) => {
const username = req.body?.username?.toLowerCase() ?? '';
const ip = req.socket.remoteAddress ?? 'unknown';
return username ? \`login:user:\${username}\` : \`login:ip:\${ip}\`;
},
handler: (req, res) => res.status(429).json({ error: 'Too many login attempts' }),
});
// Attacker alternates:
// POST /login { "username": "alice", "password": "attempt1" } — counter: login:user:alice = 1
// POST /login { "email": "alice@example.com", "password": "attempt2" } — counter: login:ip:1.2.3.4 = 1
// username counter and email counter never converge — 2x attempts per window
app.post('/login', loginLimiter, handleLogin);
// FIXED — resolve canonical account ID before keying; both username and email use same counter
import { createClient } from 'redis';
import { db } from './db.js';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const WINDOW_MS = 15 * 60 * 1000;
const MAX_ATTEMPTS = 10;
async function loginRateLimitMiddleware(req, res, next) {
const ip = req.socket.remoteAddress ?? 'unknown';
const { username, email } = req.body ?? {};
// Step 1: resolve canonical account ID from whichever identifier was provided.
// This DB lookup uses a read replica and is indexed on both columns.
let accountId = null;
if (username) {
const row = await db.queryOne('SELECT id FROM users WHERE lower(username) = lower($1)', [username]);
accountId = row?.id ?? null;
} else if (email) {
const row = await db.queryOne('SELECT id FROM users WHERE lower(email) = lower($1)', [email]);
accountId = row?.id ?? null;
}
// Step 2: build rate limit key.
// Known account: key on account ID so username and email paths share one counter.
// Unknown identifier: key on IP to limit enumeration attempts.
const rlKey = accountId
? \`login:account:\${accountId}\`
: \`login:ip:\${ip}\`;
// Step 3: atomic increment against fixed-window counter (or sliding window if preferred).
const windowKey = \`\${rlKey}:\${Math.floor(Date.now() / WINDOW_MS)}\`;
const pipeline = redis.multi();
pipeline.incr(windowKey);
pipeline.pExpire(windowKey, WINDOW_MS * 2);
const [current] = await pipeline.exec();
if (current > MAX_ATTEMPTS) {
const retryAfter = Math.ceil(WINDOW_MS / 1000);
res.set('Retry-After', String(retryAfter));
// Generic error — do not reveal whether the account exists
return res.status(429).json({
error: 'Too many login attempts. Please try again later.',
retryAfter,
});
}
// Store the resolved accountId so the login handler does not need a second lookup
req.resolvedAccountId = accountId;
next();
}
// ALSO: apply a per-IP limit as a secondary defense against distributed attacks
const ipLoginLimiter = rateLimit({
windowMs: WINDOW_MS,
max: 50, // generous per-IP limit to cover legitimate shared-NAT users
keyGenerator: (req) => req.socket.remoteAddress ?? 'unknown',
handler: (req, res) => {
res.set('Retry-After', String(Math.ceil(WINDOW_MS / 1000)));
res.status(429).json({ error: 'Too many requests from this IP' });
},
});
app.post('/login', ipLoginLimiter, loginRateLimitMiddleware, handleLogin);
How SkillAudit detects SA-SKL-RATELIMIT8
SkillAudit's static analysis engine scans MCP skill repositories for all four RATELIMIT8 patterns without executing any code. For RATELIMIT8-001, the scanner identifies server.on('upgrade', ...) handlers and checks whether a Redis-backed rate limit counter is consulted before wss.handleUpgrade() is called; a handler that calls handleUpgrade without a preceding Redis or rate limit call in the same function scope is flagged. For RATELIMIT8-002, the scanner looks for express-rate-limit configurations where windowMs is set but neither a Lua sliding-window script nor a ZADD/ZREMRANGEBYSCORE pattern appears in the codebase, indicating a fixed-window implementation. For RATELIMIT8-003, the scanner detects graphqlHTTP or ApolloServer usage and checks for graphql-query-complexity import in the same module or its transitive dependencies; absence is flagged. For RATELIMIT8-004, the scanner inspects login route handlers for req.body.username and req.body.email access patterns and checks whether both resolve to the same rate limit key string in the keyGenerator function.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
RATELIMIT8-001 | High | WebSocket upgrade handled without rate limit counter check; attacker opens N connections and sends M messages per second, bypassing HTTP rate limit entirely | Check Redis counter on upgrade event before calling handleUpgrade; enforce separate connection count limit per IP |
RATELIMIT8-002 | High | Fixed-window counter resets at boundary; 10-req limit becomes 20 requests in a 200ms burst straddling the window edge | Sliding window via Redis sorted set with ZADD/ZREMRANGEBYSCORE/ZCARD in an atomic Lua script |
RATELIMIT8-003 | High | GraphQL POST counted as 1 unit regardless of nested resolver cost; a 10-resolver query costs 10x the assumed compute | graphql-query-complexity pre-execution check; debit complexity units (not request count) from Redis counter |
RATELIMIT8-004 | High | username and email fields keyed to separate counters; alternating between them doubles effective login attempt quota | Resolve canonical account ID in middleware; key rate limit on account ID so both identifier paths share one counter |
Run SA-SKL-RATELIMIT8 on your skill: Paste your MCP skill's GitHub URL at skillaudit.dev to get a full scan alongside all other SkillAudit checks. The free tier covers public repositories and returns a shareable security badge for your README.