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"