Dangling Dns in Fastapi with Api Keys
Dangling Dns in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability
A dangling DNS record occurs when a domain name still resolves to an IP address but the associated service or infrastructure has been decommissioned. In a FastAPI application that relies on API keys for access control, this combination can expose internal or unintended endpoints to unauthorized actors.
FastAPI applications often use API keys passed via headers, query parameters, or cookies to gate access to routes. If a route is defined but the upstream service or backend dependency is no longer available, a dangling DNS record may still direct traffic to an orphaned host. Because FastAPI validates API keys before routing requests to internal logic, an attacker who knows or guesses a valid key might interact with a stale endpoint that should no longer be in use.
During a middleBrick scan, the tool tests unauthenticated attack surfaces and authenticated paths where API keys are required. It checks for unexpected data exposure and input validation issues across 12 security checks, including Authentication and Property Authorization. If a FastAPI route protected by an API key resolves to a dangling DNS target that returns sensitive information or accepts unexpected input, the scan flags this as a potential data exposure or SSRF-related concern.
For example, consider a FastAPI app that uses HTTPX to call an internal service whose DNS name has been decommissioned but still resolves. The route enforces an API key header, but the downstream service may return internal metadata or errors that leak environment details. An attacker with a valid API key can probe this route and observe responses that reveal internal hostnames, paths, or configurations, especially if input validation is weak.
middleBrick’s LLM/AI Security checks are not engaged here because this scenario involves infrastructure misalignment rather than prompt manipulation. However, the scanner’s cross-referencing of OpenAPI specs with runtime behavior can highlight mismatches between declared routes and observed responses, helping you detect inconsistencies introduced by dangling resources.
Api Keys-Specific Remediation in Fastapi — concrete code fixes
To mitigate risks when using API keys in FastAPI, ensure strict validation of downstream dependencies and explicit handling of route resolution. Below are concrete code examples that demonstrate secure patterns for API key usage and error handling to reduce the impact of a dangling DNS scenario.
Example 1: Strict API key validation with explicit error handling
from fastapi import FastAPI, Header, HTTPException, Depends
import httpx
app = FastAPI()
VALID_API_KEYS = {"s3cr3tk3y123", "anothervalidkey456"}
def verify_api_key(x_api_key: str = Header(...)):
if x_api_key not in VALID_API_KEYS:
raise HTTPException(status_code=401, detail="Invalid API Key")
return x_api_key
@app.get("/data")
def read_data(x_api_key: str = Depends(verify_api_key)):
try:
async with httpx.AsyncClient(timeout=5.0) as client:
# Replace with a service that is guaranteed to be available
response = client.get("https://internal-service.example.com/health")
response.raise_for_status()
return {"status": "ok", "details": response.json()}
except httpx.RequestError as e:
# Explicitly handle DNS resolution failures and connection errors
raise HTTPException(status_code=503, detail="Upstream service unavailable")
except httpx.HTTPStatusError as e:
# Handle unexpected responses without exposing internals
raise HTTPException(status_code=502, detail="Invalid response from upstream")
Example 2: Avoid hardcoded hostnames; use environment-based configuration
import os
from fastapi import FastAPI, Header, HTTPException
import httpx
app = FastAPI()
UPSTREAM_HOST = os.getenv("UPSTREAM_HOST")
if not UPSTREAM_HOST:
raise RuntimeError("Missing required environment variable: UPSTREAM_HOST")
def verify_api_key(x_api_key: str = Header(...)):
return x_api_key # simplified for example; integrate with your auth scheme
@app.get("/status")
def get_status(x_api_key: str = Depends(verify_api_key)):
url = f"https://{UPSTREAM_HOST}/v1/status"
try:
async with httpx.AsyncClient() as client:
r = client.get(url, timeout=5.0)
r.raise_for_status()
return r.json()
except httpx.RequestError:
raise HTTPException(status_code=503, detail="Service temporarily unavailable")
Operational practices
- Remove or update DNS records before decommissioning services to prevent dangling resolution.
- Use environment variables or service discovery instead of hardcoded hostnames.
- Log failed requests with sufficient context for debugging but avoid exposing stack traces or internal paths to clients.
- Configure short timeouts and circuit-breaker patterns to limit the impact of unresponsive dependencies.
middleBrick’s CLI tool can be used to scan your FastAPI endpoints and validate that API key enforcement and error handling behave as expected. Run middlebrick scan <url> to receive a security risk score and prioritized findings, including checks related to Authentication and Input Validation.
If you integrate security checks into your pipeline, the GitHub Action can fail builds when risk scores drop below your chosen threshold, helping you catch regressions before deployment. For continuous monitoring, the Pro plan supports scheduled scans and alerts.