Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views16 pages

Securing API Servers

The document outlines a course designed to enhance the security of API servers, targeting developers, DevOps, and security professionals. It covers critical topics such as Cross-Origin Resource Sharing (CORS), error disclosure, server information leaks, and insecure cookies, providing best practices and real-world attack scenarios. The course aims to equip learners with actionable insights to mitigate common security risks associated with API servers.

Uploaded by

mdmasumbillah628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views16 pages

Securing API Servers

The document outlines a course designed to enhance the security of API servers, targeting developers, DevOps, and security professionals. It covers critical topics such as Cross-Origin Resource Sharing (CORS), error disclosure, server information leaks, and insecure cookies, providing best practices and real-world attack scenarios. The course aims to equip learners with actionable insights to mitigate common security risks associated with API servers.

Uploaded by

mdmasumbillah628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Securing API Servers

Introduction
Course Overview
This course is designed to help professionals better secure API servers based on real-world observations and
best practices. It provides actionable insights into API security configurations that are often overlooked or
misunderstood, but critical for protecting systems.
Who This Course Is For
• Developers
• Operations (DevOps) professionals
• Security professionals
• Anyone working at the intersection of development, operations, and security
Course Format
• Divided into six independent sections, each focusing on a high-value security area.
• Scenarios and justifications are provided to explain why each topic matters in practical environments.
• Sections can be completed in any order.
Course Goals
• Help learners understand the most commonly encountered security risks in API servers.
• Provide clarity on configurations and patterns that enhance API security.
• Offer guidance grounded in real-world experience and common pitfalls.
Certification
A certificate of completion is available at the end of the course. This can be showcased on professional
platforms like LinkedIn or added to your resume to demonstrate proficiency in API security.
Getting Started
The course is ready to be taken online. Learners are encouraged to follow along actively, as the material is
intended to offer immediate practical value.

Cross Origin Resource Sharing (CORS)

What is CORS?
CORS (Cross-Origin Resource Sharing) is a browser-enforced security mechanism that determines whether
and how a browser should allow JavaScript from one origin (domain) to access resources from a different
origin.
• It only applies to browser-based requests, not to tools like curl, Postman, or scripts that make direct
HTTP requests.
• CORS uses a set of HTTP headers sent by the API server to specify which origins, methods, and headers
are permitted.
• The browser is responsible for enforcing the CORS policy—servers simply suggest rules.
Why is CORS Important?
CORS exists to prevent cross-site request abuse, which can occur when a malicious site tries to use a logged-in
user’s browser to interact with an API they are authorized to access.
Typical threat scenario:
• An attacker sets up a fake website that silently makes requests to your API using the victim's browser.
• If CORS is misconfigured (e.g., Access-Control-Allow-Origin: *), the attacker could potentially access
sensitive data or perform unwanted actions.

Key CORS Headers


Header Purpose
Access-Control-Allow-Origin Specifies the allowed origin(s). Can be a specific domain or *.
Access-Control-Allow-Methods Specifies the HTTP methods allowed (e.g., GET, POST, PUT).
Access-Control-Allow-Headers Lists allowed custom headers in requests.
Access-Control-Allow-Credentials Allows cookies and credentials to be sent in cross-origin requests.
Access-Control-Max-Age How long the results of a preflight request can be cached.

Two Types of CORS Requests


1. Simple Requests
o Automatically allowed if they meet specific criteria.
o Only use methods like GET, POST, or HEAD, and headers like Content-Type: application/x-www-
form-urlencoded.
o Browser directly sends the request and enforces CORS in the response.
2. Preflighted Requests
o Use a preflight OPTIONS request to check with the server whether the actual request is safe to
send.
o Used when custom headers, methods (PUT, DELETE, etc.), or credentials are involved.

Common Misuse and Developer Pitfall


• Developers often encounter CORS errors when working on a local frontend that tries to access a remote
API.
• The error might look like:
• Access to fetch at '<https://api.example.com>' from origin '<http://localhost:3000>' has been blocked
by CORS policy.
• In search of a quick fix, developers frequently follow advice like:
• const cors = require('cors');
• app.use(cors()); // allows all origins (insecure!)
• This sets Access-Control-Allow-Origin: *, disabling all protection and often goes unnoticed into
production.

Real-World Attack Scenarios


Scenario 1: Open API Access via Wildcard Origin
• A malicious site (red.com) embeds a script that makes calls to https://api.trustedsite.com.
• If api.trustedsite.com responds with:
• Access-Control-Allow-Origin: *
then the browser allows the cross-origin request.
• Result: The malicious site can abuse the API through the user's browser (if authenticated), stealing data
or performing actions on their behalf.
Scenario 2: Secure Access via Restricted Origin
• If api.trustedsite.com responds with:
• Access-Control-Allow-Origin: <https://trustedfrontend.com>
then only requests originating from trustedfrontend.com will be allowed by the browser.
• A request from a malicious site will be blocked by the browser before even hitting the server.
Scenario 3: Inbound Content Injection
• Your legitimate site loads an embedded iframe or script from a compromised domain.
• If the browser doesn’t enforce content isolation, malicious scripts could run inside your origin’s context.
• Setting the header:
• Cross-Origin-Resource-Policy: same-site
protects against this by preventing resources from being loaded into other sites.

Recommendations for Developers and Security Teams


1. Never use Access-Control-Allow-Origin: * in production, especially on APIs that deal with user
authentication, tokens, or sensitive data.
2. Whitelist known, trusted origins explicitly:
3. app.use(cors({
4. origin: ['<https://trustedapp.com>', '<https://admin.trustedapp.com>'],
5. credentials: true
6. }));
7. Avoid whitelisting localhost or 127.0.0.1 unless it’s for isolated development only.
8. Use security headers like Cross-Origin-Resource-Policy, Content-Security-Policy, and X-Frame-Options
to reinforce client-side protections.
9. Use libraries like Helmet in Express.js:
10. npm install helmet
11. const helmet = require('helmet');
12. app.use(helmet()); // applies a broad set of security headers
13. Audit CORS policies regularly. Misconfigurations are often introduced during early development and
forgotten as code moves to production.

Final Thoughts
• CORS is not a security control for APIs against direct server-side attacks. Tools like Postman, curl, or
malicious bots do not enforce CORS.
• It is a browser-based protection mechanism and must be configured to protect users from malicious
cross-origin interactions.
• Misunderstanding or overlooking CORS leads to frequent vulnerabilities in modern web applications.
• Following secure defaults, using proper tooling, and understanding its limitations ensures robust
defense for your APIs.

Error Disclosure

Error Disclosure refers to unintentionally exposing internal system or technology details through error
messages that are accessible to end users or potential attackers. While error handling is essential in
development, how errors are reported has significant security implications.

What is Error Disclosure?


When error messages return excessive or sensitive system information (such as stack traces, file paths, or
technology details) to the user interface or client, that constitutes error disclosure.
This data can assist attackers in:
• Understanding the technology stack
• Discovering potential vulnerabilities
• Planning targeted attacks based on known weaknesses
It may not always be visible in the user interface; even API responses or browser console messages count as
error disclosures if they leak internal data.

Why Is Error Disclosure Dangerous?


1. Leaks system internals – Revealing information such as programming language, frameworks (e.g.,
Spring), database type, or server structure gives attackers a head start.
2. Facilitates vulnerability discovery – Attackers can correlate exposed technologies with known CVEs
(Common Vulnerabilities and Exposures).
3. Bypasses UI protection – Frontend validations (like email format) can be bypassed by directly
interacting with APIs. Attackers are not bound by UI restrictions.

Common Mistakes in Error Handling


1. Detailed error messages shown to users
o e.g., “Invalid email address” → Helps attacker enumerate valid email accounts.
2. Returning exception messages from backend
o Unfiltered exceptions from frameworks (e.g., Spring or Node.js) can reveal internal logic or stack
traces.
3. Uniform vs. variable error messages
o Varying error messages (e.g., "user not found" vs. "incorrect password") allow account
enumeration.

Secure Error Handling Practices

1. Separate Developer Logs and User Messages


o Developers need detailed logs (e.g., stack traces), but users should receive only generic
messages.
o Log details to a secure internal log file or system (e.g., ELK, CloudWatch).
2. Use generic user-facing errors
o Example: “An error occurred. Please try again.” or “Invalid credentials.”
o Do not specify whether the email or password is wrong.
3. Catch and sanitize exceptions
o Use try/catch or try/except blocks to control error flow.
o Instead of returning the exception to the client, log it internally and send a generic message.
Python Example:
try:
result = perform_database_query()
except Exception as e:
log.error(f"Exception occurred: {str(e)}") # Log internally
return "An unexpected error occurred." # Generic response

Node.js Example:
try {
const result = await dbQuery();
} catch (err) {
console.error(err); // Internal log
res.status(500).send("Server error."); // Generic response
}

4. Avoid default error responses


o Many frameworks (e.g., Express.js, Spring Boot) may expose stack traces by default in dev
mode. Disable this in production.

Real-World Examples
1. API Error Disclosures
o An API response leaking that it’s built with Spring framework helps attackers find related CVEs
or predict libraries in use.
2. Generic API Message (Recommended)
o “Something is wrong. Check the input and try again.” – Doesn’t help an attacker determine if
the input failed due to format or non-existence.
3. GitHub 404 Page (Good Practice)
o GitHub uses the same 404 error whether a resource doesn’t exist or you lack permission.
o Prevents attackers from confirming whether a resource exists.

Summary Checklist
Practice Description
Fail Early Detect and reject malicious inputs at the earliest stage
Practice Description
Generic Responses Always send minimal, non-specific messages to users
Detailed Logging Log complete error details only to internal systems
Don’t Leak Stack Info Remove all stack traces, error types, and server paths from client responses
Secure Defaults Disable verbose errors in production environments
Avoid Enumeration Uniform error messages prevent attackers from deducing valid users/resources

Final Thought
Error handling should always be approached with a security-first mindset. Any information you disclose that
doesn’t help the end user can help an attacker.

Information Leak
Server information leak refers to unintentional exposure of server and technology details (e.g., web server
type, version, backend stack) via HTTP response headers. These leaks provide attackers with useful
reconnaissance data that may aid in identifying vulnerabilities specific to your tech stack.

What Causes Server Information Leak?


Information leaks typically occur when a server automatically includes response headers that expose:
• Web server type (e.g., Apache, Nginx, IIS, Uvicorn)
• Backend platform (e.g., PHP, Node.js, Python)
• Server version or framework version
• Middleware or load balancer details
• Cloud hosting/caching services
These headers are often included by default in responses and are unnecessary for end-users.

How Attackers Exploit This


1. Header Inspection:
Attackers use tools like Chrome DevTools, Postman, curl, or custom clients to inspect the response headers
returned by the server.
2. Technology Fingerprinting:
From headers such as Server, X-Powered-By, or Via, attackers determine:
o Server software (e.g., Uvicorn, Apache, Nginx)
o Runtime (e.g., PHP/7.4.1, Express, ASP.NET)
o Version numbers (which may have known vulnerabilities)
3. Vulnerability Research:
Using the identified stack, attackers search public CVE databases (e.g., cvedetails.com, nvd.nist.gov) for known
vulnerabilities.
4. Exploitation Planning:
With knowledge of server types and versions, attackers plan targeted exploits, fuzzing, or injection attempts
based on the weaknesses of the discovered technologies.
Real-Life Example
1. Using Chrome DevTools (Network > Headers), the response headers from a site show Server: Uvicorn.
2. Uvicorn is an open-source Python ASGI server.
3. With this information, an attacker:
o Locates Uvicorn's source code
o Searches for known CVEs
o Plans attacks using available exploits or misconfigurations
Similarly, common servers like Nginx may leak headers like Server: nginx/1.21.0 which has 160+ known
vulnerabilities.

Key Headers That Leak Information


• Server: Web server name and version
• X-Powered-By: Backend language or framework
• Via: Proxy or cache information
• X-AspNet-Version: ASP.NET version
• X-AspNetMvc-Version: MVC version
• X-Generator: CMS platform (e.g., WordPress)
These headers serve no benefit to users and should be removed or suppressed.

How to Prevent Server Information Leaks


General Approach:
• Remove or suppress headers like Server, X-Powered-By, and others.
• Do not expose internal technology stack details in error messages or metadata.
• Ensure that caching layers or appliances are not leaking their own identifiers.
Server-Specific Fixes:
Server Fix
Nginx server_tokens off; in nginx.conf to hide version info
Apache ServerTokens Prod and ServerSignature Off in httpd.conf
Express.js Use Helmet middleware or app.disable('x-powered-by')
Uvicorn Start server with --server-header False
IIS Use registry edit or IIS Manager to remove X-Powered-By header
Middleware and API Gateways:
• Use middleware like Helmet for Node.js to manage headers
• Configure API gateways (e.g., Kong, Apigee) to strip metadata
• Ensure reverse proxies (e.g., Cloudflare, HAProxy) do not leak upstream server info

Tools for Testing Server Header Leaks


• Browser DevTools (e.g., Chrome → Network → Headers)
• Postman, curl, or custom scripts
• Security scanners (e.g., Nikto, Nmap, Burp Suite)
• Online analyzers (e.g., securityheaders.com)
Make sure to inspect API endpoints after logging in or triggering uncacheable requests, as headers from cache
(like CDNs) may be less revealing.

Summary Checklist
Task Description
Inspect headers Use browser or tools to view HTTP response headers
Identify tech Recognize server/software from headers
Lookup CVEs Search vulnerabilities using version info
Suppress headers Configure servers to remove unnecessary headers
Verify changes Test with tools to ensure header removal

Server information leaks provide valuable reconnaissance data to attackers. Reducing these leaks is a basic but
essential security hygiene practice that protects against targeted exploitation based on known vulnerabilities.

Insecure Cookies

Cookies are small pieces of data stored on a user's device by a website to manage sessions, preferences, and
state. When improperly configured, cookies become a source of sensitive information leakage, session
hijacking, or user impersonation.

Purpose and Behavior of Cookies


• Sent from server → client using the Set-Cookie response header.
• Stored on the client and sent back to the server with each request using the Cookie request header.
• Persistent unless set to expire or deleted.
• Often contain session IDs, tokens, user info, or tracking data.

Why Cookie Security Matters


Cookies often store:
• Session identifiers
• Authentication tokens
• User preferences or roles
• Encoded payloads (e.g., Base64)
Improper cookie configuration can allow:
• Tampering (forging or editing cookies)
• Session hijacking
• Data exposure via cross-site scripting (XSS)
• Theft of credentials or user impersonation

Cookie Structure
• Cookies are composed of key-value pairs, delimited by ; (semicolons).
• Example:
• Set-Cookie: sessionID=abc123; Secure; HttpOnly; Path=/; Max-Age=3600
• Cookies may include:
o Boolean values (isLoggedIn=true)
o Identifiers (userID=42)
o Base64-encoded strings (data=eyJyb2xlIjoiYWRtaW4ifQ==)
o Nested delimiters like | within values

Common Vulnerabilities in Cookie Handling


1. Cookie Forging
• Attackers edit cookie values (e.g., session ID, role) and resend them.
• If the backend trusts cookie data without validation, it can result in:
o Privilege escalation
o Unauthorized access
o Tampered sessions
2. Base64 Decoding and Manipulation
• If cookie values are only Base64 encoded (not encrypted or signed), they can be easily decoded and
altered.
• For example, a Base64-encoded JSON can be modified and re-encoded to fake a new identity or role.
3. Weak or Predictable Session IDs
• If session tokens or IDs are numerical or predictable, attackers can guess or iterate through values.
4. JavaScript Access to Cookies
• If HttpOnly is not set, cookies can be accessed via JavaScript.
• This is especially dangerous in the presence of XSS.
5. Insecure Transmission
• Without the Secure flag, cookies are sent in plaintext over HTTP, making them vulnerable to sniffing.
6. Overexposed or Unnecessary Cookie Data
• Storing sensitive internal data (e.g., table names, roles) in cookies may expose architectural details.
• Cookies may bloat over time as servers append more data without validation or cleanup.

Important Cookie Flags


Flag Purpose
Secure Ensures cookie is only sent over HTTPS. Prevents sniffing in transit.
HttpOnly Restricts access from JavaScript (prevents theft via XSS).
Path Limits scope of cookie to certain URL paths.
SameSite Prevents CSRF by restricting cross-origin requests.
Max-Age / Expires Defines cookie lifetime (required for proper session handling).

Offensive Analysis of Cookies (Red Team/Tester Mindset)


1. Parse Cookies:
o Split using ; to identify key-value pairs.
o Inspect keys like session, userID, role.
2. Identify Data Types:
o Boolean → change true ↔ false
o Numeric → try incrementing/decrementing
o Base64 → decode, modify, re-encode
o UUIDs → test known or stolen values
3. Edit and Replay Cookies:
o Modify cookies manually or with dev tools.
o Refresh the page and observe changes in behavior.
4. Test Server Trust Level:
o Does the server validate the integrity or authenticity of the cookie?
o Can you impersonate another user by altering values?

Defensive Strategies for Secure Cookies


1. Treat Cookies as Untrusted Input
• Never assume cookie data is safe.
• Validate all cookie values on the server.
• Sanitize and restrict usage.
2. Minimal Use of Cookies
• Store only necessary information.
• Avoid storing access control or internal logic indicators.
• Consider alternative storage like secure server-side session stores.
3. Use Secure Flags
Flag Benefit
Secure Prevents sniffing during transmission
HttpOnly Prevents JavaScript-based theft (e.g., via XSS)
SameSite=Strict or Lax Helps prevent CSRF
Max-Age or Expires Limits duration of exposure
4. Encrypt or Sign Cookie Data
• Encrypt sensitive cookie contents server-side.
• Use signed cookies to prevent tampering.
• Avoid relying solely on Base64 encoding (not secure).
5. Regularly Inspect Your Cookies
• Manually parse cookies from your application.
• Analyze content:
o Any internal logic exposed?
o Any guessable or insecure values?
o Are all security flags set?

Real-World Example
1. Server sets a cookie:
2. Set-Cookie: sessionID=eyJ1c2VySWQiOjEyMywicm9sZSI6ImFkbWluIn0=; Secure; HttpOnly
3. Attacker decodes the Base64 string:
4. {
5. "userId": 123,
6. "role": "admin"
7. }
8. Changes role to "user", re-encodes and sets it in their browser.
9. If server accepts the altered cookie, it leads to user privilege modification.

Summary Checklist
Task Recommendation
Parse cookies Look for sensitive or editable values
Use Secure Ensure cookies are HTTPS-only
Use HttpOnly Prevent JavaScript access
Avoid storing sensitive data Don't keep roles, passwords, internals in cookies
Set SameSite Protect against CSRF
Use short lifetimes Set cookie expiration reasonably
Encrypt or sign data Don't rely on encoding alone
Treat as untrusted Validate and sanitize on server

Securing cookies is a critical and often overlooked part of web application security. Proper configuration and
treatment of cookies as untrusted user input can significantly reduce risks such as session hijacking, privilege
escalation, and data theft.

Path Traversal
What is Path Traversal?
Path traversal is a vulnerability that allows attackers to access files and directories that lie outside the intended
web server directory (web root). It enables unauthorized access to the file system by manipulating file paths.
• Goal of attack: Access sensitive files (e.g., /etc/passwd, config files, logs) that the application should
not serve.
• Often exploited through improper handling of user input, weak server configurations, and dynamic
file inclusion logic.

How It Happens
1. Dynamic File Access
o When an API dynamically includes or serves files based on user input, and input is not properly
validated or sanitized.
o Example:
o include($_COOKIE['template']); // Dangerous if not validated
▪ A user can manipulate the cookie to input ../../../../etc/passwd.
2. Encoding Tricks
o Attackers can bypass filters using various encodings:
▪ URL encoding (%2e%2e%2f)
▪ Unicode encoding
▪ ASCII encoding
o Filters that only look for ../ may be bypassed with crafted variations.
3. Over-reliance on Loose API Specs
o If API specs define inputs as simply string types, malicious paths can pass through undetected.
o APIs should enforce strict parameter types and patterns, using gateways or WAFs to filter at the
edge.

Real-World Example
• Attackers use automated tools (e.g., path traversal scanners) to test hundreds or thousands of possible
paths.
• Even cookies can carry malicious values if used in dynamic includes.
• Example scenario:
o A file download API uses a query like ?file=invoice.pdf
o If unvalidated, an attacker can modify to ?file=../../../../etc/passwd

Contributing Factors
1. Weak Input Validation
o Accepting file names, paths, or includes directly from user input without sanitization.
2. Loose Server Configurations
o Directory listings enabled
o File includes allowed from outside web root
o Legacy server versions may lack secure defaults
3. Loose API Specifications
o Inputs defined loosely (e.g., any string)
o No length constraints or patterns
o Not filtered at gateway/WAF level

How To Prevent Path Traversal


Input Validation
• Sanitize all inputs that will interact with the file system.
• Use whitelists of allowed filenames or paths.
• Apply strict length and format constraints to string inputs.
API Specification Hardening
• Define strict parameter types in OpenAPI/Swagger specs.
• Use schemas that restrict values (e.g., enums, patterns, min/max length).
• Let API gateways or WAFs block invalid inputs before reaching the backend.
Server Hardening
• Disable directory listing in server config.
• Ensure file access is restricted to within the web root.
• Disallow inclusion of files from outside the intended directory.
Safer File Access Patterns
• Instead of using user input directly in file paths:
o Use internal IDs or references
o Map ID to a file path securely in backend logic
• Example:
• file_id = request.GET['file_id']
• file_path = lookup_path_from_id(file_id)
• with open(file_path) as f:
• return f.read()
Static & Dynamic Analysis
• Use static analysis tools to find code paths that read files dynamically.
• Use fuzzing and automated testing tools to simulate traversal attempts.
Filesystem Isolation
• Place the web root on a dedicated volume or partition, making upward traversal useless.
• Never store sensitive files (e.g., .git/, .env, README, backups) in the web-accessible path.

CVEs & Prevalence


• Path traversal vulnerabilities are still active and frequently reported in real-world applications.
• Thousands of related CVEs exist.
• Recent examples include issues in modern tools like AutoGPT.
• Often discovered during:
o Penetration testing
o Bug bounty reports
o Automated scanning

Summary Checklist

Rate Limits
What is Rate Limiting?
Rate limiting is a defensive mechanism that restricts how often a client can make a request to an API server
within a defined time window.
• Goal of rate limiting: Prevent abuse, brute-force attacks, account enumeration, credential stuffing, DoS
attacks, and excessive resource usage.
• Without rate limiting, attackers can automate requests at high volume to exploit application logic or
infrastructure.

Why It Matters in API Security


1. APIs are inherently exposed to the internet
o Automated abuse is easier compared to traditional web applications.
o APIs expose specific functionality that attackers can target in bulk (e.g., login, password reset,
search).
2. Common Targets for Abuse
o Authentication endpoints (/login, /reset-password)
o Account creation or invitation
o Search or lookup features used for data scraping
o Rate-sensitive business logic like SMS/email OTP systems
3. Attackers bypass protections using automation
o Use tools like Hydra, Burp Suite, custom scripts
o Rotate IPs, user-agents, or tokens
o Distributed attacks using botnets or cloud services

How It Happens (Abuse Without Rate Limiting)


Example: /login endpoint accepts unlimited POST requests
• Attacker sends thousands of login attempts in a short time (credential stuffing or brute-force).
• No lockout, no delay, no CAPTCHA → attacker eventually succeeds.
• Similarly, APIs without rate control on OTP endpoints may be used to drain SMS quota or spam users.

Real-World Scenarios
1. Credential Stuffing
o Attackers use leaked username/password pairs to test accounts at scale.
o No rate limiting = thousands of attempts per minute per IP.
2. Enumeration via Error Messages
o API reveals whether a username/email is valid.
o No rate limit = attacker can enumerate all users in the system.
3. Denial of Service
o Excessive API calls can exhaust system resources or slow down the service.
4. Account Creation Bots
o Attackers register fake accounts in bulk, often using disposable emails or phone numbers.

How To Prevent Abuse with Rate Limiting


Implement Per-User and Per-IP Limits
• Enforce request thresholds based on:
o IP address
o User ID
o API key/token
• Example: Allow 10 login attempts per minute per IP
Define Rate Limits per Endpoint Type
• Set different limits for sensitive endpoints:
o Login: 5-10/minute
o OTP: 3/minute
o Search: 20/minute
o File download: 100/day
• Apply stricter controls where abuse risk is higher.
Use Exponential Backoff or Delays
• Add delay after repeated failed requests to discourage automation.
• Can use increasing delay after each failure or after a threshold is exceeded.
Block or Alert on Suspicious Patterns
• Detect burst activity from:
o Single IP
o Range of IPs
o User agents with abnormal traffic patterns
• Alert or auto-block using WAF, API gateway, or firewall.
CAPTCHA and MFA Integration
• Combine rate limiting with CAPTCHA on authentication forms after failures.
• Use MFA to reduce risk even when rate limits are bypassed.
API Gateway & WAF Support
• Most modern gateways (e.g., Kong, Apigee, AWS API Gateway) support rate limiting.
• Can define rules declaratively in YAML/OpenAPI specs.

API Specification Considerations


• OpenAPI does not define rate limiting behavior, but specs should document limits.
• Include information such as:
o Expected request limits per endpoint
o Retry-after headers
o Error codes (429 Too Many Requests)
• Example for documentation:
• responses:
• 429:
• description: Too Many Requests
• headers:
• X-RateLimit-Limit: max requests allowed
• X-RateLimit-Remaining: requests left
• Retry-After: time before retry

HTTP Headers Used in Rate Limiting


Header Description
X-RateLimit-Limit Max number of requests allowed per window
X-RateLimit-Remaining Number of requests remaining in current window
Retry-After Time to wait before making another request
Summary Checklist

You might also like