skip to content
Samuel Edwin's Website

Protecting GraphQL Server From Malicious Queries

/ 2 min read

GraphQL’s flexibility is its biggest strength, and also its biggest weakness.

It’s easier to abuse GraphQL servers than REST APIs through queries.

This is a quite common problem that open source and commercial solutions exist to solve this.

Let’s explore some of them.

1. Nested Queries

GraphQL allows us to nest queries within queries so we can get all data in one request.

This also means the attacker can nest queries indefinitely.

query {
user(id: 1) {
friends {
friends {
friends {
friends {
# Nest it forever
}
}
}
}
}
}

Solution

Limit the maximum depth of the queries.

2. Alias abuse

GraphQL allows us to alias fields in the response.

query {
popularProducts: products(sort: "POPULARITY") {
id
name
}
bestSellingProducts: products(sort: "BEST_SELLING") {
id
name
}
}

Attackers can use an absurd amount of aliases to make the query slow.

query {
a: products(sort: "POPULARITY") {
id
name
}
b: products(sort: "POPULARITY") {
id
name
}
c: products(sort: "POPULARITY") {
id
name
}
# ... more aliases
}

Solution

Implement max aliases limit.

Big query abuse

Attackers can send a query with a huge size.

Practically all query operations available for the server can be used all at once, increasing the server load.

query {
searchProducts(keyword: "phone") {
id
name
}
product(id: 1) {
id
name
description
price
shop {
id
name
}
}
shop(id: 1) {
id
name
address
products {
id
name
description
price
}
}
user {
id
name
email
orders {
id
products {
shop {
id
name
}
}
}
}
}

Solution

Implement Cost limit and character limit.

Introspection

GraphQL has a feature called introspection.

It allows us to query the schema of the API to get information about the types, fields, and relationships in the API.

This means attackers can use introspection to get a complete information of our GraphQL server.

Solution

Disable introspection in production.

Conclusion

There are many ways attackers can abuse GraphQL servers.

This post only cover the most popular attacks, and there are many other attacks out there.

OWASP has a great overview of common GraphQL security problems and solutions.

I’d suggest you to give it a read.

Open source solutions like GraphQL Armor can be used to protect your server against malicious queries.

In case open source solutions are not enough, I’d advise you to use commercial solutions like Stellate and Escape (disclaimer: Not affiliated to any of them).