All jobs

Add Query Depth Limits to a GraphQL API

Yes. An agent adds a depth rule to the server's validation step, sets the limit from the queries the project really sends, and shows a deep query being refused.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

A depth limit belongs where the server validates a query, before any resolver runs, so the agent first finds that place and what the schema allows today. In a server like graphql/swapi-graphql, handler/graphql.mjs builds its Netlify function with createHandler({ schema: schema.default }) from graphql-http and passes no validationRules, and it answers every origin with Access-Control-Allow-Origin: *. The schema under src/schema is cyclic by design: a Film has a characterConnection of Person, a Person has a filmConnection of Film, and so on through planets, species, starships and vehicles. Nothing stops a query from following that loop as many levels down as its author cares to type.

Reading the resolvers shows why capping page size would not be enough here. connectionFromUrls in src/schema/connections.js loads every object in the relation with getObjectsFromUrls and only then slices the array with connectionFromArray, so first: 1 trims the response and not the work. Depth is the control that bounds it. The agent adds a validation rule that walks the operation, follows fragment spreads, and reports an error when the nesting passes a limit. package.json pins graphql at 14.5.8, so it either uses graphql-depth-limit, whose published peer range accepts any graphql version, or writes the rule itself against the visitor API of that version. It says which it chose and why, and puts the rule in src so that Babel builds it into lib beside the schema the handler imports.

Two details decide whether the change is safe to merge. The first is how the rule is passed: graphql-http appends an array of validationRules to graphql-js's standard rules, while a function replaces them, so the agent passes an array and keeps the standard checks. The second is the number. A limit set too low breaks real clients and the introspection query that GraphiQL sends on load, which nests several levels through ofType. The agent measures before it chooses: it computes the depth of every query in the specs under src/schema/__tests__ and of the introspection query that the GraphiQL page in public/index.html sends, then sets the limit above the deepest legitimate one and reads it from an environment variable with that default.

It tests at two levels. Jest specs call graphql-js's validate with the standard rules plus the new one: a query at the limit passes, one level deeper fails with a message naming the limit, a deep query hidden behind nested fragments fails the same way, and introspection passes. Then it runs the server for real. npm install runs the postinstall script, which downloads the Star Wars data into cache/data.json and builds lib; the README's description of a local express server is out of date, so the agent follows package.json, where npm run watch starts netlify dev. With that running it posts an ordinary query and a deeply nested one with curl and records the status code and body of each. npm test runs ESLint, flow check and Jest, and all three have to pass with the new file.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "A GitHub issue labelled security says this GraphQL server accepts queries of any depth. Read package.json, handler/graphql.mjs, netlify.toml, src/schema/index.js, src/schema/connections.js, src/schema/apiHelper.js and the specs under src/schema/__tests__ first. Trust package.json scripts over the README where they disagree, and say where they disagree. In the pull request, show one cycle in the schema with the field names that form it, and say whether the connection resolvers load a whole relation before slicing it. Add a validation rule that limits query depth, counting through fragment spreads. Either add graphql-depth-limit, after checking it supports the pinned graphql version, or write the rule against that version's visitor API; say which and why. Put the rule under src so the build includes it, and pass it to createHandler as an array of validationRules so the standard rules still apply. Before choosing the limit, measure the depth of every query in the specs and of the standard introspection query that the GraphiQL page in public/index.html sends, list them, and set the default above the deepest; read the limit from an environment variable. Add Jest specs using validate: at the limit, one past it, deep through nested fragments, and introspection. Run npm install, then npm test, then start the server with npm run watch and post one ordinary and one too-deep query with curl; paste both status codes and bodies. State what a depth limit does not stop, such as many aliases of one wide field. Open a pull request that closes the issue.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

The pull request changes handler/graphql.mjs, adds the rule and its spec under src, and touches package.json and package-lock.json only if a dependency was added. The description starts with the cycle it found, written as a query a reader can paste, and the finding about the connection resolvers. A table follows with the measured depth of each query it found: one line per spec file, and one for introspection. The chosen default sits under it with the name of the variable that overrides it.

The verification section holds the npm test output and the two curl exchanges against the local server: the ordinary query with its data, and the nested one with its status code and the errors entry naming the limit it passed. Because the rule runs during validation, the refused query never reaches a resolver, and the description points at the server log to show no data was loaded for it.

It closes with what remains open. Depth does not bound breadth: a query can alias one wide connection many times at a shallow depth, and stopping that needs a complexity budget, which is a larger change the description outlines without making. A reviewer checks the limit against clients the repository cannot see, such as a mobile app with its own queries, and decides whether the wide-open CORS header is still wanted.

Run it on every GitHub issue labelled security

Findings from a penetration test or a scanner usually land as issues. Add an automation to the Project in the console with a github trigger on issues.labeled and the label security, and a saved prompt that states the method: locate where the server validates queries, measure what real clients send, add the limit as a validation rule, test it in Jest and against the running server, and say what the limit leaves uncovered. Each labelled issue is added after that prompt and starts one run.

Switch the automation's Read only setting on for a first pass if you want findings before fixes: its runs can read the repository and comment, and cannot push. From a script, the equivalent is one POST /o/{org}/sessions per issue with a request_id that is a UUID v5 of the issue URL, so a second delivery of the same issue returns the run already started.

The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.

Why run it on Rush?

The limit is only as good as the number, and the number comes from measurement. The agent parses every query the repository contains, computes its depth and sets the default from that list, then starts the server and sends a query past the limit to watch it be refused. Each of those steps is a command with output, kept in the run's transcript and quoted in the pull request. A reviewer can see that GraphiQL still loads and that the refusal happens before any resolver runs.

This repository also shows why the work is done in a clean sandbox. Its install step downloads data from an external API and compiles the schema with Babel, its README describes a server layout that no longer exists, and its test command chains a linter, Flow and Jest. An agent that runs all of that from an empty machine finds the mismatches, and the pull request records them. On a laptop that has had the project installed for years, the stale README goes unnoticed.

Frequently asked questions

Will the limit break GraphiQL or schema introspection?

It should not, and a test guards it. The standard introspection query is one of the queries the agent measures before picking the default, and a Jest spec asserts it still validates. If you disable introspection in production, say so and that spec is dropped.

Does it work with Apollo Server, Yoga or another server?

Yes. All of them validate with graphql-js rules, and each has its own option for adding one. The agent reads which server your handler uses and passes the same rule through that option; the Jest specs do not change.

Is a depth limit enough to stop expensive queries?

No. It stops unbounded nesting, which is the cheapest attack on a cyclic schema. A shallow query can still request a wide field many times under different aliases. The description says so and sketches a complexity budget as the follow-up.

What does a client see when its query is too deep?

A validation error in the standard errors array, with a message that names the limit, and no data. The pull request pastes the exact response from the local server so client developers know what to handle.

More GraphQL jobs

More jobs like this: Turn a Linear label into a PR

Keep reading