Security - Add complexity max on gql queries (#16069)
closes https://github.com/twentyhq/private-issues/issues/348 closes https://github.com/twentyhq/private-issues/issues/352 closes https://github.com/twentyhq/private-issues/issues/353 closes https://github.com/twentyhq/private-issues/issues/354
This commit is contained in:
+33
@@ -0,0 +1,33 @@
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { type ValidationContext } from 'graphql';
|
||||
import { type Plugin } from 'graphql-yoga';
|
||||
|
||||
import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
|
||||
|
||||
export const useComputeComplexity = (maximumComplexity: number): Plugin => ({
|
||||
onValidate: ({ addValidationRule }) => {
|
||||
addValidationRule((context: ValidationContext) => {
|
||||
let complexity = 0;
|
||||
|
||||
return {
|
||||
Field() {
|
||||
complexity++;
|
||||
},
|
||||
Document: {
|
||||
leave() {
|
||||
if (complexity > maximumComplexity) {
|
||||
context.reportError(
|
||||
new UserInputError(
|
||||
`Query complexity is too high: ${complexity} - Too many fields requested`,
|
||||
{
|
||||
userFriendlyMessage: msg`The request is too complex to process. Please try reducing the amount of data requested.`,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user