Skip to content
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

feat(root-level-limitation): add max root fields limitation plugin #3233

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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,67 @@
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);
});
});
60 changes: 60 additions & 0 deletions packages/plugins/root-level-limitation/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"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 <srcgrp@gmail.com>",
"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",
"@whatwg-node/server": "^0.9.32",
"graphql": "^15.2.0 || ^16.0.0",
"graphql-yoga": "^5.3.0"
},
"dependencies": {
"tslib": "^2.5.2"
},
"devDependencies": {
"@whatwg-node/fetch": "^0.9.17",
"graphql": "^16.6.0",
"graphql-yoga": "5.3.0"
},
"publishConfig": {
"directory": "dist",
"access": "public"
},
"typescript": {
"definition": "dist/typings/index.d.ts"
}
}
79 changes: 79 additions & 0 deletions packages/plugins/root-level-limitation/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { createGraphQLError } from '@graphql-tools/utils';

interface GraphQLParams {
operationName?: string;
query?: string;
}

export function rootLevelQueryLimit({ maxRootLevelFields }: { maxRootLevelFields: number }) {
return {
onParams({ params }: unknown) {
const { query, operationName } = params as GraphQLParams;

if (operationName?.includes('IntrospectionQuery')) return true;

const newQuery = formatQuery(query || '');
const linesArray = newQuery.split('\n');

let countLeadingSpacesTwo = 0;

for (const line of linesArray) {
const leadingSpaces = line?.match(/^\s*/)?.[0]?.length || 0;

if (leadingSpaces === 4 && line[leadingSpaces] !== ')') {
countLeadingSpacesTwo++;

if (countLeadingSpacesTwo > maxRootLevelFields * 2) {
throw createGraphQLError('Query is too complex.', {
extensions: {
http: {
spec: false,
status: 400,
headers: {
Allow: 'POST',
},
},
},
});
}
}
}

return true;
},
};
}

function formatQuery(queryString: string) {
queryString = queryString.replace(/^\s+/gm, '');

let indentLevel = 0;
let formattedString = '';

for (let i = 0; i < queryString.length; i++) {
const char = queryString[i];

if (char === '{' || char === '(') {
formattedString += char;
indentLevel++;
// formattedString += ' '.repeat(indentLevel * 4);
} else if (char === '}' || char === ')') {
indentLevel--;

if (formattedString[formattedString.length - 1] !== '\n')
formattedString = formattedString.trim().replace(/\n$/, '');

if (char === ')') formattedString += char;

if (char === '}') formattedString += '\n' + ' '.repeat(indentLevel * 4) + char;
} else if (char === '\n') {
if (queryString[i + 1] !== '\n' && queryString[i + 1] !== undefined) {
formattedString += char + ' '.repeat(indentLevel * 4);
}
} else {
formattedString += char;
}
}

return formattedString;
}
Loading