How to secure GraphQL APIs: challenges and best practices
GraphQL APIs, while offering robust features and flexibility, present unique security challenges compared to traditional REST APIs. This article delves into the complexities of securing GraphQL APIs, highlighting common vulnerabilities and providing a comprehensive guide to best practices for building secure GraphQL apps.
A visual learner? Check out our latest webinar on GraphQL security:
Why GraphQL APIs are challenging to secure
Complex query capabilities
GraphQL APIs allow for complex queries with features like batching, aliasing, and fragments. These capabilities, while useful, increase the attack surface significantly. Attackers can exploit these features to perform brute force attacks, denial of service, and more.
Graph Structure
The inherent graph structure of these APIs means multiple paths might lead to the same data. Ensuring robust access control across all possible paths can be daunting, requiring meticulous security measures to prevent unauthorized access.
Common vulnerabilities in GraphQL APIs
- API Brute Forcing : GraphQL APIs allow batching and aliasing, where multiple queries can be sent in a single HTTP request. This can be exploited to bypass rate limits set at the gateway or firewall level. For instance, an attacker could send thousands of queries in one request, overwhelming the API without triggering rate limiting mechanisms. This vulnerability is particularly dangerous when combined with login functionalities, enabling attackers to attempt numerous login combinations within a single request, potentially leading to account takeovers.
GraphQL Bombs: This type of attack exploits the file upload feature combined with aliasing. An attacker can upload a file and create multiple aliases for it in a single query, causing the server to store multiple copies of the file. This can quickly consume server storage space, leading to a denial of service. Such attacks exploit the API's ability to handle complex queries, turning it against the system to cripple it with minimal effort from the attacker. Find out more about GraphQL bombs. - Recursive Queries: GraphQL APIs support fragments, which are reusable pieces of queries, akin to functions in programming. If a fragment is designed to call itself recursively without adequate controls, it can lead to an infinite recursion loop. This vulnerability can crash the API server by overwhelming it with continuous recursive calls, similar to a denial of service attack. This issue highlights the need for careful design and validation of recursive functionalities within GraphQL APIs.
- Schema Leakage: Endpoints with disabled introspection still leak underlying API schema through field suggestion. Using open source tool Clairvoyance, anybody can build back the full schema. Be careful about deactivating all development features and avoiding error messages or error messages that are two verbals in production because that discloses a lot of information from the APIs. Learn more about schema leakage in our webinar.
- Security Misconfiguration: these vulnerabilities are mostly due because Federated GraphQL apps often forget to catch error messages from underlying APIs. And also because a lot of graph dual end points have development features enabled in production.
- Insecure Direct Object References: Without proper authorization checks, attackers can manipulate API resources, leading to data breaches.
Best practices for securing GraphQL APIs
For security engineers
- Take back control of the API attack surface. Build an API inventory.
You should be able to answer the following questions:
- How many APIs does my company expose externally?
- Which of them are critical to the business?
- Which of them manipulates sensitive data?
- Do we have any development endpoints exposed on the internet? Do we have any unnecessarily exposed endpoints?
- Do some GraphQL API threat modeling. “If I was an attacker, how could I use GraphQL APIs to threaten the business?”
- Talk with the developers. Understand how they build their APIs. Work closely with them to ensure they understand the security implications of the features they implement. Promote a security-focused culture that prioritizes API security from the design phase through to deployment. Give examples.
4. Implement best practices throughout the API lifecycle:
- Implement an API Gateway
- Implement secret scanning, especially on front-end repositories
- Test every API release for OWASP API Top 10 and business logic flaws. If possible, do it as early as in the CI/CD
- Have proper security monitoring for live API traffic
For developers
Limit Access control with Authorization and Authentication
Without the appropriate authorization-check layer, private data and high-access features may be exposed to unauthorized users. Ensure enforcement of authorization and authentication rules through a cleaner approach using resolver middleware.
Input validation
The best way to protect your API from injections is to use input validation for all incoming requests, write custom validators for domain-specific and more complex validations. graphql-scalars can help
Rate limiting to block brute force attacks
Use the graphql-limit-plugin to specify this limit on your queries and mutations. The best way to set it up is to set a large time window between queries/mutations when they are highly vulnerable (like a sign in) and a shorter one for less vulnerable queries/mutations. That way you only limit attackers and not your users.
Depth Limiting
You can use the graphql-armor package to easily limit the depth of queries. First, check how deep you expect queries to be, and then set a maximum depth accordingly.
Schema Whitelisting
Limit the exposed schema to only include necessary types and fields, reducing the attack surface. You can use persistgraphql by Apollo or graphql-codegen from The Guild to auto-generate a list of approved queries at build time.
Limit the Cost of GraphQL Queries
You can use the graphql-armor package to easily limit the cost of queries. First, make an estimate of your resolvers’ cost for your database and third-party services, then implement a hard limit on each query.
Useful GraphQL security tools
Leverage tools like GraphQL Armor and other middleware solutions to enforce security best practices such as rate limiting, depth limiting, and query whitelisting.
Authentication & Authorization
- GraphQL Shield - GraphQL Shield helps you create a permission layer for your application.
- GraphQL Authz - GraphQL authorization layer
Security
- GraphQL Armor - Highly customizable security middleware for Apollo GraphQL and Yoga/Envelop servers.
- GraphQL Protect - A dead-simple yet highly customizable security sidecar compatible with any HTTP GraphQL Server or Gateway.
- GraphQl-scalars - validate GraphQL input parameters
- GraphQL Cop - Utility to run common security tests against GraphQL APIs that can be run inside CI/CD.
Tools
- Graphql.security - a free tool that runs a dozen common security tests on a given GraphQL endpoint. (for continuous scanning you can use the Escape GraphQL Security platform)
Conclusion
Securing GraphQL APIs requires a detailed understanding of their unique features and potential vulnerabilities. By implementing robust security practices and leveraging specialized tools, organizations can protect their APIs from emerging threats. As GraphQL APIs continue to evolve, so too should the strategies used to secure them, ensuring safe and reliable operations. Things can get real complex real fast—that's why companies love Escape.
Our comprehensive solution can streamline this process by quickly identifying issues across your API endpoints and providing remediation snippets—all in as little as 15 minutes, without complex integrations or traffic monitoring.
đź’ˇ Want to learn more? Check the following articles: