Security: Depth & Complexity
GraphQL's flexibility is also an attack surface. A REST endpoint does a fixed amount of work; a GraphQL endpoint does whatever the query asks. Because schemas often contain cycles (User.friends → [User]), a tiny query can demand an enormous amount of work:
{
user(id: 1) {
friends { # 100 friends
friends { # x 100
friends { # x 100
friends { # x 100 = 100,000,000 user lookups
name
}
}
}
}
}
}Validation happily accepts this; it's a perfectly valid query. Production servers therefore add limits before execution.
Measuring depth with visit
graphql-js gives you visit(ast, visitor), which walks every node of a parsed query and calls enter/leave functions by node kind. Counting nested selection sets gives the depth:
import { parse, visit } from 'graphql';
function queryDepth(source) {
let depth = 0;
let maxDepth = 0;
visit(parse(source), {
Field: {
enter() { depth += 1; maxDepth = Math.max(maxDepth, depth); },
leave() { depth -= 1; },
},
});
return maxDepth;
}
console.log(queryDepth('{ me { name } }'));
console.log(queryDepth('{ user(id: 1) { friends { friends { friends { name } } } } }'));2
5
A depth-limit validation rule
Turn it into a custom validation rule (see the Validation lesson) so deep queries are rejected before any resolver runs. Fragments need care: a ...Spread must count the fields inside the fragment at the current depth, or attackers could hide the nesting in fragments:
import { buildSchema, parse, validate, specifiedRules, GraphQLError, Kind } from 'graphql';
function depthLimit(maxDepth) {
return function DepthLimitRule(context) {
const fragments = {};
for (const def of context.getDocument().definitions) {
if (def.kind === Kind.FRAGMENT_DEFINITION) fragments[def.name.value] = def;
}
const measure = (selectionSet, depth, seen) => {
let deepest = depth;
for (const sel of selectionSet.selections) {
if (sel.kind === Kind.FIELD) {
if (sel.name.value.startsWith('__')) continue; // ignore __typename etc.
deepest = Math.max(deepest, sel.selectionSet ? measure(sel.selectionSet, depth + 1, seen) : depth + 1);
} else if (sel.kind === Kind.INLINE_FRAGMENT) {
deepest = Math.max(deepest, measure(sel.selectionSet, depth, seen));
} else if (sel.kind === Kind.FRAGMENT_SPREAD) {
const name = sel.name.value;
if (seen.has(name) || !fragments[name]) continue; // cycles are reported by other rules
deepest = Math.max(deepest, measure(fragments[name].selectionSet, depth, new Set([...seen, name])));
}
}
return deepest;
};
return {
OperationDefinition(node) {
const depth = measure(node.selectionSet, 0, new Set());
if (depth > maxDepth) {
context.reportError(new GraphQLError(
`Query depth ${depth} exceeds the maximum of ${maxDepth}.`, { nodes: node },
));
}
},
};
};
}
const schema = buildSchema(`
type User { name: String!, friends: [User!]! }
type Query { me: User! }
`);
const rules = [...specifiedRules, depthLimit(3)];
const queries = {
shallow: '{ me { name friends { name } } }',
deep: '{ me { friends { friends { friends { name } } } } }',
sneaky: '{ me { ...F1 } } fragment F1 on User { friends { ...F2 } } fragment F2 on User { friends { friends { name } } }',
};
for (const [label, source] of Object.entries(queries)) {
const errors = validate(schema, parse(source), rules);
console.log(label.padEnd(8), errors.length ? errors[0].message : 'ok');
}shallow ok
deep Query depth 5 exceeds the maximum of 3.
sneaky Query depth 5 exceeds the maximum of 3.
The "sneaky" query spreads its nesting across two fragments, but the rule follows the spreads and still measures depth 5.
Complexity (cost) analysis
Depth alone misses wide queries ({ a: users(first: 1000) { … } b: users(first: 1000) { … } … }). Cost analysis gives each field a cost and multiplies by list sizes, then rejects queries above a budget. A simple model: each field costs 1, and a field with a first argument multiplies the cost of its children:
import { parse, Kind } from 'graphql';
function queryCost(source) {
const cost = (selectionSet) => {
let total = 0;
for (const sel of selectionSet.selections) {
if (sel.kind !== Kind.FIELD) continue;
const firstArg = sel.arguments.find((a) => a.name.value === 'first');
const multiplier = firstArg ? Number(firstArg.value.value) : 1;
total += 1 + (sel.selectionSet ? multiplier * cost(sel.selectionSet) : 0);
}
return total;
};
const operation = parse(source).definitions[0];
return cost(operation.selectionSet);
}
const examples = [
'{ me { name } }',
'{ posts(first: 5) { title author { name } } }',
'{ posts(first: 100) { comments(first: 50) { author { name } } } }',
];
const BUDGET = 1000;
for (const source of examples) {
const c = queryCost(source);
console.log(String(c).padStart(6), c > BUDGET ? 'REJECT' : 'ok ', source);
} 2 ok { me { name } }
16 ok { posts(first: 5) { title author { name } } }
10101 REJECT { posts(first: 100) { comments(first: 50) { author { name } } } }
Production-grade versions (graphql-query-complexity, Apollo's demand control, Hive's cost directives) let you annotate costs in the schema with directives such as @cost(weight: 5) and @listSize(assumedSize: 50).
A security checklist
| Threat | Mitigation |
|---|---|
| Deep or huge queries | depth limit, cost limit, cap first/limit arguments |
| Many operations in one request (batching attacks) | limit operations per HTTP request; limit aliases per query |
Brute force via aliases (a1: login(...) a2: login(...) …) |
rate-limit by cost or by resolver calls, not only by HTTP requests |
| Slow resolvers | timeouts per request, DataLoader against N+1 |
| Schema discovery | disable introspection on private APIs, or accept only persisted queries |
| Leaking internals | mask unexpected errors (see the Errors lesson) |
| Unauthorized data | authorization in business logic for every path (see Authorization) |
| Injection | variables instead of string building; parameterized SQL in resolvers |
Tip: If your API only serves your own apps, persisted queries / an operation allow-list is the single most effective measure: the server only executes queries that were registered at build time, so no attacker-written query ever runs.
Test yourself
Why can a small GraphQL query be dangerous?
- Queries are not validated
- Nested lists in cyclic schemas multiply the work exponentially
- GraphQL has no types
- Introspection runs on every query
Why must a depth-limit rule follow fragment spreads?
- Fragments are slower
- Otherwise nesting hidden inside fragments would go uncounted
- Fragments can't be nested
- The spec requires it
What does query cost analysis add compared with a depth limit?
- It checks syntax
- It accounts for list sizes and wide selections, not just nesting
- It encrypts the query
- It caches results