Overview
In this module, we will cover how we can set limits in our incoming queries to protect our backend resources.
Operation limits
To ensure that we have the proper protection against malicious (or ill-formed) queries, we need to have some GraphQL-specific safeguards in place. For this, we will use a feature of Apollo GraphOS called operation limits.
Operation limits prevents running queries that put excess strain on our service. We can place height, depth, and alias limits on our graph via our router configuration.
We can configure the following properties:
max_height
: Limits the number of unique fields included in an operation, including fields of fragments. If a particular field is included multiple times via aliases, it's counted only once.max_depth
: Limits the deepest nesting of selection sets in an operation, including fields in fragments.max_aliases
: Limits the total number of aliased fields in an operation, including fields of fragments.max_root_fields
: Limits the number of root fields in an operation, including root fields in fragments. If a particular root field is included multiple times via aliases, each usage is counted.
The current state
Let's run a complex query against our graph.
Open up Studio and navigate to the Explorer.
We want to run a query that has a height greater than
10
. Here is a good example query to run:A query with a lot of heightquery ALotOfHeight {getFeaturedProducts {descriptionfeaturedidimagesnamepriceshortDescriptionskuvariants {colorwayidinStockpricesize}}}We should get data back!
https://studio.apollographql.com
Configuring operation limits
In the GitHub repo, navigate to the
router
folder and open up therouter.yaml
fileAdd the following lines into the
router.yaml
file to enable operation limits:limits:max_depth: 5max_height: 10max_aliases: 3This will instruct the router to block any requests that exceed these limits.
Commit the changes
https://github.com
Check your work
Navigate back to Studio and open up the Explorer
Run the same query as before:
A query with a lot of heightquery ALotOfHeight {getFeaturedProducts {descriptionfeaturedidimagesnamepriceshortDescriptionskuvariants {colorwayidinStockpricesize}}}With our operation limits in place, we should see the query fail with the error code
MAX_HEIGHT_LIMIT
and the messageMaximum height (field count) limit exceeded in this operation
https://studio.apollographql.com
Feel free to play with other queries that exceed our new operation limits. Our graph is now more secure, and all it took was a few lines of configuration!
Up next
In the next module, we'll lock down what type of queries can be executed against our graph so that only pre-approved queries can be run.