Claude skill GraphQL introspection and resolver authorization bypass — SA-SKL-GRAPHQL4
GraphQL's self-describing schema design — a core feature for DX — becomes an attack surface when introspection remains enabled in production, when authorization is enforced only at the top query level but not on nested resolver fields, when batched alias queries multiply effective throughput past rate limits, and when __typename fields on union error types expose internal service architecture to any caller who can trigger a validation error.
GraphQL in MCP skill backends
MCP skills that expose a GraphQL API for audit result queries, skill metadata reads, or report generation face four recurring security patterns that SkillAudit's SA-SKL-GRAPHQL4 check covers. GraphQL's flexibility — specifically, the ability to request exactly the fields you want, to alias fields, and to batch multiple operations — introduces security asymmetries that REST APIs don't share: an attacker can query fields that weren't exposed in the UI documentation, bypass rate limits with a single batched request, and enumerate the entire API surface in seconds using introspection.
publicUser { adminDetails { secretToken } } bypasses auth__typename on union error type exposes internal service class names and architecture to any caller who triggers a validation errorGRAPHQL4-001 — Introspection enabled in production
GraphQL introspection allows any client to query the full schema definition — every type, field, argument, mutation, subscription, and directive — via a standard __schema query. This is valuable during development and for generating client code. In production, it provides attackers with a complete map of the API surface: internal admin mutations that are never linked in the UI, deprecated fields that still execute, and sensitive type structures that reveal business logic.
Introspection should be disabled in production via an environment check or a dedicated plugin. Many GraphQL libraries support this via a single configuration option. After disabling introspection, it's also worth implementing query depth limits and field allowlisting to prevent attackers from probing the schema via trial-and-error.
// VULNERABLE — introspection enabled in production (Apollo Server default)
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
const server = new ApolloServer({
typeDefs,
resolvers,
// No introspection config — Apollo enables introspection by default
// Attacker sends: { __schema { queryType { fields { name description } } } }
// Returns full schema: all queries, mutations, types, fields
});
// FIXED — disable introspection in production; enable query depth + complexity limits
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import depthLimit from 'graphql-depth-limit';
import { createComplexityLimitRule } from 'graphql-validation-complexity';
const IS_DEV = process.env.NODE_ENV === 'development';
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: IS_DEV, // disabled in production
validationRules: [
depthLimit(5), // max 5 levels of nesting
createComplexityLimitRule(1000), // max complexity score per query
],
formatError: (err) => {
// Don't expose internal error details in production
if (!IS_DEV) return { message: 'Internal server error' };
return err;
},
});
GRAPHQL4-002 — Authorization only on top-level query resolver
A common GraphQL authorization mistake is to place the auth check only in the top-level query resolver, assuming that if the caller is authenticated to access user(id: "123"), they are authorized to access all nested fields. This assumption breaks when the schema includes sensitive nested fields — adminDetails, billingInfo, secretToken — that should be gated on a higher privilege level. An attacker who is authenticated as a regular user can call { user(id: "1") { adminDetails { secretToken } } } and receive the sensitive nested data because only the top-level user resolver checked authentication, not the adminDetails resolver.
The fix is per-field authorization using a library like graphql-shield, which allows declarative permission rules at the field or type level. Every sensitive field resolver must enforce its own authorization check independent of the parent resolver.
// VULNERABLE — auth only on top-level resolver; nested adminDetails is unauthenticated
const resolvers = {
Query: {
user: async (_, { id }, ctx) => {
if (!ctx.user) throw new Error('Unauthenticated'); // auth check here
return getUserById(id); // returns entire user object including adminDetails
},
},
User: {
// No auth check here — any authenticated user can request adminDetails
adminDetails: async (user) => getAdminDetails(user.id),
secretToken: async (user) => getSecretToken(user.id),
},
};
// FIXED — per-field authorization with graphql-shield
import { shield, rule, and } from 'graphql-shield';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { applyMiddleware } from 'graphql-middleware';
const isAuthenticated = rule({ cache: 'contextual' })(
async (parent, args, ctx) => ctx.user != null
);
const isAdmin = rule({ cache: 'contextual' })(
async (parent, args, ctx) => ctx.user?.role === 'admin'
);
const permissions = shield({
Query: {
user: isAuthenticated,
adminDashboard: and(isAuthenticated, isAdmin),
},
User: {
// Each sensitive nested field requires its own authorization rule
adminDetails: and(isAuthenticated, isAdmin), // ← separate check per field
secretToken: and(isAuthenticated, isAdmin),
email: isAuthenticated,
publicProfile: isAuthenticated, // even public-ish fields need auth gate
},
}, {
fallbackRule: isAuthenticated, // deny-by-default: all fields require auth
allowExternalErrors: false,
});
const schema = applyMiddleware(makeExecutableSchema({ typeDefs, resolvers }), permissions);
GRAPHQL4-003 — Batched query alias amplification
GraphQL allows field aliasing: { a1: scanRepo(url: "u1") { result } a2: scanRepo(url: "u2") { result } }. This is a legitimate feature for fetching multiple resources in one round trip. The security issue is that a single HTTP request containing 100 aliased identical queries executes 100 operations against the database or external service, while counting as only 1 request against an HTTP-path rate limiter. An attacker who is rate-limited to 60 requests per minute can effectively perform 6000 operations per minute using 100-alias batches.
The fix is query complexity analysis that counts each field resolver execution (including aliases) toward the total complexity budget, and a maximum alias count per document. Libraries like graphql-query-complexity provide per-field cost functions that make alias amplification automatically expensive under the complexity budget.
// VULNERABLE — HTTP-path rate limit on /graphql misses operation count in body
import rateLimit from 'express-rate-limit';
// Limits HTTP requests to /graphql — but one request can contain 100 aliased queries
const graphqlRateLimit = rateLimit({ windowMs: 60000, max: 60 });
app.use('/graphql', graphqlRateLimit, graphqlHandler);
// Attacker sends one HTTP request with body:
// { a1: scanRepo(url:"u1"){result} a2: scanRepo(url:"u2"){result} ... a100: scanRepo(url:"u100"){result} }
// = 100 operations, counted as 1 HTTP request against the rate limit
// FIXED — query complexity + max alias count + per-operation cost
import { createComplexityLimitRule } from 'graphql-validation-complexity';
import { getComplexity, simpleEstimator, fieldExtensionsEstimator } from 'graphql-query-complexity';
import { parse, validate, execute } from 'graphql';
// Custom validation rule: reject documents with more than 10 field aliases total
function maxAliasRule(maxAliases: number) {
return (context: any) => {
let aliasCount = 0;
return {
Field(node: any) {
if (node.alias) aliasCount++;
if (aliasCount > maxAliases) {
context.reportError(new GraphQLError(`Query has too many aliases (max ${maxAliases})`));
}
},
};
};
}
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: false,
validationRules: [
depthLimit(5),
maxAliasRule(10), // max 10 aliases per document
createComplexityLimitRule(500, {
onCost: (cost) => {
// log cost for monitoring
if (cost > 400) console.warn('High-complexity query:', cost);
},
}),
],
});
GRAPHQL4-004 — __typename leaks internal type names on union errors
GraphQL union types are commonly used for error handling: a mutation returns ScanResult | ValidationError | InternalServerError. The __typename field on these union members returns the actual GraphQL type name — which often reflects internal service class names like DatabaseConnectionError, AuditEngineTimeoutError, or MicroserviceUnavailableError. Attackers deliberately trigger errors (invalid inputs, boundary conditions) to enumerate the internal architecture from the returned __typename values, then target the identified subsystems.
The fix is to map internal error types to a small set of public-facing codes before they reach the GraphQL layer, and to use an abstract error interface that exposes only a generic message and code field — not the full type hierarchy.
// VULNERABLE — internal error types exposed via __typename in union responses
// Schema:
// union AuditResult = AuditSuccess | ValidationError | DatabaseConnectionError |
// AuditEngineTimeoutError | MicroserviceUnavailableError
// When attacker submits invalid input, response includes:
// { "data": { "runAudit": { "__typename": "DatabaseConnectionError", "message": "..." } } }
// Reveals internal DB layer exists and is a separate service
// FIXED — map internal errors to public codes; abstract error interface
// Schema:
// interface AuditError { code: AuditErrorCode! message: String! }
// enum AuditErrorCode { VALIDATION_ERROR RATE_LIMITED INTERNAL_ERROR }
// type AuditErrorResult implements AuditError { code: AuditErrorCode! message: String! }
// union AuditResult = AuditSuccess | AuditErrorResult ← only one error type, no impl details
// In resolver:
const resolvers = {
Mutation: {
runAudit: async (_, { repoUrl }, ctx) => {
try {
const result = await auditEngine.scan(repoUrl);
return { __typename: 'AuditSuccess', ...result };
} catch (err) {
// Map all internal errors to public codes
const code = err instanceof ValidationError ? 'VALIDATION_ERROR'
: err instanceof RateLimitError ? 'RATE_LIMITED'
: 'INTERNAL_ERROR'; // absorbs DatabaseConnectionError, timeouts, etc.
return {
__typename: 'AuditErrorResult',
code,
message: code === 'VALIDATION_ERROR' ? err.message : 'An error occurred',
// Never expose err.message for INTERNAL_ERROR — may contain db host, stack trace
};
}
},
},
};
Related patterns: GraphQL rate limiting via alias amplification is related to the HTTP-layer rate limiting bypass patterns in SA-SKL-RATELIMIT6. For authorization bypass patterns that occur at the HTTP layer rather than the GraphQL resolver layer, see the JWT kid injection patterns in SA-SKL-JWT4. For prior coverage of GraphQL introspection and query batching in MCP server deployments, see the GraphQL security in MCP skills blog post.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
GRAPHQL4-001 | High | Apollo Server default introspection in production | introspection: process.env.NODE_ENV === 'development' |
GRAPHQL4-002 | Critical | Auth check on top-level resolver only; nested fields unauthenticated | graphql-shield per-field rules; fallbackRule: isAuthenticated |
GRAPHQL4-003 | High | HTTP-path rate limit misses batched alias count in body | Max alias count rule + graphql-query-complexity per-resolver cost |
GRAPHQL4-004 | Medium | __typename on union error type exposes internal class names | Map all internal errors to AuditErrorResult { code enum message }; absorb impl details |