HIGH information disclosurefastapibasic auth

Information Disclosure in Fastapi with Basic Auth

Information Disclosure in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability

Information disclosure occurs when an API unintentionally exposes sensitive data to an attacker. In FastAPI, using HTTP Basic Authentication without additional protections can contribute to disclosure in both development-time mistakes and runtime behavior. Basic Auth encodes credentials with Base64, which is easily reversible, so transmitting credentials over unencrypted channels exposes them in clear text. If TLS is missing or misconfigured, an attacker on the network can intercept the Authorization header and recover credentials.

Even when TLS is used, implementation choices can lead to information leakage. For example, logging incoming requests including headers may accidentally record Authorization values, and verbose error messages can reveal stack traces or internal paths when malformed credentials are supplied. FastAPI’s default exception handlers may return detailed HTML error pages that expose version details or endpoint structures, aiding reconnaissance.

Another scenario involves misconfigured CORS or improperly set security schemes in OpenAPI specs. If the security scheme is declared but not enforced on certain routes, some endpoints may run without authentication while others require it, allowing an attacker to probe the weaker endpoints to infer authentication boundaries. Because middleBrick scans unauthenticated attack surfaces, it can detect endpoints that lack required security checks and highlight discrepancies between declared security requirements and runtime behavior.

During a scan, middleBrick checks whether credentials are transmitted over encrypted channels, examines whether error responses leak sensitive information, and reviews the API specification to ensure security schemes are consistently applied. Findings may include missing transport protections, overly verbose error messages, or inconsistent application of authentication that can lead to information disclosure.

Basic Auth-Specific Remediation in Fastapi — concrete code fixes

To reduce information disclosure risks when using Basic Auth in FastAPI, enforce HTTPS, avoid logging sensitive headers, and ensure consistent security across all endpoints.

Enforce HTTPS in production

Always use TLS to protect credentials in transit. In production, terminate TLS at the load balancer or reverse proxy and ensure your application rejects non-TLS requests.

Secure FastAPI implementation with Basic Auth

The following example shows a minimal, secure setup using HTTP Basic Auth, with hashed password verification and explicit security dependency enforcement:

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel
import secrets
import hashlib
import os

app = FastAPI()
security = HTTPBasic()

# In production, store these securely (e.g., environment variables or a secrets manager)
USERS = {
    "alice": hashlib.sha256("StrongPassword123".encode()).hexdigest(),
}

def verify_credentials(credentials: HTTPBasicCredentials):
    expected_password_hash = USERS.get(credentials.username)
    if expected_password_hash is None:
        # Use a constant-time comparison to avoid timing attacks
        dummy_hash = hashlib.sha256("dummy".encode()).hexdigest()
        hashlib.sha256((credentials.password or "").encode()).hexdigest()
        return False
    return secrets.compare_digest(expected_password_hash, hashlib.sha256(credentials.password.encode()).hexdigest())

def get_current_user(credentials: HTTPBasicCredentials = Depends(security)):
    if not verify_credentials(credentials):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username

@app.get("/secure-data")
def read_secure_data(username: str = Depends(get_current_user)):
    return {"message": f"Hello {username}, this is protected data"}

@app.get("/open-endpoint")
def read_open_data():
    return {"info": "This endpoint does not require authentication"}

Key points in this implementation:

  • Passwords are stored as SHA-256 hashes (in practice, prefer a slow KDF like Argon2 or bcrypt).
  • secrets.compare_digest mitigates timing attacks during hash comparison.
  • Error responses avoid revealing whether a username exists by using a dummy hash computation before comparison.
  • The security dependency is applied only to routes that require it, making enforcement explicit.

Operational and logging safeguards

Ensure your web server and application logs do not capture Authorization header values. Configure log formats to exclude headers containing credentials. Centralize and protect logs, and set appropriate retention policies to minimize exposure.

Consistent security across the API

Apply the security scheme uniformly in the OpenAPI spec and enforce it across all paths. Avoid mixing authenticated and unauthenticated routes without clear boundaries. Using middleBrick’s OpenAPI/Swagger analysis, you can verify that declared security requirements align with runtime behavior and that $ref resolutions correctly propagate security requirements across the spec.

Frequently Asked Questions

Can middleBrick detect missing HTTPS for Basic Auth endpoints?
Yes. middleBrick checks whether credentials are transmitted over encrypted channels as part of its Encryption and Data Exposure checks.
Does middleBrick test for verbose error messages that may leak information in FastAPI?
Yes. As part of its Information Disclosure and Input Validation checks, middleBrick examines whether error responses expose stack traces or internal details that could aid an attacker.