How do you prevent nested attack on GraphQL server?

Technology CommunityCategory: GraphQLHow do you prevent nested attack on GraphQL server?
VietMX Staff asked 3 years ago
Problem

Consider the query:

{
  authors {
    firstName
    posts {
      title
      author {
        firstName
        posts{
          title
          author {
            firstName
            posts {
              title
              [n author]
                [n post]
            }
          }
        }
      }
    }
  }
}

In other words, how can you limit the number of recursions being submitted in a query?

I’ll just list all of the different methods:

  • Query validation – in every GraphQL server, the first step to running a query is validation – this is where the server tries to determine if there are any serious errors in the query, so that we can avoid using actual server resources
  • Query timeout – if it’s not possible to detect that a query will be too resource-intensive statically (perhaps even shallow queries can be very expensive!), then we can simply add a timeout to the query execution.
  • Query whitelisting – you could compile a list of allowed queries ahead of time, and check any incoming queries against that list
  • Query cost limiting – similar to query timeouts, you can assign a cost to different operations during query execution, for example a database query, and limit the total cost the client is able to use per query

(1) and (2) in particular are probably something every GraphQL server should have by default, especially since many new developers might not be aware of these concerns.

Also there are some Node.js implementations that impose cost and depth bounds on incoming GraphQL documents.

  • graphql-depth-limit
  • graphql-validation-complexity
  • graphql-query-complexity