Skip to content

Add maxQueryNodes limit #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {

const rule = createComplexityRule({
// The maximum allowed query complexity, queries above this threshold will be rejected
maximumComplexity: 1000,
maximumComplexity: 1_000,

// The query variables. This is needed because the variables are not available
// in the visitor of the graphql-js library
Expand All @@ -40,9 +40,16 @@ const rule = createComplexityRule({
// The context object for the request (optional)
context: {}

// specify operation name only when pass multi-operation documents
// Specify operation name when evaluating multi-operation documents
operationName?: string,

// The maximum number of query nodes to evaluate (fields, fragments, composite types).
// If a query contains more than the specified number of nodes, the complexity rule will
// throw an error, regardless of the complexity of the query.
//
// Default: 10_000
maxQueryNodes?: 10_000,

// Optional callback function to retrieve the determined query complexity
// Will be invoked whether the query is rejected or not
// This can be used for logging or to implement rate limiting
Expand Down
19 changes: 17 additions & 2 deletions src/QueryComplexity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ export interface QueryComplexityOptions {

// Pass request context to the estimators via estimationContext
context?: Record<string, any>;

// The maximum number of nodes to evaluate. If this is set, the query will be
// rejected if it exceeds this number. (Includes fields, fragments, inline fragments, etc.)
// Defaults to 10_000.
maxQueryNodes?: number;
}

function queryComplexityMessage(max: number, actual: number): string {
Expand All @@ -101,6 +106,7 @@ export function getComplexity(options: {
variables?: Record<string, any>;
operationName?: string;
context?: Record<string, any>;
maxQueryNodes?: number;
}): number {
const typeInfo = new TypeInfo(options.schema);

Expand All @@ -118,6 +124,7 @@ export function getComplexity(options: {
variables: options.variables,
operationName: options.operationName,
context: options.context,
maxQueryNodes: options.maxQueryNodes,
});

visit(options.query, visitWithTypeInfo(typeInfo, visitor));
Expand All @@ -140,6 +147,8 @@ export default class QueryComplexity {
skipDirectiveDef: GraphQLDirective;
variableValues: Record<string, any>;
requestContext?: Record<string, any>;
evaluatedNodes: number;
maxQueryNodes: number;

constructor(context: ValidationContext, options: QueryComplexityOptions) {
if (
Expand All @@ -154,7 +163,8 @@ export default class QueryComplexity {
this.context = context;
this.complexity = 0;
this.options = options;

this.evaluatedNodes = 0;
this.maxQueryNodes = options.maxQueryNodes ?? 10_000;
this.includeDirectiveDef = this.context.getSchema().getDirective('include');
this.skipDirectiveDef = this.context.getSchema().getDirective('skip');
this.estimators = options.estimators;
Expand Down Expand Up @@ -274,7 +284,12 @@ export default class QueryComplexity {
complexities: ComplexityMap,
childNode: FieldNode | FragmentSpreadNode | InlineFragmentNode
): ComplexityMap => {
// let nodeComplexity = 0;
this.evaluatedNodes++;
if (this.evaluatedNodes >= this.maxQueryNodes) {
throw new GraphQLError(
'Query exceeds the maximum allowed number of nodes.'
);
}
let innerComplexities = complexities;

let includeNode = true;
Expand Down
83 changes: 83 additions & 0 deletions src/__tests__/QueryComplexity-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -939,4 +939,87 @@ describe('QueryComplexity analysis', () => {

expect(errors).to.have.length(0);
});

it('should reject queries that exceed the maximum number of fragment nodes', () => {
const query = parse(`
query {
...F
...F
}
fragment F on Query {
scalar
}
`);

expect(() =>
getComplexity({
estimators: [simpleEstimator({ defaultComplexity: 1 })],
schema,
query,
maxQueryNodes: 1,
variables: {},
})
).to.throw('Query exceeds the maximum allowed number of nodes.');
});

it('should reject queries that exceed the maximum number of field nodes', () => {
const query = parse(`
query {
scalar
scalar1: scalar
scalar2: scalar
scalar3: scalar
scalar4: scalar
scalar5: scalar
scalar6: scalar
scalar7: scalar
}
`);

expect(() =>
getComplexity({
estimators: [simpleEstimator({ defaultComplexity: 1 })],
schema,
query,
maxQueryNodes: 1,
variables: {},
})
).to.throw('Query exceeds the maximum allowed number of nodes.');
});

it('should limit the number of query nodes to 10_000 by default', () => {
const failingQuery = parse(`
query {
${Array.from({ length: 10_000 }, (_, i) => `scalar${i}: scalar`).join(
'\n'
)}
}
`);

expect(() =>
getComplexity({
estimators: [simpleEstimator({ defaultComplexity: 1 })],
schema,
query: failingQuery,
variables: {},
})
).to.throw('Query exceeds the maximum allowed number of nodes.');

const passingQuery = parse(`
query {
${Array.from({ length: 9999 }, (_, i) => `scalar${i}: scalar`).join(
'\n'
)}
}
`);

expect(() =>
getComplexity({
estimators: [simpleEstimator({ defaultComplexity: 1 })],
schema,
query: passingQuery,
variables: {},
})
).not.to.throw();
});
});
Loading