Claude skill GraphQL query depth and batch attack security — SA-SKL-GRAPHQL3
GraphQL's flexible query language is a double-edged sword for MCP skills: the same expressiveness that makes it useful for Claude to fetch exactly the data it needs also makes it trivial to craft queries that exhaust server resources. SA-SKL-GRAPHQL3 covers four patterns: unbounded query depth that multiplies resolver calls exponentially; batched requests that fit 100 operations into one HTTP request to bypass single-request rate limits; introspection enabled in production that maps the full schema for attackers; and resolvers that perform N+1 database queries for each item in a list, turning a pagination query into a database overload.
GraphQL resource exhaustion vs information disclosure
GraphQL attacks fall into two categories. Resource exhaustion attacks — query depth abuse, field complexity attacks, and batch abuse — aim to degrade availability by forcing the server to perform exponentially expensive work. Information disclosure attacks — introspection and field guessing — aim to map the schema to identify mutation endpoints, deprecated authentication fields, or internal administrative types that are not documented in public API references. SA-SKL-GRAPHQL3 addresses two of each type, as they require distinct mitigations: depth and batch limits are enforced by middleware before execution, while introspection and N+1 issues require schema-level and resolver-level changes.
The practical severity of depth attacks depends on the schema's cyclicity: a schema where User has a friends field that returns a list of User objects is cyclical and allows infinite nesting. A depth of 10 on such a schema causes 10 levels of User → friends → User → friends resolution, which is 2^10 = 1024 resolver calls for a fan-out of 2 friends per user. A depth of 20 causes over a million. The graphql-depth-limit middleware enforces a maximum depth before execution begins, adding negligible overhead.
SA-SKL-GRAPHQL3 in scope: GRAPHQL3-001 (unbounded query depth — exponential resolver multiplication), GRAPHQL3-002 (batch operations without per-operation rate limiting), GRAPHQL3-003 (introspection enabled in production), GRAPHQL3-004 (N+1 resolver without DataLoader batching). Each finding includes SkillAudit detection rules and correct Node.js / graphql-js fixes.
GRAPHQL3-001 — Unbounded query depth exhausts CPU and DB connections
An MCP skill's GraphQL API has a cyclical schema: the Audit type has a relatedAudits field that returns a list of Audit objects, each of which also has relatedAudits. Without a depth limit, a client can submit a query with 20 levels of relatedAudits { relatedAudits { ... } } nesting. If each Audit has 3 related audits, 20 levels of nesting requires 3^20 = 3.5 billion resolver invocations. Even if each invocation is fast, the CPU and database connection pool are exhausted in seconds. This is a low-sophistication denial-of-service that requires no authentication if the GraphQL endpoint is public, and requires only a compromised skill token if the endpoint is authenticated.
The graphql-depth-limit package provides a validation rule that counts the nesting depth of a parsed GraphQL document and rejects it before execution if the depth exceeds the configured maximum. A maximum depth of 5 is sufficient for most MCP skill APIs and covers all legitimate query patterns. For schemas with legitimate deep nesting (e.g., organizational hierarchy traversal), a depth of 7–8 is usually sufficient. Fragment spreads are counted toward the depth; introspection queries have their own depth and are not affected.
// VULNERABLE — GraphQL endpoint with no depth limit
import { createServer } from 'http';
import { createYoga } from 'graphql-yoga';
import { schema } from './schema'; // Cyclical schema: Audit.relatedAudits: [Audit]
const yoga = createYoga({
schema,
// No depth limit — a client can submit arbitrarily deeply nested queries
// Query that exhausts the server:
// query { audit(id: "1") { relatedAudits { relatedAudits { relatedAudits {
// relatedAudits { relatedAudits { relatedAudits { relatedAudits {
// relatedAudits { relatedAudits { relatedAudits { title } } } } } } } } } } } }
// 10 levels deep on a schema with branching factor 3 = 59,049 resolver calls
// 20 levels deep = 3,486,784,401 resolver calls
});
createServer(yoga).listen(4000);
// FIXED — depth limit middleware + query complexity limit as defense-in-depth
import { createServer } from 'http';
import { createYoga } from 'graphql-yoga';
import depthLimit from 'graphql-depth-limit';
import { schema } from './schema';
const yoga = createYoga({
schema,
validationRules: [
// Block queries deeper than 5 levels — covers all legitimate MCP skill query patterns
depthLimit(5, { ignore: [/__/] }), // Ignore introspection fields (__ prefix)
],
// Additional defense: limit the size of the query document string
// graphql-yoga exposes this via the requestTextLimit option
// Prevents memory exhaustion from extremely large query strings before parsing
});
// defense-in-depth: also apply a query complexity limit
// graphql-query-complexity counts field weights and rejects expensive queries
import { createComplexityLimitRule } from 'graphql-validation-complexity';
const yogaWithComplexity = createYoga({
schema,
validationRules: [
depthLimit(5, { ignore: [/__/] }),
createComplexityLimitRule(1000, {
// Assign costs: simple scalar = 1, list fields = 10, expensive resolvers = 50
scalarCost: 1,
objectCost: 1,
listFactor: 10,
introspectionListFactor: 2,
}),
],
// Per-request timeout as final backstop
plugins: [
{
onExecute({ args }) {
// Abort execution if it takes more than 10 seconds
const timeout = setTimeout(() => {
// graphql-yoga supports AbortController for cancellation
}, 10_000);
return {
onExecuteDone() { clearTimeout(timeout); },
};
},
},
],
});
graphql-depth-limit(5) as a validation rule before execution, and graphql-validation-complexity with a field weight cap as defense-in-depth. Detection: SkillAudit flags GraphQL server configurations where validationRules does not include a depth-limiting rule, and flags schema types with self-referential or cyclical field relationships.GRAPHQL3-002 — Query batching without per-operation rate limit
GraphQL HTTP transport allows an array of operation objects in a single POST request body — this is query batching. A client can send [{ query: "mutation { ... }" }, { query: "mutation { ... }" }, ...] with 100 entries in a single HTTP request. If the server applies rate limiting per HTTP request (e.g., 10 requests per minute), an attacker can include 100 mutations in each of those 10 allowed requests, effectively executing 1000 mutations per minute. For MCP skills that expose mutations for account modification, password reset, or token generation, this allows a complete bypass of the per-request rate limit. The fix requires counting the number of operations in a batch and applying the rate limit quota per operation, not per HTTP request.
Beyond rate limiting, batching also complicates authentication context propagation. Each operation in a batch should execute in the same authentication context (the HTTP request's authentication header), but implementations that derive per-operation contexts can be confused into mixing auth contexts across batch entries. GraphQL Yoga and Apollo Server both support batch execution but require explicit configuration to enable it — many production deployments leave it enabled by default without recognizing the rate limiting implications.
// VULNERABLE — batch execution enabled, rate limit applied per HTTP request only
import { createServer } from 'http';
import { createYoga } from 'graphql-yoga';
import rateLimit from 'express-rate-limit';
import express from 'express';
import { schema } from './schema';
const app = express();
// Rate limit: 10 requests per minute per IP
// BUT each request can be a batch of 100 operations — effectively 1000 ops/minute
app.use('/graphql', rateLimit({
windowMs: 60_000,
max: 10,
message: { error: 'Too many requests' },
}));
// graphql-yoga enables batching by default — 100 mutations per request allowed
app.use('/graphql', createYoga({
schema,
batching: true, // Enabled — but no per-operation quota
}));
// FIXED — count operations in batch; apply per-operation rate limit quota
import { createServer } from 'http';
import { createYoga, Plugin } from 'graphql-yoga';
import { parse, OperationDefinitionNode } from 'graphql';
import express from 'express';
import { schema } from './schema';
// Per-IP operation counter (use Redis in production for distributed deployments)
const opCounters = new Map<string, { count: number; resetAt: number }>();
const MAX_OPS_PER_MINUTE = 60; // 60 operations per minute per IP
const MAX_BATCH_SIZE = 5; // Maximum operations per batch request
function checkOperationRateLimit(ip: string, opCount: number): boolean {
const now = Date.now();
const entry = opCounters.get(ip);
if (!entry || now > entry.resetAt) {
opCounters.set(ip, { count: opCount, resetAt: now + 60_000 });
return opCount <= MAX_OPS_PER_MINUTE;
}
if (entry.count + opCount > MAX_OPS_PER_MINUTE) {
return false; // Over the per-minute quota
}
entry.count += opCount;
return true;
}
const app = express();
// Pre-parse middleware: count operations in batch before execution
app.use('/graphql', express.json({ limit: '64kb' }), (req, res, next) => {
const body = req.body;
const ip = req.ip ?? 'unknown';
// Count operations in this request (may be a single object or an array)
const operations = Array.isArray(body) ? body : [body];
if (operations.length > MAX_BATCH_SIZE) {
return res.status(400).json({
errors: [{ message: `Batch size ${operations.length} exceeds maximum of ${MAX_BATCH_SIZE}` }],
});
}
// Count total operation count (some entries may be fragments — count only operations)
let totalOpCount = 0;
for (const op of operations) {
try {
const doc = parse(op.query ?? '');
totalOpCount += doc.definitions.filter(
(d): d is OperationDefinitionNode => d.kind === 'OperationDefinition'
).length;
} catch {
return res.status(400).json({ errors: [{ message: 'Invalid GraphQL document' }] });
}
}
// Apply per-operation rate limit
if (!checkOperationRateLimit(ip, totalOpCount)) {
return res.status(429).json({
errors: [{ message: 'Rate limit exceeded — too many GraphQL operations' }],
});
}
next();
});
app.use('/graphql', createYoga({
schema,
batching: {
limit: MAX_BATCH_SIZE, // graphql-yoga built-in batch size limit
},
}));
batching is enabled and the rate limiting middleware operates on HTTP request count rather than per-operation count.GRAPHQL3-003 — Introspection enabled in production
GraphQL introspection (__schema, __type, __typename queries) allows any client to retrieve the complete schema definition: all types, all fields, all mutations, all subscriptions, all input types, all enum values, and all directives. In a production MCP skill API, this exposes: internal mutation names that are not advertised in documentation (e.g., adminResetUserCredentials, debugGetRawAuditData); deprecated fields that are retained for backward compatibility but no longer enforced with the same security controls; and input validation rules (via description fields) that reveal expected formats for injection probing. Tools like GraphQL Voyager and InQL automate schema extraction and attack surface mapping from an introspection response.
The fix is to disable introspection in NODE_ENV=production. For APIs that require schema discovery by trusted clients (e.g., internal tooling), require authentication on the GraphQL endpoint and check that the authenticated user has an introspection role before allowing introspection queries. GraphQL Yoga and Apollo Server both support disabling introspection via a single configuration option. Persisted queries (pre-registered operation IDs) provide an additional layer by preventing arbitrary query submission entirely.
// VULNERABLE — introspection enabled in production (default in most GraphQL servers)
import { createYoga } from 'graphql-yoga';
import { schema } from './schema';
// graphql-yoga defaults: introspection is enabled in all environments
const yoga = createYoga({
schema,
// introspection: true (default) — no NODE_ENV check
// Any unauthenticated or authenticated client can run:
// query { __schema { types { name fields { name type { name kind } } } } }
// And receive the full schema including internal admin mutations
});
// What an attacker learns from introspection on this skill:
// - Mutation "adminForcePasswordReset(userId: ID!)" — not in public docs
// - Query "debugGetRawAuditLog(auditId: ID!)" — returns unredacted internal data
// - Type "InternalAuditConfig" with field "encryptionKeyId" — internal detail
// - Enum "AuditStatusInternal" with values "PENDING_DELETION", "FLAGGED_FOR_REVIEW"
// FIXED — disable introspection in production; allow with auth for trusted clients
import { createYoga } from 'graphql-yoga';
import { schema } from './schema';
import { NoSchemaIntrospectionCustomRule } from 'graphql';
const isProduction = process.env.NODE_ENV === 'production';
const yoga = createYoga({
schema,
// Option 1: disable introspection entirely in production
// graphql-yoga exposes this via the graphiql option and validationRules
graphiql: !isProduction, // Also disable the GraphiQL IDE in production
validationRules: isProduction
? [
// NoSchemaIntrospectionCustomRule rejects __schema and __type queries
NoSchemaIntrospectionCustomRule,
]
: [],
// Option 2 (alternative): require authentication for introspection
// Implement as a custom validation rule that checks context.user.roles
// before allowing introspection queries through
});
// Persisted queries as defense-in-depth: pre-register all allowed operations
// and reject any query document that is not in the registered set
// This prevents arbitrary query submission entirely, including introspection
// graphql-yoga supports this via the persistedOperations plugin:
import { usePersistedOperations } from '@graphql-yoga/plugin-persisted-operations';
const yogaWithPersistedOps = createYoga({
schema,
plugins: [
usePersistedOperations({
// Map of operationId → document string — only these operations are allowed
getPersistedOperation(operationId: string) {
return registeredOperations.get(operationId) ?? null;
// Returns null for unregistered operation IDs — request is rejected
},
// Allow non-persisted queries in development only
allowArbitraryOperations: !isProduction,
}),
],
});
NoSchemaIntrospectionCustomRule as a validation rule when NODE_ENV === 'production', disabling GraphiQL in production, and optionally deploying persisted operations to prevent arbitrary query submission entirely. Detection: SkillAudit sends a { __schema { types { name } } } introspection query to the GraphQL endpoint and flags any response that returns a non-empty types array in a production deployment.GRAPHQL3-004 — N+1 query without DataLoader batches DB calls
An MCP skill's GraphQL resolver for a list query fetches the list items in one database query, then for each item in the list executes a separate database query to resolve a related field. For a list of 50 audit reports, each needing the author's user object resolved, the naive implementation makes 1 query for the audit list + 50 queries for 50 users = 51 database queries. For a list of 500 items, that is 501 queries. This is the N+1 query problem. In a GraphQL context it is especially severe because the client can request deeply nested relationships: audits { author { organization { members { profile { ... } } } } } creates four levels of N+1 multiplication.
DataLoader (by Meta) solves N+1 by batching all calls to a resolver function that occur within the same event loop tick into a single batch call. The first resolver call for user(id: 1) does not immediately execute — it is queued. All resolver calls for user(id: 2), user(id: 3), etc. that arrive before the event loop yields are queued in the same batch. When the event loop yields, DataLoader fires one SELECT * FROM users WHERE id IN (1, 2, 3, ...) query for the entire batch, then resolves each individual promise with its matching result. DataLoader also caches results within a request lifecycle, deduplicated by key, preventing repeated queries for the same entity.
// VULNERABLE — N+1 query in GraphQL resolver
import { GraphQLObjectType, GraphQLList, GraphQLString, GraphQLSchema } from 'graphql';
import { db } from './database';
// Resolver for the "audits" query field
const QueryType = new GraphQLObjectType({
name: 'Query',
fields: {
audits: {
type: new GraphQLList(AuditType),
resolve: async () => {
// Query 1: fetch all audits
return db.query('SELECT * FROM audits LIMIT 50');
},
},
},
});
// Resolver for the "author" field on each Audit object
// This runs ONCE PER AUDIT — 50 audits = 50 separate DB queries
const AuditType = new GraphQLObjectType({
name: 'Audit',
fields: {
id: { type: GraphQLString, resolve: (audit) => audit.id },
title: { type: GraphQLString, resolve: (audit) => audit.title },
author: {
type: UserType,
resolve: async (audit) => {
// VULNERABLE: one SELECT per audit row — 50 audits = 50 queries
// Combined with the initial query: 51 total DB round-trips for a list of 50
return db.queryOne('SELECT * FROM users WHERE id = $1', [audit.authorId]);
},
},
},
});
// FIXED — DataLoader batches all author lookups into a single IN query
import DataLoader from 'dataloader';
import { db } from './database';
// DataLoader batch function: receives an array of keys, returns array of values in same order
async function batchLoadUsers(userIds: readonly string[]): Promise<(User | Error)[]> {
// Single query for the entire batch of user IDs requested in this event loop tick
const users = await db.query(
'SELECT * FROM users WHERE id = ANY($1::uuid[])',
[userIds]
);
// Create a map for O(1) lookup — DataLoader requires results in the same order as keys
const userMap = new Map(users.map((u: User) => [u.id, u]));
// Return results in the same order as the input keys
// Return Error instances for missing keys so DataLoader rejects individual promises
return userIds.map(id => userMap.get(id) ?? new Error(`User not found: ${id}`));
}
// Create a new DataLoader per request — per-request cache lifetime prevents stale reads
// across different authenticated users' requests
function createLoaders() {
return {
userLoader: new DataLoader<string, User>(batchLoadUsers, {
maxBatchSize: 100, // Maximum keys in a single batch call
cache: true, // Cache within this request's DataLoader instance
}),
// Add more loaders here: orgLoader, skillLoader, etc.
};
}
// Pass loaders through GraphQL context so all resolvers share the same instance
// (and therefore the same per-request cache)
const yoga = createYoga({
schema,
context: async () => ({
db,
loaders: createLoaders(), // New DataLoader instance per request
}),
});
// Resolver using DataLoader — zero N+1 queries
const AuditTypeSafe = new GraphQLObjectType({
name: 'Audit',
fields: {
id: { type: GraphQLString, resolve: (audit) => audit.id },
title: { type: GraphQLString, resolve: (audit) => audit.title },
author: {
type: UserType,
// DataLoader queues this call and batches all author lookups from this request
// into one SELECT * FROM users WHERE id = ANY([id1, id2, ..., id50])
resolve: (audit, _args, context) =>
context.loaders.userLoader.load(audit.authorId),
},
},
});
db.queryOne() or equivalent inside the resolver function for each list item execute N+1 database queries per list field — 50 audits with an author field triggers 51 DB round-trips; this scales to hundreds of queries for deeply nested relationships and degrades database performance under normal load; fix by using DataLoader to batch all keys from an event loop tick into a single WHERE id = ANY($1) query, creating a fresh DataLoader instance per request to prevent cross-request cache contamination. Detection: SkillAudit flags GraphQL resolver implementations where a database query function is called inside a field resolver of a list-type parent resolver without using a DataLoader or similar batching mechanism.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| GRAPHQL3-001 | HIGH | Unbounded query nesting depth — cyclic schema allows exponential resolver multiplication (branching^depth calls) | graphql-depth-limit(5) as validation rule; graphql-validation-complexity cap as defense-in-depth |
| GRAPHQL3-002 | HIGH | Query batching with per-HTTP-request rate limit — 100 ops in 1 request bypasses 10 req/min quota (1000 ops/min effective) | Cap batch size at 5; count operations across batch toward per-minute IP quota |
| GRAPHQL3-003 | MEDIUM | Introspection in production exposes internal mutations, deprecated fields, and schema structure for attack mapping | NoSchemaIntrospectionCustomRule in production; persisted operations as defense-in-depth |
| GRAPHQL3-004 | MEDIUM | N+1 DB query per list resolver field — 50-item list triggers 51 round-trips; cascades with nested relationships | DataLoader per request; WHERE id = ANY($1) batch query; per-request cache for deduplication |
Related patterns: SA-SKL-GRAPHQL1 covers foundational GraphQL injection and authorization bypass patterns. GraphQL introspection in production covers introspection exploitation in depth including schema enumeration tooling. SA-SKL-TIMEOUT1 covers missing rate limits and timeout absence patterns that compound GraphQL depth and batch abuse.