Apply API Client Security
Configure outbound HTTP clients with strict TLS verification, timeouts, response size limits, and response sanitization — treating data from third-party APIs as untrusted until validated.
Why This Is Best Practice
Adopted by: OWASP API Security Top 10 2023 API10 (Unsafe Consumption of APIs) is a dedicated category for client-side API security failures. AWS SDK, Google Cloud Client Libraries, and Azure SDK all enforce TLS certificate validation by default. NIST SP 800-52 Rev 2 requires certificate validation for all TLS connections. PCI DSS v4.0 Requirement 6.3.3 mandates secure configurations for components that connect to payment APIs.
Impact: Disabling TLS certificate verification (verify=False in Python requests, rejectUnauthorized: false in Node.js) enables man-in-the-middle attacks on all API calls — attackers on the same network can intercept credentials and response data. OWASP documents cases where third-party APIs injected malicious data into responses that was then rendered to users without sanitization, enabling XSS via upstream compromise. Unlimited response sizes allow external APIs to send gigabyte responses that exhaust server memory.
Why best: Trusting upstream APIs completely is the common approach — it's fast to implement but creates a dependency chain attack surface. Treating third-party API responses as potentially hostile (validating schema, sanitizing content, enforcing limits) provides defense-in-depth against upstream compromise.
Sources: OWASP API Security Top 10 2023 API10; CWE-295; CWE-918; NIST SP 800-52 Rev 2
Steps
Never disable TLS certificate verification:
import requests
# BAD — disables all TLS security
response = requests.get('https://api.example.com', verify=False)
# GOOD — verify enabled by default, specify CA bundle if needed
response = requests.get('https://api.example.com') # verify=True default
response = requests.get('https://api.example.com', verify='/path/to/custom-ca.pem')
// BAD — Node.js
const https = require('https');
const agent = new https.Agent({ rejectUnauthorized: false });
fetch('https://api.example.com', { agent });
// GOOD
fetch('https://api.example.com'); // no custom agent needed
Set connection and read timeouts — never wait indefinitely on external APIs:
import requests
# Set both connect timeout and read timeout (seconds)
response = requests.get(
'https://api.example.com/data',
timeout=(5, 30) # (connect_timeout, read_timeout)
)
# For long-running requests: stream and enforce size limits
response = requests.get(url, stream=True, timeout=(5, 30))
content = b''
MAX_BYTES = 10 * 1024 * 1024 # 10 MB limit
for chunk in response.iter_content(8192):
content += chunk
if len(content) > MAX_BYTES:
response.close()
raise ValueError("Response too large")
Validate response schema before using data:
from pydantic import BaseModel, ValidationError
from typing import List, Optional
class ExternalUserResponse(BaseModel):
id: str
email: str
name: Optional[str] = None
# NOT accepting arbitrary fields
def fetch_user(user_id):
response = requests.get(f'{EXTERNAL_API}/users/{user_id}', timeout=(5, 10))
response.raise_for_status()
try:
return ExternalUserResponse(**response.json())
except (ValidationError, ValueError) as e:
logger.error("Invalid response from upstream API: %s", e)
raise ServiceError("Upstream API returned unexpected data")
Sanitize response content before rendering — treat upstream API data as untrusted user input:
import html
from markupsafe import Markup
def render_product_description(description_from_api):
# Escape HTML — the upstream API may be compromised
safe = html.escape(description_from_api)
return Markup(safe) # mark as safe only after escaping
If the API returns HTML for rich text: use DOMPurify (browser) or bleach (Python) to sanitize.
Store API credentials securely, rotate them — never hardcode:
import os
from functools import lru_cache
@lru_cache(maxsize=1)
def get_api_key():
return os.environ['EXTERNAL_API_KEY'] # from secret manager or env
# Use per-request headers, don't log them
headers = {
'Authorization': f'Bearer {get_api_key()}',
'User-Agent': 'MyApp/1.0',
}
Validate redirect chains — HTTP clients following redirects may end up at attacker-controlled endpoints:
class SafeHTTPAdapter(requests.adapters.HTTPAdapter):
ALLOWED_HOSTS = {'api.example.com', 'cdn.example.com'}
def send(self, request, **kwargs):
from urllib.parse import urlparse
host = urlparse(request.url).hostname
if host not in self.ALLOWED_HOSTS:
raise SecurityError(f"Redirect to disallowed host: {host}")
return super().send(request, **kwargs)
session = requests.Session()
session.mount('https://', SafeHTTPAdapter())
Log upstream API errors with context, not credentials:
def call_external_api(endpoint, params):
try:
response = requests.get(endpoint, params=params, timeout=(5, 30))
response.raise_for_status()
return response.json()
except requests.Timeout:
logger.error("API timeout: %s", endpoint)
raise ServiceUnavailable()
except requests.HTTPError as e:
logger.error("API HTTP error: %s %s", e.response.status_code, endpoint)
raise
# Never log: headers (may contain API keys), full request body (may contain credentials)
Rules
verify=False in any language is never acceptable in production — use custom CA bundles if your infrastructure uses internal CAs.
- Always validate HTTP status codes before parsing response bodies — a 200 does not mean the body matches the expected schema.
- Retry logic must include jitter and exponential backoff — thundering herds after upstream recovery cause secondary outages.
- Third-party API responses that contain user-controlled data (e.g., social login display names) must be treated as untrusted user input.
Common Mistakes
- Propagating upstream 500 errors directly to clients — leaks implementation details; translate to generic errors (see
design-error-handling).
- Using
requests.get(url) without timeout in a web server — one slow upstream API call blocks the request worker indefinitely.
- Logging full API responses — may contain PII or secrets from the upstream service.
- Assuming HTTPS means the server is legitimate — HTTPS only proves the domain is valid; the domain itself may be compromised. Validate the response content too.
1---2name: apply-api-client-security3description: Use when your application consumes external or third-party APIs — configuring HTTP clients, validating TLS certificates, handling secrets, and sanitizing responses from upstream services.4source: 'OWASP API Security Top 10 2023 API10 (Unsafe Consumption of APIs); OWASP Transport Layer Security Cheat Sheet; CWE-295; CWE-918'5tags: [security, owasp, api-client, http-client, certificate-validation, upstream-trust, developer]6metadata:7 source: https://skillmd.com/skills/jeffreytse/apply-api-client-security8---910# Apply API Client Security1112Configure outbound HTTP clients with strict TLS verification, timeouts, response size limits, and response sanitization — treating data from third-party APIs as untrusted until validated.1314## Why This Is Best Practice1516**Adopted by:** OWASP API Security Top 10 2023 API10 (Unsafe Consumption of APIs) is a dedicated category for client-side API security failures. AWS SDK, Google Cloud Client Libraries, and Azure SDK all enforce TLS certificate validation by default. NIST SP 800-52 Rev 2 requires certificate validation for all TLS connections. PCI DSS v4.0 Requirement 6.3.3 mandates secure configurations for components that connect to payment APIs.17**Impact:** Disabling TLS certificate verification (`verify=False` in Python requests, `rejectUnauthorized: false` in Node.js) enables man-in-the-middle attacks on all API calls — attackers on the same network can intercept credentials and response data. OWASP documents cases where third-party APIs injected malicious data into responses that was then rendered to users without sanitization, enabling XSS via upstream compromise. Unlimited response sizes allow external APIs to send gigabyte responses that exhaust server memory.18**Why best:** Trusting upstream APIs completely is the common approach — it's fast to implement but creates a dependency chain attack surface. Treating third-party API responses as potentially hostile (validating schema, sanitizing content, enforcing limits) provides defense-in-depth against upstream compromise.1920Sources: OWASP API Security Top 10 2023 API10; CWE-295; CWE-918; NIST SP 800-52 Rev 22122## Steps23241. **Never disable TLS certificate verification**:2526 ```python27 import requests2829 # BAD — disables all TLS security30 response = requests.get('https://api.example.com', verify=False)3132 # GOOD — verify enabled by default, specify CA bundle if needed33 response = requests.get('https://api.example.com') # verify=True default34 response = requests.get('https://api.example.com', verify='/path/to/custom-ca.pem')35 ```3637 ```javascript38 // BAD — Node.js39 const https = require('https');40 const agent = new https.Agent({ rejectUnauthorized: false });41 fetch('https://api.example.com', { agent });4243 // GOOD44 fetch('https://api.example.com'); // no custom agent needed45 ```46472. **Set connection and read timeouts** — never wait indefinitely on external APIs:4849 ```python50 import requests5152 # Set both connect timeout and read timeout (seconds)53 response = requests.get(54 'https://api.example.com/data',55 timeout=(5, 30) # (connect_timeout, read_timeout)56 )5758 # For long-running requests: stream and enforce size limits59 response = requests.get(url, stream=True, timeout=(5, 30))60 content = b''61 MAX_BYTES = 10 * 1024 * 1024 # 10 MB limit62 for chunk in response.iter_content(8192):63 content += chunk64 if len(content) > MAX_BYTES:65 response.close()66 raise ValueError("Response too large")67 ```68693. **Validate response schema before using data**:7071 ```python72 from pydantic import BaseModel, ValidationError73 from typing import List, Optional7475 class ExternalUserResponse(BaseModel):76 id: str77 email: str78 name: Optional[str] = None79 # NOT accepting arbitrary fields8081 def fetch_user(user_id):82 response = requests.get(f'{EXTERNAL_API}/users/{user_id}', timeout=(5, 10))83 response.raise_for_status()84 try:85 return ExternalUserResponse(**response.json())86 except (ValidationError, ValueError) as e:87 logger.error("Invalid response from upstream API: %s", e)88 raise ServiceError("Upstream API returned unexpected data")89 ```90914. **Sanitize response content before rendering** — treat upstream API data as untrusted user input:9293 ```python94 import html95 from markupsafe import Markup9697 def render_product_description(description_from_api):98 # Escape HTML — the upstream API may be compromised99 safe = html.escape(description_from_api)100 return Markup(safe) # mark as safe only after escaping101 ```102103 If the API returns HTML for rich text: use DOMPurify (browser) or bleach (Python) to sanitize.1041055. **Store API credentials securely, rotate them** — never hardcode:106107 ```python108 import os109 from functools import lru_cache110111 @lru_cache(maxsize=1)112 def get_api_key():113 return os.environ['EXTERNAL_API_KEY'] # from secret manager or env114115 # Use per-request headers, don't log them116 headers = {117 'Authorization': f'Bearer {get_api_key()}',118 'User-Agent': 'MyApp/1.0',119 }120 ```1211226. **Validate redirect chains** — HTTP clients following redirects may end up at attacker-controlled endpoints:123124 ```python125 class SafeHTTPAdapter(requests.adapters.HTTPAdapter):126 ALLOWED_HOSTS = {'api.example.com', 'cdn.example.com'}127128 def send(self, request, **kwargs):129 from urllib.parse import urlparse130 host = urlparse(request.url).hostname131 if host not in self.ALLOWED_HOSTS:132 raise SecurityError(f"Redirect to disallowed host: {host}")133 return super().send(request, **kwargs)134135 session = requests.Session()136 session.mount('https://', SafeHTTPAdapter())137 ```1381397. **Log upstream API errors with context, not credentials**:140141 ```python142 def call_external_api(endpoint, params):143 try:144 response = requests.get(endpoint, params=params, timeout=(5, 30))145 response.raise_for_status()146 return response.json()147 except requests.Timeout:148 logger.error("API timeout: %s", endpoint)149 raise ServiceUnavailable()150 except requests.HTTPError as e:151 logger.error("API HTTP error: %s %s", e.response.status_code, endpoint)152 raise153 # Never log: headers (may contain API keys), full request body (may contain credentials)154 ```155156## Rules157158- `verify=False` in any language is never acceptable in production — use custom CA bundles if your infrastructure uses internal CAs.159- Always validate HTTP status codes before parsing response bodies — a 200 does not mean the body matches the expected schema.160- Retry logic must include jitter and exponential backoff — thundering herds after upstream recovery cause secondary outages.161- Third-party API responses that contain user-controlled data (e.g., social login display names) must be treated as untrusted user input.162163## Common Mistakes164165- **Propagating upstream 500 errors directly to clients** — leaks implementation details; translate to generic errors (see `design-error-handling`).166- **Using `requests.get(url)` without timeout in a web server** — one slow upstream API call blocks the request worker indefinitely.167- **Logging full API responses** — may contain PII or secrets from the upstream service.168- **Assuming HTTPS means the server is legitimate** — HTTPS only proves the domain is valid; the domain itself may be compromised. Validate the response content too.