Claude skill GraphQL security — SA-SKL-GRAPHQL
GraphQL's flexibility is also its attack surface. MCP skills that expose GraphQL APIs — often for rich tool result schemas or for internal dashboard queries — inherit a set of vulnerabilities distinct from REST. GRAPHQL-001 covers introspection left enabled in production, which lets any user enumerate your entire schema including internal types and mutations. GRAPHQL-002 covers missing query depth limits that allow exponentially complex nested queries. GRAPHQL-003 covers missing query complexity limits exploitable via alias repetition. GRAPHQL-004 covers batch query arrays that deliver hundreds of mutations in a single HTTP request, bypassing per-request rate limits.
Why GraphQL requires different security controls than REST
REST APIs expose a fixed set of endpoints with predictable shapes. GraphQL exposes a single endpoint where the query language itself determines what data is fetched and how much work the server does. A client can construct a query that nests 30 levels deep, repeats a field 1000 times via aliases, or batches 500 mutations into one request body. The server executes exactly what the client asks unless explicit validation limits are in place. These are not edge cases or bugs — they are features of GraphQL that require deliberate mitigation.
SA-SKL-GRAPHQL in scope: GRAPHQL-001 (introspection in production), GRAPHQL-002 (missing depth limit), GRAPHQL-003 (missing complexity limit), GRAPHQL-004 (batch mutation array). Each includes SkillAudit detection rules and graphql-depth-limit / graphql-query-complexity / batching-disable fixes.
GRAPHQL-001 — Introspection enabled in production
GraphQL introspection allows any client to query the schema itself: all types, all fields, all query and mutation names, all argument shapes, all directives. This is essential for development tooling (GraphiQL, Apollo Studio, code generators), but in production it gives an attacker a complete map of your API surface — including internal types, admin mutations, and undocumented fields. Attackers routinely run introspection queries as the first step of a GraphQL assessment. The fix is to disable introspection in production via the disableIntrospection validation rule from the graphql-disable-introspection package or Apollo Server's built-in introspection: false option.
// VULNERABLE: Apollo Server with introspection enabled in production (the default)
const { ApolloServer } = require('@apollo/server');
const server = new ApolloServer({
typeDefs,
resolvers,
// No introspection config — introspection is ENABLED by default in Apollo Server 4
// Any user can run: { __schema { types { name fields { name } } } }
// and get a complete map of every type, field, mutation, and argument in your API
});
// FIXED: disable introspection in production; keep enabled in development
const { ApolloServer } = require('@apollo/server');
const server = new ApolloServer({
typeDefs,
resolvers,
// Disable introspection outside of development
// Apollo Server 4+: introspection option (defaults to NODE_ENV !== 'production')
introspection: process.env.NODE_ENV !== 'production',
// Also disable the Apollo Studio landing page in production (leaks endpoint details)
plugins: process.env.NODE_ENV === 'production'
? [ApolloServerPluginLandingPageDisabled()]
: [ApolloServerPluginLandingPageLocalDefault()],
});
// Alternative for graphql-http or express-graphql:
// import { NoSchemaIntrospectionCustomRule } from 'graphql';
// validationRules: process.env.NODE_ENV === 'production'
// ? [NoSchemaIntrospectionCustomRule]
// : []
NoSchemaIntrospectionCustomRule validation rule); any authenticated or unauthenticated user can enumerate all types, fields, mutations, and argument shapes in the schema; attackers use this to identify undocumented admin mutations, internal types, and weak authorization targets. Fix: set introspection: false in Apollo Server production config, or add NoSchemaIntrospectionCustomRule to validationRules; keep introspection enabled in development via NODE_ENV check. Detection: SkillAudit flags ApolloServer configurations without an explicit introspection: false or NODE_ENV-gated introspection disable in production.GRAPHQL-002 — No query depth limit
GraphQL resolvers are recursive: querying an AuditResult can include its job, which includes its user, which includes their auditResults, which includes their jobs, and so on. Without a depth limit, an attacker can send a query nested 100 levels deep. Each nesting level multiplies the number of database calls: a query nested 20 levels into a 10-join schema triggers an exponential number of resolver calls. The event loop blocks; the database connection pool exhausts; the server goes down. The graphql-depth-limit package adds a validation rule that rejects queries exceeding a maximum nesting depth before any resolver runs.
// VULNERABLE: no depth limit — attacker crafts an exponentially deep query
// { auditResult { job { user { auditResults { job { user { ... 50 more levels ... } } } } } } }
// Each nesting level multiplies DB resolver calls — query depth 20 can crash the process
const { ApolloServer } = require('@apollo/server');
const server = new ApolloServer({
typeDefs,
resolvers,
// No depth validation rule — GraphQL executes queries of arbitrary depth
});
// FIXED: graphql-depth-limit rejects deeply nested queries before any resolver runs
const { ApolloServer } = require('@apollo/server');
const depthLimit = require('graphql-depth-limit');
const server = new ApolloServer({
typeDefs,
resolvers,
validationRules: [
// Reject any query nested deeper than 7 levels
// 7 is sufficient for all legitimate dashboard queries; adjust to your schema
depthLimit(7),
// Add introspection disable in production (GRAPHQL-001 fix)
...(process.env.NODE_ENV === 'production'
? [require('graphql').NoSchemaIntrospectionCustomRule]
: []),
],
});
// Verify the limit works by testing a 8-level nested query in your test suite:
// const deepQuery = `{ a { b { c { d { e { f { g { h { id } } } } } } } } }`;
// expect(execute(schema, parse(deepQuery), { validationRules: [depthLimit(7)] }))
// .toMatchObject({ errors: [{ message: /exceeds maximum operation depth/ }] });
User → AuditResult → Job → User) and no query depth limit validation rule; an attacker sends a query nested to depth 20–50 which triggers exponential resolver calls and exhausts the database connection pool or event loop; server becomes unavailable for all users. Fix: add graphql-depth-limit (or equivalent) to validationRules with MAX_DEPTH=7; the validation runs before any resolver and rejects the query with a 400 error. Detection: SkillAudit flags ApolloServer / express-graphql setups where validationRules does not include a depth-limiting rule and the schema has type cross-references.GRAPHQL-003 — No query complexity limit
GraphQL aliases allow a client to call the same field multiple times in one query with different names. A query that aliases auditResult 1000 times executes 1000 database queries in one HTTP request. This is distinct from depth: the query may be only 2 levels deep but 1000 fields wide. Query complexity scoring assigns a numeric cost to each field (typically 1 for scalar, N for list fields, M×N for nested lists) and rejects queries whose total score exceeds a threshold. The graphql-query-complexity package calculates this score during validation and rejects the query before any resolver runs.
// VULNERABLE: alias amplification — 1000 field repetitions in one query
// { a1: auditResult(id: "1") { score } a2: auditResult(id: "2") { score } ... a1000: ... }
// Executes 1000 DB queries in one HTTP request; bypasses per-request rate limit
const { ApolloServer } = require('@apollo/server');
const server = new ApolloServer({
typeDefs,
resolvers,
// No complexity rule — alias amplification is unbounded
});
// FIXED: graphql-query-complexity assigns field costs and rejects high-cost queries
const { ApolloServer } = require('@apollo/server');
const {
createComplexityLimitRule,
fieldExtensionsEstimator,
simpleEstimator,
} = require('graphql-query-complexity');
const server = new ApolloServer({
typeDefs,
resolvers,
validationRules: [
depthLimit(7), // depth from GRAPHQL-002
createComplexityLimitRule(1000, {
// Assign costs in schema extensions or use simple uniform estimator
estimators: [
// Field-level cost annotation: extend type AuditResult { score: Int @cost(value: 1) }
fieldExtensionsEstimator(),
// Default fallback: 1 per scalar field, multiplied by list multipliers
simpleEstimator({ defaultComplexity: 1 }),
],
onCost: (cost) => {
console.debug('[GraphQL] Query complexity:', cost);
},
}),
],
});
graphql-query-complexity createComplexityLimitRule(1000) to validationRules; tune the threshold based on the most expensive legitimate query your UI sends. Detection: SkillAudit flags GraphQL endpoints without both depth AND complexity validation rules when the schema contains list fields or external-API-backed resolvers.GRAPHQL-004 — Batch query array bypasses rate limits
Many GraphQL servers support query batching: the client sends an array of query objects in one HTTP request body, and the server executes all of them and returns an array of results. This is a legitimate performance feature for client-side request coalescing. It is also a rate-limit bypass: a rate limiter counting HTTP requests sees one request; the GraphQL server executes 500 mutations. An attacker who can send one authenticated request every second can execute 500 mutations per second if each request contains a 500-element batch array. The fix is to either disable batching entirely (if no legitimate client uses it) or enforce a maximum batch size of 10–20 elements.
// VULNERABLE: batching enabled with no size limit
// Client sends: [
// { query: 'mutation { createAudit(repoUrl: "url1") { id } }' },
// { query: 'mutation { createAudit(repoUrl: "url2") { id } }' },
// ... 498 more ...
// ]
// Rate limiter sees 1 request; GraphQL executes 500 createAudit mutations
// 500 audit jobs created, 500 credits deducted, 500 queue entries created
const { ApolloServer } = require('@apollo/server');
const { expressMiddleware } = require('@apollo/server/express4');
// Default express-graphql and many Apollo Server setups accept batched arrays
app.use('/graphql', expressMiddleware(server, {
// No batch size limit configured
}));
// FIXED option A: disable batching entirely (simplest; use if no client needs batching)
app.use('/graphql', expressMiddleware(server, {
// Apollo Server 4 disables batching by default — explicitly confirm:
// allowBatchedHttpRequests: false // (this is the default in Apollo Server 4)
}));
// If using graphql-http:
// app.use('/graphql', createHandler({
// schema,
// // graphql-http does not support batching by design
// }));
// FIXED option B: allow batching but enforce a max batch size
app.use('/graphql', (req, res, next) => {
if (Array.isArray(req.body)) {
const MAX_BATCH_SIZE = 10;
if (req.body.length > MAX_BATCH_SIZE) {
return res.status(400).json({
errors: [{ message: `Batch size ${req.body.length} exceeds maximum ${MAX_BATCH_SIZE}` }],
});
}
}
next();
}, expressMiddleware(server));
[{query:...}, ...]) without a maximum batch size; standard per-request rate limits count HTTP requests, not operations; an attacker sends authenticated requests containing 500-element mutation batches, executing 500 operations per rate-limit window (e.g., 500 account creations, 500 audit runs, 500 credit deductions per second). Fix: either disable batch request handling entirely (allowBatchedHttpRequests: false in Apollo Server 4, or use graphql-http which has no batch support), or enforce a maximum of 10–20 operations per batch before the GraphQL layer executes anything. Detection: SkillAudit flags Apollo Server 3 and older setups (which enable batching by default) and express-graphql configurations without explicit batch-size middleware.SkillAudit detection summary — SA-SKL-GRAPHQL
| Pattern ID | Severity | What SkillAudit flags | Fix |
|---|---|---|---|
| GRAPHQL-001 | HIGH | No introspection: false or NoSchemaIntrospectionCustomRule in production | introspection: process.env.NODE_ENV !== 'production' |
| GRAPHQL-002 | HIGH | No depth limit in validationRules with cross-referenced types | depthLimit(7) from graphql-depth-limit |
| GRAPHQL-003 | HIGH | No complexity limit in validationRules with list or external-API resolvers | createComplexityLimitRule(1000) |
| GRAPHQL-004 | HIGH | Apollo Server 3 (batch on by default) or missing batch-size middleware | allowBatchedHttpRequests: false or max 10 |
Related patterns: For GraphQL injection via unsanitized variables, see SA-SKL-GRAPHQL-INJ. For resource exhaustion via unbounded memory and CPU in non-GraphQL handlers, see SA-SKL-ALLOCATION. For rate limiting bypass patterns beyond GraphQL batching, see SA-SKL-RATELIMIT.