HIGH data exposurefastapibasic auth

Data Exposure in Fastapi with Basic Auth

Data Exposure in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability

Basic Authentication in FastAPI transmits credentials in an HTTP header that is base64-encoded but not encrypted. Because base64 is easily reversible, any party that can observe the wire can recover the username and password. If TLS is missing or terminated early, credentials are exposed in clear text across networks, including Wi‑Fi, corporate proxies, and load balancers. Even when TLS is used, misconfigurations such as accepting cleartext HTTP on internal interfaces, allowing mixed content, or weak cipher suites can create paths for interception.

During a black-box scan, middleBrick tests unauthenticated endpoints that accept Basic Auth headers. It checks whether credentials are transmitted over non‑TLS schemes, whether the Authorization header is cached by browsers or intermediaries, and whether sensitive data appears in logs, error messages, or URLs (e.g., credentials accidentally echoed in Location headers during redirects). The scan also examines responses for clear‑text secrets, session identifiers, or PII that may be returned alongside authenticated data. Because Basic Auth does not encrypt the payload, response data containing personal or financial information can be read if an attacker compromises an insecure channel or a misconfigured server.

Another exposure vector arises from improper storage or logging. FastAPI applications that log Authorization headers, either explicitly or through framework instrumentation, can leak credentials to log aggregation systems or console outputs that are accessible to unauthorized users. Similarly, if responses include sensitive data and are cached by browsers, shared caches, or CDNs without appropriate cache‑control directives, authenticated data may be served to other users. The scanner validates whether responses include headers such as Cache‑Control, Pragma, and strict Content‑Security‑Policy to prevent inadvertent data retention. Findings typically highlight missing transport encryption, weak cipher suites, overly permissive CORS, and missing protections against credential leakage in logs and caches.

Basic Auth-Specific Remediation in Fastapi — concrete code fixes

To mitigate data exposure when using Basic Auth in FastAPI, enforce TLS for all traffic and avoid sending credentials over cleartext protocols. Use HTTPStrictTransportHeaders middleware to ensure browsers only connect via HTTPS, and redirect any HTTP requests to HTTPS. Never accept authentication over non‑TLS endpoints, and disable cleartext HTTP listeners in your deployment configuration.

In FastAPI, you can implement HTTP Basic Auth with the HTTPBasic and HTTPBasicCredentials classes from fastapi.security. Combine this with explicit dependency checks to reject non‑TLS requests. The example below shows a secure pattern that validates credentials and enforces HTTPS before processing the request.

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
import secrets

app = FastAPI()
security = HTTPBasic()

def verify_credentials(credentials: HTTPBasicCredentials = Depends(security)):
    # Enforce HTTPS in production by rejecting non‑TLS origins at the edge or in middleware
    # This function is called as a dependency to validate credentials
    expected_username = "api_user"
    expected_password = "s3cr3t_p@ssw0rd"
    if not secrets.compare_digest(credentials.username, expected_username):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials",
            headers={"WWW-Authenticate": "Basic"},
        )
    if not secrets.compare_digest(credentials.password, expected_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username

@app.get("/secure-data")
def get_secure_data(username: str = Depends(verify_credentials)):
    # Ensure responses include cache‑control headers to prevent caching of sensitive data
    # {"username": username, "data": "classified"}
    return {"username": username, "data": "classified"}

Complementary protections include setting cache‑control headers on responses to prevent caching of sensitive data, using short‑lived tokens if possible, and rotating credentials regularly. Configure CORS to restrict origins and avoid exposing endpoints to untrusted domains. Ensure that logs are sanitized to remove Authorization headers before writing to persistent storage. middleBrick can validate these configurations during a scan and surface misconfigurations related to transport security, caching, and credential handling.

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

Why is Basic Auth considered high risk even when used with TLS?
Basic Auth sends credentials in base64 encoding, which is reversible. If TLS is terminated early, misconfigured, or downgraded, credentials can be exposed. Additionally, credentials may leak via logs, browser history, or shared caches, making layered protections essential.
How does middleBrick detect data exposure risks related to Basic Auth in FastAPI?
middleBrick tests unauthenticated endpoints that accept Basic Auth headers, checks for missing or weak TLS configurations, inspects responses for leaked credentials or PII, and validates cache‑control and CORS settings to ensure sensitive data is not retained or exposed inadvertently.