Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { createSchema, createYoga } from 'graphql-yoga';
import { rootLevelQueryLimit } from '../src/index.js';

describe('root-level-limitation', () => {
const schema = createSchema({
typeDefs: /* GraphQL */ `
type Query {
topProducts: GetTopProducts
topBooks: GetTopBooks
}
type GetTopBooks {
id: Int
}
type GetTopProducts {
id: Int
}
`,
});

const yoga = createYoga({
schema,
plugins: [rootLevelQueryLimit({ maxRootLevelFields: 1 })],
maskedErrors: false,
});

it('should not allow requests with max root level query', async () => {
const res = await yoga.fetch('http://yoga/graphql', {
method: 'POST',
body: JSON.stringify({
query: /* GraphQL */ `
{
topBooks {
id
}
topProducts {
id
}
}
`,
}),
headers: {
'Content-Type': 'application/json',
},
});

expect(res.status).toBe(400);
});

it('should allow requests with max root level query', async () => {
const res = await yoga.fetch('http://yoga/graphql', {
method: 'POST',
body: JSON.stringify({
query: /* GraphQL */ `
{
topProducts {
id
}
}
`,
}),
headers: {
'Content-Type': 'application/json',
},
});
expect(res.status).toBe(200);
});

it('should not allow requests with max root level query and nested fragments', async () => {
const res = await yoga.fetch('http://yoga/graphql', {
method: 'POST',
body: JSON.stringify({
query: /* GraphQL */ `
fragment QueryFragment on Query {
topBooks {
id
}
topProducts {
id
}
}
{
...QueryFragment
}
`,
}),
headers: {
'Content-Type': 'application/json',
},
});
})

it('should allow requests with max root level query in comments', async () => {
const res = await yoga.fetch('http://yoga/graphql', {
method: 'POST',
body: JSON.stringify({
query: /* GraphQL */ `
{
# topBooks {
# id
# }
topProducts {
id
}
}
`,
}),
headers: {
'Content-Type': 'application/json',
},
});

expect(res.status).toBe(200);
})
});
59 changes: 59 additions & 0 deletions packages/plugins/root-level-limitation/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
{
"name": "@graphql-yoga/plugin-root-level-limitation",
"version": "1.0.0",
"type": "module",
"description": "Apollo's federated check max root values plugin for GraphQL Yoga.",
"repository": {
"type": "git",
"url": "https://github.com/dotansimha/graphql-yoga.git",
"directory": "packages/plugins/root-level-limitation"
},
"author": "Saeed Akasteh <[email protected]>",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
},
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"exports": {
".": {
"require": {
"types": "./dist/typings/index.d.cts",
"default": "./dist/cjs/index.js"
},
"import": {
"types": "./dist/typings/index.d.ts",
"default": "./dist/esm/index.js"
},
"default": {
"types": "./dist/typings/index.d.ts",
"default": "./dist/esm/index.js"
}
},
"./package.json": "./package.json"
},
"typings": "dist/typings/index.d.ts",
"scripts": {
"check": "tsc --pretty --noEmit"
},
"peerDependencies": {
"@graphql-tools/utils": "^10.1.0",
"@envelop/core": "^5.0.0",
"graphql": "^15.2.0 || ^16.0.0"
},
"dependencies": {
"tslib": "^2.5.2"
},
"devDependencies": {
"@envelop/core": "^5.0.0",
"graphql": "^16.6.0",
"graphql-yoga": "5.3.0"
},
"publishConfig": {
"directory": "dist",
"access": "public"
},
"typescript": {
"definition": "dist/typings/index.d.ts"
}
}
47 changes: 47 additions & 0 deletions packages/plugins/root-level-limitation/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { createGraphQLError, getRootTypes } from '@graphql-tools/utils';
import { Plugin } from '@envelop/core';
import type { ValidationRule } from 'graphql/validation/ValidationContext';
import { isObjectType } from 'graphql';

export interface RootLevelQueryLimitOptions {
maxRootLevelFields: number;
}

export function createRootLevelQueryLimitRule(opts: RootLevelQueryLimitOptions): ValidationRule {
const { maxRootLevelFields } = opts;

return function rootLevelQueryLimitRule (context) {
const rootTypes = getRootTypes(context.getSchema());
let rootFieldCount = 0;
return {
Field() {
const parentType = context.getParentType();
if (isObjectType(parentType) && rootTypes.has(parentType)) {
rootFieldCount++;
if (rootFieldCount > maxRootLevelFields) {
throw createGraphQLError('Query is too complex.', {
extensions: {
http: {
spec: false,
status: 400,
},
},
});
}
}
},
};
};

}

export function rootLevelQueryLimit(opts: RootLevelQueryLimitOptions): Plugin {
const rootLevelQueryLimitRule = createRootLevelQueryLimitRule(opts);
return {
onValidate({ addValidationRule }) {
addValidationRule(
rootLevelQueryLimitRule
)
}
}
}
24 changes: 22 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions website/route-lockfile.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
/docs/features/persisted-operations
/docs/features/request-batching
/docs/features/response-caching
/docs/features/root-level-limitation
/docs/features/schema
/docs/features/sofa-api
/docs/features/subscriptions
Expand Down
1 change: 1 addition & 0 deletions website/src/pages/docs/features/_meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export default {
'file-uploads': 'File Uploads',
'defer-stream': 'Defer and Stream',
'request-batching': 'Request Batching',
'root-level-limitation': 'Root Level Limitation',
cors: 'CORS',
'csrf-prevention': 'CSRF Prevention',
'parsing-and-validation-caching': 'Parsing and Validation Caching',
Expand Down
60 changes: 60 additions & 0 deletions website/src/pages/docs/features/root-level-limitation.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
---
description:
This plugin enforces a limit on the number of root fields allowed in a GraphQL query, similar to
the `maxRootFields` option in Apollo Router. This can help to improve the performance and
stability of your GraphQL server by preventing overly complex queries.
---

# Root Fields

This plugin enforces a limit on the number of root fields allowed in a GraphQL query, similar to the
`maxRootFields` option in Apollo Router. This can help to improve the performance and stability of
your GraphQL server by preventing overly complex queries.

Here's an example query that fetches two root fields, `field1`, `field2` and `field3`:

```
query GetAllFields {
field { # 1
id
}
field2 { # 2
id
}
field3 { # 3
id
}
}
```

# Limit Root Fields

## Installation

```sh npm2yarn
npm i @graphql-yoga/root-level-limitation
```

## Quick Start

```ts
import { createServer } from 'node:http'
import { createSchema, createYoga } from 'graphql-yoga'
import { rootLevelQueryLimit } from '@graphql-yoga/root-level-limitation'

export const yoga = createYoga({
schema: createSchema({
typeDefs: /* GraphQL */ `
type Query {
hello: String!
}
`
}),
plugins: [rootLevelQueryLimit({ maxRootLevelFields: 1 })]
})

const server = createServer(yoga)
server.listen(4000, () => {
console.info('Server is running on http://localhost:4000/graphql')
})
```