How to handle errors and secure a REST API? - Part 4
Classify errors and faults, design the error body and apply the security techniques for a REST API: authentication, CORS and rate limiting.
How to handle errors and secure a REST API? - Part 4
Every API will fail at some point, either because the client sent a wrong request or because something went wrong inside the server. How the API communicates these failures decides how quickly a consumer can fix their request and how quickly we can find and fix our own problems. At the same time, a careless error message can leak stack traces or server details to an attacker. In the previous article, we discussed representations, status codes and verbs. In this article, we are going to see how to handle errors and faults, and how to secure a REST API at different layers.
REST API Design Guidelines series:
- Why REST and what makes an API RESTful?
- How to design resources and URIs for a REST API?
- How to use verbs, representations and status codes in a REST API?
- How to handle errors and secure a REST API? (this article)
- How to improve REST API performance and handle concurrency?
- How to handle long running requests, versioning, testing and documentation in a REST API?
TL;DR Summary
- HTTP errors fall into two categories: Error (client-side, 4xx) and Fault (server-side, 5xx).
- Every error and fault response must have a descriptive body, except for HEAD requests.
- Never send the stack trace, server, log or metric details in an error response.
- Log all server-side faults for investigation and monitoring.
- Allow only authenticated and authorized users and applications to access restricted resources.
- Enable the latest TLS, validate and sanitize input, configure CORS for browser consumers and rate limit all public facing APIs.
Exception Handling
HTTP is based on the exchange of representations, and that applies to errors as well. The server will encounter an error either because of problems with the client request or problems within the server. In case of any error, the server should send a representation that contains the state of the error condition. This includes the response status code, response headers and a body containing the description of the error. HTTP errors are classified into two categories,
- Error
- Fault
Error
It represents a client-side error, and the server should return a 4xx status code when the error is due to client input. The following list shows the status code mapping for some predefined errors.
400 - Return this status code along with an appropriate message when the request is not valid or contains any malicious input.
Example:
Given https://api.example.com/api/news/**** when the expected format is https://api.example.com/api/news/234343,

and https://api.example.com/api/news/<script></script>,

401 - Return this status code along with an appropriate message when the request is trying to access the resource without providing valid credentials. The client may gain access after it is successfully authenticated.
Example:
https://api.example.com/api/users/3434333

403 - Return this status code when the user is authenticated but not authorized to access the resource.

404 - Return this status code when the given resource is not found.

405 - Return this status code when the given method is not supported by the resource.

415 - Return this status code when the client requests with an unsupported media type.

429 - Return this status code when the client is making too many requests from the same IP.
Fault
It represents a server-side error, and the server should return a 5xx status code when a server-side error occurs. All server-side errors should be logged for developer analysis. The following list shows the status code mapping for some predefined faults.
500 - Return this code when a server-side error occurs.
503 - Return this code when the back-end server (data store) does not respond within the specified timeout.
Message body for errors
Include a body in the error response for all errors (for both error and fault), except when the HTTP method is HEAD. In the body, include some or all of the following,
- A brief message describing the error condition
- A longer description with information on how to fix the error condition, if applicable
- An identifier for the error
- A link to learn more about the error condition, with tips on how to resolve it
And make sure you,
- Don’t share stack trace details.
- Don’t share any details about the server, logs and metrics.
Example:
{
"code": "<error identifier>",
"message": "Invalid request or malicious request",
"description": "<how to fix the error condition>",
"link": "<link to learn more about this error>"
}
Security
Security means different things at different layers and parts of a system. It means we need to apply various techniques at different parts of a system, and some of the techniques are as follows,
- Ensure that only authenticated and authorized users access the restricted resources.
- Ensure that only authorized applications can access your APIs when the consumer is another system instead of a user (web browser).
- Encode or sanitize the data whenever required.
- Enable the latest version of TLS.
- Configure an input validation module (middleware) for all requests.
- Validate the incoming representation.
- Ensure the confidentiality and integrity of information right from the moment it is collected until the time it is stored and later presented to authorized entities or users.
- Configure CORS when your consumers are web browsers.
- Configure rate limiting.
- Restrict the access to pre-production environments to prevent public access. In our case, we use the Cloudflare Zone Lockdown rule for this.
Authentication/Authorization
Authentication is the process of validating the identity of a user, and Authorization is the process of validating a user’s access rights. It is highly recommended to use OAuth2 and OpenID Connect compliant services. In our case,
- We use Azure AD B2C for user authentication.
- We use Azure AD for app authentication.
- We use our existing identity service when we want to use the existing user base.
Confidentiality and Integrity
Apply the following techniques for confidentiality and integrity,
- Enable the latest TLS version (HTTPS), which will enable a secure channel between the consumer and the provider.
- Validate the incoming representation.
- Encode or sanitize when the data contains HTML or XML. It is not mandatory, but you must consider it.
- Use HMAC with SHA-256 or a later hash algorithm to detect data tampering when communication happens between two systems.
- Enable file, storage or database level encryption.
- Mask the data at the data store when it is required.
CORS
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have access permission to a resource from a server at a different origin. It prevents somebody from consuming our APIs directly from their web applications in the browser.
Restrict the resource access from cross domains for all or selected resources with the following headers,
Access-Control-Allow-Origin: https://www.domain1.com
Access-Control-Allow-Headers: header1, header2
Note:
Access-Control-Allow-Originaccepts only one origin (or*). When you want to allow more than one domain, check the requestOriginheader against your allowed list and return the matching origin.
Must Do: It is mandatory to configure CORS when your primary consumers are web browsers.
Rate Limit
All public facing APIs must be configured with rate limiting. In our case, we configure it at Cloudflare.
When a consumer makes too many calls and exceeds the allowed threshold, then the service must send the 429 status code. The service should return the 503 status code to the client when it is overloaded or load shedding.
Best practices checklist
Fault Handling
- Send 4xx response codes for request related errors.
- Send 5xx response codes for server level exceptions.
- Send 500 status when server level operations failed.
- Send 503 status when the underlying data store or service failed to connect.
- Don’t send the stack trace or any other sensitive information along with a fault or error.
- All server level exceptions should be logged for investigation and monitoring.
- All error or fault responses should contain a descriptive message for the error condition.
Security
- Allow only authenticated and authorized users to access the restricted resources.
- Should use app authentication when the consumer is another system or a mobile app.
- Must enable the latest version of TLS.
- Should encode or sanitize the data when it is required.
- Should configure the input validation module.
- Should validate the incoming representation.
- Should configure CORS to avoid direct consumption of the API from domains which are not allowed.
- Should restrict public access to pre-production environments.
- Should enable file level or data store level encryption.
- Should use input masking at the data store when it is required.
Wrap up
In this article, we have looked at how to classify and respond to errors and faults, what to include in an error body, and the security techniques for authentication, confidentiality and integrity, CORS and rate limiting. I really appreciate that you took the time to read this article. In the next article, I will walk you through how to improve the API performance with caching, conditional GET and compression, and how to handle concurrency.
Related Posts
How to design resources and URIs for a REST API? - Part 2
Identify resources from domain nouns and functions, choose the right granularity with an example and follow the conventions to design URIs.
How to handle long running requests, versioning, testing and documentation in a REST API? - Part 6
Design long running requests with 202 and a status resource, define breaking changes and version an API, and cover testing and documentation with OpenAPI.
How to improve REST API performance and handle concurrency? - Part 5
Improve REST API performance with Cache-Control, conditional GET, ETag and compression, and handle concurrency with optimistic locking.