graphql: limit query depth and complexity

Depth 3 counts every field including leaves and expands fragments in place, so the Skill.profile cycle cannot be walked twice. Complexity budget 100 with weight 10 on list fields blocks alias floods at validation time.
This commit is contained in:
arswarog committed 2026-11-18 13:06:55 +03:00
1 parent c824a7675b
commit b0da59fbf4
5 files changed
+122 -4

No files matched your search

+1
View File
@@ -35,6 +35,7 @@
"dataloader": "^2.2.3", "dataloader": "^2.2.3",
"dotenv": "^18.0.10", "dotenv": "^18.0.10",
"graphql": "^17.1.0", "graphql": "^17.1.0",
"graphql-query-complexity": "^2.0.0",
"pg": "^8.23.1", "pg": "^8.23.1",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1", "rxjs": "^7.8.1",
+3
View File
@@ -9,6 +9,7 @@ import { AppService } from './app.service.js';
import { ProfileModule } from './profile/profile.module.js'; import { ProfileModule } from './profile/profile.module.js';
import { createProfileLoaders, GraphQLContext } from './profile/profile.loaders.js'; import { createProfileLoaders, GraphQLContext } from './profile/profile.loaders.js';
import { ProfileService } from './profile/profile.service.js'; import { ProfileService } from './profile/profile.service.js';
import { complexityLimit, depthLimit } from './query-limits.js';
@Module({ @Module({
imports: [ imports: [
@@ -29,6 +30,8 @@ import { ProfileService } from './profile/profile.service.js';
plugins: [ApolloServerPluginLandingPageLocalDefault()], plugins: [ApolloServerPluginLandingPageLocalDefault()],
context: (): GraphQLContext => ({ loaders: createProfileLoaders(profileService) }), context: (): GraphQLContext => ({ loaders: createProfileLoaders(profileService) }),
validationRules: [depthLimit(3), complexityLimit(100)],
}), }),
}), }),
ProfileModule, ProfileModule,
+7 -4
View File
@@ -17,17 +17,20 @@ export class ProfileResolver {
return this.profileService.getProfile(); return this.profileService.getProfile();
} }
@ResolveField(() => [SkillDto], { description: 'Навыки' }) @ResolveField(() => [SkillDto], { description: 'Навыки', complexity: 10 })
skills(@Parent() profile: ProfileDto, @Context() context: GraphQLContext): Promise<SkillDto[]> { skills(@Parent() profile: ProfileDto, @Context() context: GraphQLContext): Promise<SkillDto[]> {
return context.loaders.skills.load(profile.id); return context.loaders.skills.load(profile.id);
} }
@ResolveField(() => [LinkDto], { description: 'Ссылки на профессиональные ресурсы' }) @ResolveField(() => [LinkDto], {
description: 'Ссылки на профессиональные ресурсы',
complexity: 10,
})
links(@Parent() profile: ProfileDto, @Context() context: GraphQLContext): Promise<LinkDto[]> { links(@Parent() profile: ProfileDto, @Context() context: GraphQLContext): Promise<LinkDto[]> {
return context.loaders.links.load(profile.id); return context.loaders.links.load(profile.id);
} }
@ResolveField(() => [ExperienceDto], { description: 'Опыт работы' }) @ResolveField(() => [ExperienceDto], { description: 'Опыт работы', complexity: 10 })
experience( experience(
@Parent() profile: ProfileDto, @Parent() profile: ProfileDto,
@Context() context: GraphQLContext, @Context() context: GraphQLContext,
@@ -35,7 +38,7 @@ export class ProfileResolver {
return context.loaders.experience.load(profile.id); return context.loaders.experience.load(profile.id);
} }
@ResolveField(() => [ProjectDto], { description: 'Проекты' }) @ResolveField(() => [ProjectDto], { description: 'Проекты', complexity: 10 })
projects( projects(
@Parent() profile: ProfileDto, @Parent() profile: ProfileDto,
@Context() context: GraphQLContext, @Context() context: GraphQLContext,
+92
View File
@@ -0,0 +1,92 @@
import type { ASTVisitor, SelectionSetNode, ValidationContext } from 'graphql';
import { GraphQLError, Kind } from 'graphql';
import {
createComplexityRule,
fieldExtensionsEstimator,
simpleEstimator,
type ComplexityEstimator,
} from 'graphql-query-complexity';
/**
* Лимит глубины запроса.
*
* Глубина считается по полям, включая листья: `{ profile { skills { name } } }` — 3.
* Фрагменты разворачиваются на месте spread, поэтому цепочка фрагментов не обходит лимит.
*/
export function depthLimit(maxDepth: number): (context: ValidationContext) => ASTVisitor {
return (context) => {
const activeFragments = new Set<string>();
const walk = (selectionSet: SelectionSetNode, depth: number): boolean => {
for (const selection of selectionSet.selections) {
switch (selection.kind) {
case Kind.FIELD: {
if (selection.name.value.startsWith('__')) {
break;
}
const fieldDepth = depth + 1;
if (fieldDepth > maxDepth) {
context.reportError(
new GraphQLError(
`Query is too deep: field "${selection.name.value}" at depth ${fieldDepth} exceeds limit ${maxDepth}`,
{ nodes: [selection] },
),
);
return true;
}
if (selection.selectionSet && walk(selection.selectionSet, fieldDepth)) {
return true;
}
break;
}
case Kind.INLINE_FRAGMENT:
if (walk(selection.selectionSet, depth)) {
return true;
}
break;
case Kind.FRAGMENT_SPREAD: {
const name = selection.name.value;
const fragment = context.getFragment(name);
if (!fragment || activeFragments.has(name)) {
break;
}
activeFragments.add(name);
const aborted = walk(fragment.selectionSet, depth);
activeFragments.delete(name);
if (aborted) {
return true;
}
break;
}
}
}
return false;
};
return {
OperationDefinition(node) {
walk(node.selectionSet, 0);
},
};
};
}
/**
* Лимит стоимости запроса.
*
* Вес поля берётся из `extensions.complexity` (Nest заполняет его опцией `complexity`
* декораторов `@Field`/`@ResolveField`), остальные поля стоят 1.
*/
export function complexityLimit(maxComplexity: number): (context: ValidationContext) => ASTVisitor {
const withoutIntrospection: ComplexityEstimator = ({ field, type }) =>
field.name.startsWith('__') || type.name.startsWith('__') ? 0 : undefined;
return createComplexityRule({
maximumComplexity: maxComplexity,
estimators: [
withoutIntrospection,
fieldExtensionsEstimator(),
simpleEstimator({ defaultComplexity: 1 }),
],
});
}
+19
View File
@@ -3799,6 +3799,17 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"graphql-query-complexity@npm:^2.0.0":
version: 2.0.0
resolution: "graphql-query-complexity@npm:2.0.0"
dependencies:
lodash.get: "npm:^4.4.2"
peerDependencies:
graphql: ^16.6.0 || ^17.0.0
checksum: 10c0/928e8c466a6b58461507be263806fdd652ace0105046f9584ee2a88a6db27e648d05ae4042ebb24e92926fec3052e7cbe32b3a448494d5c0a90b0e3f8b9deb71
languageName: node
linkType: hard
"graphql-tag@npm:2.12.7": "graphql-tag@npm:2.12.7":
version: 2.12.7 version: 2.12.7
resolution: "graphql-tag@npm:2.12.7" resolution: "graphql-tag@npm:2.12.7"
@@ -4105,6 +4116,7 @@ __metadata:
dataloader: "npm:^2.2.3" dataloader: "npm:^2.2.3"
dotenv: "npm:^18.0.10" dotenv: "npm:^18.0.10"
graphql: "npm:^17.1.0" graphql: "npm:^17.1.0"
graphql-query-complexity: "npm:^2.0.0"
oxlint: "npm:^1.58.0" oxlint: "npm:^1.58.0"
oxlint-tsgolint: "npm:^7.0.2001" oxlint-tsgolint: "npm:^7.0.2001"
pg: "npm:^8.23.1" pg: "npm:^8.23.1"
@@ -4301,6 +4313,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"lodash.get@npm:^4.4.2":
version: 4.4.2
resolution: "lodash.get@npm:4.4.2"
checksum: 10c0/48f40d471a1654397ed41685495acb31498d5ed696185ac8973daef424a749ca0c7871bf7b665d5c14f5cc479394479e0307e781f61d5573831769593411be6e
languageName: node
linkType: hard
"lodash.omit@npm:4.18.0": "lodash.omit@npm:4.18.0":
version: 4.18.0 version: 4.18.0
resolution: "lodash.omit@npm:4.18.0" resolution: "lodash.omit@npm:4.18.0"