TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › GraphQL: Introspection, Depth and Batching

GraphQL: Introspection, Depth and Batching

A REST API has many endpoints with fixed responses; a GraphQL API has one endpoint, and the client writes a query that says exactly which fields and nested objects it wants. That flexibility moves security decisions. Authorization can't be attached to a URL any more, because every request goes to /graphql: it must sit on each type and field. Rate limiting by request count no longer measures cost, because one request can ask for a million objects or try a hundred passwords. And the schema, which REST APIs often keep private, is usually discoverable by asking the server itself. This lesson uses the reference implementation, graphql-js (the GraphQL course teaches the language), to run an introspection query, a deeply nested query and an aliased brute-force attempt against a toy schema, then adds the validation rules that refuse them.

Definitions

  • Schema: the types, fields and arguments the API offers. Resolver: the function that produces a field's value; where authorization checks belong.
  • Introspection: built-in fields (__schema, __type) that return the schema itself. Invaluable for tools like GraphiQL, and a full map for an attacker.
  • Query depth: how deeply selections nest (user { friends { friends { … } } }). Cyclic relations make depth, and cost, unbounded.
  • Aliases: renaming a field in the response (a1: login(…) a2: login(…)), which lets one request call the same field many times. Batching: some servers accept an array of operations in one HTTP request.
  • Query cost analysis: estimating work before execution (each list multiplies the cost of its children) and refusing queries over a budget. Persisted queries: the server only runs queries from an allow-list registered at build time.

Three abusive queries, then three rules

The example builds a small schema with a cyclic friends relation and a login mutation, then validates queries before executing them, first with the standard rules only, then with three extra rules: no introspection, a maximum depth, and a maximum number of fields per operation (which also caps aliases).

js · try it yourself
import { buildSchema, parse, validate, specifiedRules, NoSchemaIntrospectionCustomRule, GraphQLError, graphql } from 'graphql';

const schema = buildSchema(`
  type User { id: ID!, name: String!, friends: [User!]! }
  type Query { me: User! }
  type Mutation { login(user: String!, password: String!): Boolean! }
`);
const alice = { id: '1', name: 'alice' };
alice.friends = [alice];                                      // cyclic data, as in any social graph
let loginCalls = 0;
const rootValue = { me: () => alice, login: () => { loginCalls++; return false; } };

function maxDepth(limit) {
  return (context) => ({
    Field(node, key, parent, path, ancestors) {
      const depth = ancestors.filter((a) => a.kind === 'Field').length + 1;
      if (depth > limit) context.reportError(new GraphQLError(`depth ${depth} exceeds ${limit}`));
    },
  });
}
function maxFields(limit) {
  return (context) => {
    let count = 0;
    return { Field() { if (++count === limit + 1) context.reportError(new GraphQLError(`more than ${limit} fields`)); } };
  };
}
const strictRules = [...specifiedRules, NoSchemaIntrospectionCustomRule, maxDepth(4), maxFields(20)];

const nested = '{ me { ' + 'friends { '.repeat(8) + 'name' + ' }'.repeat(8) + ' } }';
const aliased = 'mutation { ' + Array.from({ length: 100 }, (_, i) => `a${i}: login(user: "admin", password: "guess${i}")`).join(' ') + ' }';
const queries = {
  'normal query': '{ me { name friends { name } } }',
  'introspection': '{ __schema { types { name } } }',
  'depth 10': nested,
  '100 aliased logins': aliased,
};

for (const [name, q] of Object.entries(queries)) {
  const doc = parse(q);
  const loose = validate(schema, doc, specifiedRules);
  const strict = validate(schema, doc, strictRules);
  console.log(`${name.padEnd(20)} standard rules: ${loose.length ? 'refused' : 'ok'}  |  strict: ${strict.length ? 'refused (' + strict[0].message + ')' : 'ok'}`);
}

const types = await graphql({ schema, source: queries.introspection });
console.log('introspection reveals:', types.data.__schema.types.map((t) => t.name).filter((n) => !n.startsWith('__')).join(', '));
loginCalls = 0;
await graphql({ schema, source: aliased, rootValue });
console.log('one HTTP request with aliases ran login', loginCalls, 'times');
const deep = await graphql({ schema, source: nested, rootValue });
console.log('depth-10 result is', JSON.stringify(deep.data).length, 'bytes for one user; with 100 friends each it would be 100^8 objects');
normal query         standard rules: ok  |  strict: ok
introspection        standard rules: ok  |  strict: refused (GraphQL introspection has been disabled, but the requested query contained the field "__schema".)
depth 10             standard rules: ok  |  strict: refused (depth 5 exceeds 4)
100 aliased logins   standard rules: ok  |  strict: refused (more than 20 fields)
introspection reveals: User, ID, String, Query, Mutation, Boolean
one HTTP request with aliases ran login 100 times
depth-10 result is 135 bytes for one user; with 100 friends each it would be 100^8 objects

The standard rules check only that a query is valid; every abusive query passes them. Introspection revealed every type, including the Mutation with its login field, without any documentation. A single HTTP request ran login a hundred times, so a rate limit that counts HTTP requests sees one attempt where there were a hundred guesses. The nested query was tiny here because alice's only friend is herself, but with realistic data each level multiplies the work. The strict rule set refused all three before any resolver ran, while the normal query passed.

How GraphQL weaknesses are detected

  • Testing (in scope): send the introspection query (and, if it is disabled, try field suggestions: many servers answer a misspelled field with "Did you mean password?"); look for mutations and fields that lack authorization by calling them as a low-privilege user; send nested and aliased queries with growing size and watch response times (carefully, agreed in the rules of engagement, since this can take a service down); check whether arrays of operations are accepted. Tools: InQL and GraphQL Raider for Burp, graphql-cop, Clairvoyance for schema recovery when introspection is off.
  • Code review: authorization in the HTTP layer only (it sees one endpoint), resolvers that fetch by id without ownership checks (BOLA again), no depth/cost limits, introspection and GraphiQL enabled in production.
  • Monitoring: query depth, field count, aliases and execution time per request, logged per client; error counts from the validation rules; many login resolver calls per request.

How it is fixed

  1. Authorize in resolvers (or in a shared layer called by every resolver), per object and per field.
  2. Limit queries before executing them: maximum depth, field/alias counts, cost analysis with list multipliers, timeouts, pagination with a maximum page size.
  3. Turn off introspection and field suggestions in production for private APIs, or better, accept only persisted queries from your own clients.
  4. Rate limit by operation cost and by sensitive resolver (login attempts per account), not by HTTP request.
  5. Disable or cap batching of operation arrays.

Pitfalls

  • Hiding the schema as the main defence: it can be reconstructed from suggestions, client bundles and error messages; authorization must hold with the schema public.
  • Auth checks on the Query.user entry point but not on nested paths: me { friends { privateEmail } } reaches the same data through another edge.
  • Error messages with stack traces and resolver details in production.

Practice

1. A login mutation is limited to 10 HTTP requests per minute per IP. How many password guesses per minute does the aliased query allow, and what is the fix?

10 requests × 100 aliases = 1,000 guesses per minute (more with bigger queries). Limit login attempts per account and per source inside the resolver, and cap aliases/fields per operation.

2. Introspection is disabled, but the server answers { me { passwrd } } with "Cannot query field passwrd on type User. Did you mean password?". What does that mean?

Field suggestions leak the schema one guess at a time. Disable suggestions in production (many servers have an option) and make sure password (or its hash) isn't a field at all.

Test yourself

Why can't GraphQL authorization be attached to URLs?

  1. GraphQL has no URLs
  2. Every operation goes to the same endpoint; authorization must sit on types, fields and resolvers
  3. URLs are encrypted
  4. Browsers block it

How did one request run login 100 times?

  1. Batching arrays
  2. Aliases: the same field requested 100 times under different names
  3. Recursion
  4. A bug in graphql-js

Which query did the standard validation rules refuse?

  1. Introspection
  2. The deep query
  3. The aliased logins
  4. None of them

What are persisted queries?

  1. Cached responses
  2. An allow-list of queries registered by your own clients; the server refuses anything else
  3. Queries saved in the database
  4. Introspection results