MEDIUM dangling dnsfastapibasic auth

Dangling Dns in Fastapi with Basic Auth

Dangling Dns in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability

A dangling DNS record occurs when a hostname (e.g., internal.api.example.com) still points to an IP address, but the service or workload originally using that address has been decommissioned or moved. In a FastAPI application that uses HTTP Basic Auth, this combination can expose internal or unintended endpoints during both development and production operations.

When FastAPI resolves a route or configuration value (such as a database URL, outbound HTTP client target, or background task endpoint) at startup or lazily on first request, it may store the resolved IP or connection details. If the DNS record later changes to point elsewhere—or is removed without cleaning up references—the application may continue to communicate with the stale IP. With Basic Auth protecting only the FastAPI application itself, outbound calls from FastAPI to the dangling hostname are not re-authenticated under the same credentials context, and the stale endpoint may be unauthenticated or weakly protected.

During a middleBrick scan, the tool tests unauthenticated attack surfaces and runs checks such as the LLM/AI Security and Unsafe Consumption modules. If FastAPI endpoints dynamically construct outbound URLs (for example, to call internal services or legacy APIs), and a dangling DNS record resolves to a server that echoes back data or exposes debug information, the scan may detect data exposure or SSRF-like behaviors. The scanner does not rely on internal architecture; it observes runtime behavior. A dangling DNS target that returns sensitive headers or tokens can result in findings mapped to Data Exposure and Unsafe Consumption, with remediation guidance to validate and hardcode or use service discovery instead of relying on mutable DNS.

Basic Auth-Specific Remediation in Fastapi — concrete code fixes

To reduce risk when using HTTP Basic Auth in FastAPI, enforce strict input validation, avoid runtime DNS-based endpoint resolution for critical calls, and ensure credentials are not leaked in logs or error messages. The following examples show secure patterns.

Secure FastAPI with Basic Auth and validated outbound targets

from fastapi import FastAPI, Depends, HTTPException, Header
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel, Field
from typing import Dict
import httpx
import os

app = FastAPI()
security = HTTPBasic()

# Hardcode or load allowed origins; do not rely on DNS for sensitive targets
ALLOWED_SERVICE_HOSTS = {"api.internal.example.com": "10.0.0.10"}

class Payload(BaseModel):
    data: str = Field(..., min_length=1, max_length=1024)

def verify_credentials(credentials: HTTPBasicCredentials = Depends(security)):
    # Replace with secure secret comparison and constant-time checks
    expected_user = os.getenv("API_USER", "admin")
    expected_pass = os.getenv("API_PASS", "s3cr3t")
    if not credentials.username == expected_user or not credentials.password == expected_pass:
        raise HTTPException(status_code=401, detail="Invalid credentials")
    return credentials.username

@app.post("/process")
async def process(
    payload: Payload,
    username: str = Depends(verify_credentials)
):
    # Use a statically configured or service-discovered target; avoid raw DNS lookups for outbound calls
    target_host = "api.internal.example.com"
    if target_host not in ALLOWED_SERVICE_HOSTS:
        raise HTTPException(status_code=400, detail="Target not allowed")

    target_url = f"https://{target_host}/v1/submit"
    headers = {"X-User": username}

    # Use a short timeout and avoid forwarding raw user input as Host or untrusted headers
    async with httpx.AsyncClient(timeout=5.0) as client:
        try:
            resp = await client.post(
                target_url,
                json=payload.dict(),
                headers=headers,
                # Do not blindly forward incoming Host or similar headers
            )
            resp.raise_for_status()
        except httpx.RequestError as exc:
            raise HTTPException(status_code=502, detail=f"Service unavailable: {exc}")

    return {"status": "ok"}

Checklist for Basic Auth and DNS safety

  • Validate and restrict outbound hostnames against an allowlist; do not concatenate user input into target hosts.
  • Use fixed IPs or service mesh endpoints for critical internal calls; avoid relying on dynamic DNS that can change.
  • Ensure credentials are verified with constant-time comparisons and never logged; configure secure password hashing for the Basic Auth realm.
  • Set timeouts and circuit breakers on outbound clients to limit exposure to unresponsive or malicious endpoints.
  • Audit environment variables and configuration files to ensure no dangling DNS hostnames are embedded.

These steps align with findings from middleBrick checks such as Input Validation, Property Authorization, and Unsafe Consumption, and they help ensure that authentication boundaries remain intact even when DNS configurations change.

Frequently Asked Questions

How does middleBrick detect risks related to dangling DNS in FastAPI with Basic Auth?
middleBrick runs unauthenticated scans that include input validation and unsafe consumption checks. It observes runtime behavior when FastAPI constructs outbound calls, and flags cases where responses from dangling DNS targets may expose data or configuration issues while Basic Auth protects only the FastAPI application.
Can the middleBrick CLI or GitHub Action enforce fixes for Basic Auth or DNS issues?
middleBrick detects and reports findings with remediation guidance; it does not fix, patch, or block. You can integrate the middleBrick CLI in scripts or use the GitHub Action to fail builds when risk scores exceed your threshold, but remediation implementation is your responsibility.