HIGH header injectionfastapibasic auth

Header Injection in Fastapi with Basic Auth

Header Injection in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability

Header Injection occurs when user-controlled input is reflected into HTTP headers without validation or sanitization. In Fastapi applications that use HTTP Basic Authentication, this risk typically arises when developers construct response headers, custom request headers, or logging mechanisms using data that originates from the request, query parameters, or untrusted sources. Because Basic Authentication relies on the Authorization header, any injection into other headers can corrupt the authentication context, bypass intended controls, or expose sensitive information.

Fastapi, which is built on Starlette and Pydantic, provides convenient ways to read headers and to set custom headers in responses. If a route directly incorporates user input into headers—such as a locale, request ID, or custom metadata—without strict validation, an attacker can inject newline characters (CRLF, \r\n) to split headers and append malicious ones. For example, injecting into a custom X-Request-ID or a Location header can lead to response splitting, cache poisoning, or the addition of unintended headers like Set-Cookie or WWW-Authenticate, which may change how clients or intermediaries process the response. In the context of Basic Auth, if the server constructs a WWW-Authenticate challenge based on user input, an attacker may manipulate the realm or other parameters, weakening the clarity or security of the authentication mechanism.

Another angle specific to Basic Auth is the handling of the Authorization header itself. While Fastapi’s security utilities parse and validate credentials, developers sometimes mirror or log the raw Authorization header for debugging. If an attacker can control part of the header value through injection elsewhere and the application reflects or logs it unsafely, this can lead to header smuggling or information leakage. Moreover, when OpenAPI/Swagger specs are generated from route definitions that incorporate user input into header-related descriptions or examples, the spec may inadvertently document unsafe patterns. Runtime findings from a black-box scan can detect mismatches between the declared spec and actual behavior, highlighting routes where injected headers reach responses or where authentication handling is inconsistent.

Consider a Fastapi endpoint that accepts a user-supplied label used in a custom header:

from fastapi import Fastapi, Request

app = Fastapi()

@app.get("/items/")
def read_items(x_custom_label: str = "default", request: Request):
    # Unsafe: directly using user input in a custom response header
    return {"message": "ok", "x-custom-label": x_custom_label}

If the parameter x_custom_label is attacker-controlled and the framework reflects it into the response header without validation, CRLF injection can split the header and inject additional headers. Even when using Basic Auth via the Security scheme, if the application builds WWW-Authenticate or other headers using unchecked input, the authentication boundary can be blurred. MiddleBrick scans detect such patterns by correlating OpenAPI spec definitions with runtime behavior, identifying routes where headers are constructed in ways that could allow injection, and highlighting the absence of input validation as a concrete finding.

Basic Auth-Specific Remediation in Fastapi — concrete code fixes

Remediation focuses on strict input validation, avoiding reflection of untrusted data into headers, and using Fastapi’s built-in security utilities correctly. Never construct WWW-Authenticate or other security headers using user-controlled values. Always rely on Fastapi’s Security HTTP scheme for Basic Auth, and ensure custom headers are either static or rigorously sanitized.

Below is a secure Fastapi example that uses HTTP Basic Authentication correctly and avoids header injection by not reflecting untrusted input into headers:

from fastapi import Fastapi, Depends, HTTPException, status, Security
from fastapi.security import HTTPBasic, HTTPBasicCredentials

app = Fastapi()
security = HTTPBasic()

def verify_credentials(credentials: HTTPBasicCredentials = Security(security)):
    # Replace with secure credential verification (e.g., constant-time compare)
    correct_username = "admin"
    correct_password = "secret"
    if credentials.username != correct_username or credentials.password != correct_password:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials",
            headers={"WWW-Authenticate": 'Basic realm="api"'},
        )
    return credentials.username

@app.get("/secure/")
def secure_route(username: str = Depends(verify_credentials)):
    # Safe: no user input reflected into headers
    return {"user": username, "x-request-id": "static-or-generated-id"}

If you must include a custom header, derive it from trusted sources only (e.g., a server-side UUID or a constant), and never concatenate user input. For example, avoid patterns like {"x-injected": user_value}. Instead, generate or select header values from a controlled set:

import uuid
from fastapi import Header

@app.get("/items/")
def read_items(x_request_id: str = Header(None)):
    # Safe: using a server-generated ID, not user input
    safe_id = x_request_id or str(uuid.uuid4())
    return {"message": "ok", "x-request-id": safe_id}

Additionally, ensure that any logging or observability mechanisms do not inadvertently echo unsanitized header values. Validate and normalize any metadata that might be used in headers, and test routes with tools that probe for response splitting and header smuggling. The combination of correct Basic Auth usage and disciplined header handling reduces the attack surface and prevents injection-based confusion between authentication and other controls.

Frequently Asked Questions

Can header injection bypass Basic Auth protections in Fastapi?
Yes, if user input is reflected into response or request headers without validation, an attacker can inject additional headers such as Set-Cookie or manipulate WWW-Authenticate values. This can lead to response splitting, cache poisoning, or authentication context confusion, effectively weakening Basic Auth protections. Always validate and avoid reflecting untrusted data into headers.
How does middleBrick detect header injection risks in Fastapi APIs using Basic Auth?
middleBrick performs black-box scans that include input validation and header reflection checks. It correlates OpenAPI/Swagger spec definitions with runtime behavior to identify routes where headers are constructed from user-controlled input. Findings include missing validation and risky header usage patterns, with remediation guidance mapped to OWASP API Top 10 and compliance frameworks.