From b0da59fbf49df29371e59d606db0e9a8508672fd Mon Sep 17 00:00:00 2001 From: Arswarog Date: Wed, 18 Nov 2026 11:14:26 +0300 Subject: [PATCH] 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. --- package.json | 1 + src/app.module.ts | 3 + src/profile/resolvers/profile.resolver.ts | 11 ++- src/query-limits.ts | 92 +++++++++++++++++++++++ yarn.lock | 19 +++++ 5 files changed, 122 insertions(+), 4 deletions(-) create mode 100644 src/query-limits.ts diff --git a/package.json b/package.json index 1e985d3..c3f06fc 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "dataloader": "^2.2.3", "dotenv": "^18.0.10", "graphql": "^17.1.0", + "graphql-query-complexity": "^2.0.0", "pg": "^8.23.1", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", diff --git a/src/app.module.ts b/src/app.module.ts index 1735f23..1da138c 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -9,6 +9,7 @@ import { AppService } from './app.service.js'; import { ProfileModule } from './profile/profile.module.js'; import { createProfileLoaders, GraphQLContext } from './profile/profile.loaders.js'; import { ProfileService } from './profile/profile.service.js'; +import { complexityLimit, depthLimit } from './query-limits.js'; @Module({ imports: [ @@ -29,6 +30,8 @@ import { ProfileService } from './profile/profile.service.js'; plugins: [ApolloServerPluginLandingPageLocalDefault()], context: (): GraphQLContext => ({ loaders: createProfileLoaders(profileService) }), + + validationRules: [depthLimit(3), complexityLimit(100)], }), }), ProfileModule, diff --git a/src/profile/resolvers/profile.resolver.ts b/src/profile/resolvers/profile.resolver.ts index adaaf65..47e1a8d 100644 --- a/src/profile/resolvers/profile.resolver.ts +++ b/src/profile/resolvers/profile.resolver.ts @@ -17,17 +17,20 @@ export class ProfileResolver { return this.profileService.getProfile(); } - @ResolveField(() => [SkillDto], { description: 'Навыки' }) + @ResolveField(() => [SkillDto], { description: 'Навыки', complexity: 10 }) skills(@Parent() profile: ProfileDto, @Context() context: GraphQLContext): Promise { return context.loaders.skills.load(profile.id); } - @ResolveField(() => [LinkDto], { description: 'Ссылки на профессиональные ресурсы' }) + @ResolveField(() => [LinkDto], { + description: 'Ссылки на профессиональные ресурсы', + complexity: 10, + }) links(@Parent() profile: ProfileDto, @Context() context: GraphQLContext): Promise { return context.loaders.links.load(profile.id); } - @ResolveField(() => [ExperienceDto], { description: 'Опыт работы' }) + @ResolveField(() => [ExperienceDto], { description: 'Опыт работы', complexity: 10 }) experience( @Parent() profile: ProfileDto, @Context() context: GraphQLContext, @@ -35,7 +38,7 @@ export class ProfileResolver { return context.loaders.experience.load(profile.id); } - @ResolveField(() => [ProjectDto], { description: 'Проекты' }) + @ResolveField(() => [ProjectDto], { description: 'Проекты', complexity: 10 }) projects( @Parent() profile: ProfileDto, @Context() context: GraphQLContext, diff --git a/src/query-limits.ts b/src/query-limits.ts new file mode 100644 index 0000000..39782da --- /dev/null +++ b/src/query-limits.ts @@ -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(); + + 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 }), + ], + }); +} diff --git a/yarn.lock b/yarn.lock index 714a2f4..8a74315 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3799,6 +3799,17 @@ __metadata: languageName: node 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": version: 2.12.7 resolution: "graphql-tag@npm:2.12.7" @@ -4105,6 +4116,7 @@ __metadata: dataloader: "npm:^2.2.3" dotenv: "npm:^18.0.10" graphql: "npm:^17.1.0" + graphql-query-complexity: "npm:^2.0.0" oxlint: "npm:^1.58.0" oxlint-tsgolint: "npm:^7.0.2001" pg: "npm:^8.23.1" @@ -4301,6 +4313,13 @@ __metadata: languageName: node 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": version: 4.18.0 resolution: "lodash.omit@npm:4.18.0"