HIGH log injectionfastapiapi keys

Log Injection in Fastapi with Api Keys

Log Injection in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability

Log injection occurs when untrusted data is written directly into application logs without proper sanitization or formatting. In FastAPI applications that rely on API keys for authentication, the combination of header- or cookie-based API key handling and insufficient log hygiene can turn routine request logging into an abuse vector.

Consider a FastAPI endpoint that authenticates requests by reading an X-API-Key header and then logs the key as part of a diagnostic message. If the API key value contains newline characters, structured log delimiters, or shell-like metacharacters, an attacker can inject additional log lines or forge log context. For example, an API key like abc123\nAuthorization: Basic d3Jvbmc6cGFzc3dvcmQ= can cause the log to appear as though a second authorization header was present, complicating audit trails and potentially misleading security monitoring.

When API keys are logged in plaintext alongside request metadata (timestamp, path, method), you also risk exposing secrets in log aggregation systems. If these logs are later ingested by monitoring or SIEM tools, the exposed keys can be used for lateral movement or privilege escalation, especially when log retention policies are long or access controls on log stores are weak.

Another scenario involves query parameters or path segments that are reflected into logs without sanitization. An attacker could supply a path such as /resources/123 and append crafted characters that, when logged, produce malformed entries interpreted as multiple logical events by log parsers. This can obscure the true sequence of operations or hide related attacks in high-volume environments.

Because FastAPI is built on Starlette and Pydantic, developers often assume framework-level validation and automatic OpenAPI generation provide comprehensive security. However, validation does not inherently sanitize data destined for logging. Without explicit measures, API key values that pass validation can still be written into logs in a format that enables injection, information leakage, or log forging.

To detect these patterns, a scanner like middleBrick runs checks focused on Data Exposure and Input Validation while also evaluating Log Injection as part of its broader security assessment. It examines whether sensitive values such as API keys appear in logs, whether input is sanitized before being written to observability outputs, and whether log formatting preserves separation between entries to prevent line injection.

Api Keys-Specific Remediation in Fastapi — concrete code fixes

Remediation centers on preventing sensitive API key values from being logged and ensuring that any data written to logs is sanitized and structured. Below are concrete, realistic examples for a FastAPI application using API key authentication.

Example 1: Explicitly redacting API keys before logging

Instead of logging the raw API key, redact or hash it. This preserves traceability for debugging without exposing the secret.

import logging
from fastapi import FastAPI, Header, HTTPException
import hashlib

app = FastAPI()
logger = logging.getLogger("api_access")

def safe_log_api_key(api_key: str) -> str:
    return hashlib.sha256(api_key.encode()).hexdigest()

@app.get("/items/")
async def read_items(x_api_key: str = Header(...)):
    if not validate_key(x_api_key):
        logger.warning(f"auth_fail api_key_hash={safe_log_api_key(x_api_key)}")
        raise HTTPException(status_code=401, detail="Invalid API key")
    logger.info(f"request api_key_hash={safe_log_api_key(x_api_key)} path=/items")
    return {"data": "ok"}

Example 2: Structured logging with sanitized fields

Use structured logging (e.g., JSON-friendly dictionaries) and avoid interpolating raw headers into log messages that could be concatenated with newlines.

import logging
import json
from fastapi import FastAPI, Header

app = FastAPI()
logger = logging.getLogger("structured")

@app.get("/resources/{item_id}")
async def get_resource(item_id: int, x_api_key: str = Header(...)):
    log_entry = {
        "event": "resource_request",
        "item_id": item_id,
        "api_key_hash": hashlib.sha256(x_api_key.encode()).hexdigest(),
        "method": "GET",
        "path": "/resources/{item_id}"
    }
    logger.info(json.dumps(log_entry))
    return {"item_id": item_id}

Example 3: Using FastAPI dependencies to centralize validation and logging

Centralize key validation and safe logging in a dependency to avoid repeating redaction logic across endpoints.

from fastapi import Depends, FastAPI, Header, HTTPException
import hashlib
import logging

app = FastAPI()
logger = logging.getLogger("api_access")

def get_api_key(x_api_key: str = Header(...)):
    safe_key = hashlib.sha256(x_api_key.encode()).hexdigest()
    logger.debug(f"auth_check api_key_hash={safe_key}")
    if not validate_key(x_api_key):
        raise HTTPException(status_code=401, detail="Invalid API key")
    return x_api_key

@app.get("/secure/")
async def secure_endpoint(api_key: str = Depends(get_api_key)):
    return {"status": "authorized"}

General best practices

  • Never log raw API keys, secrets, or tokens.
  • Prefer hashing or truncating identifiers when traceability is needed.
  • Use structured logging and avoid string concatenation that spans multiple lines.
  • Apply consistent input validation and treat all incoming data as potentially malicious.

middleBrick’s scans include checks for Data Exposure and Input Validation, helping you identify endpoints where API keys might be exposed in logs or where injection is possible. By combining these runtime findings with secure coding practices, you reduce the likelihood of log-based information leaks and injection-related confusion in your observability pipelines.

Frequently Asked Questions

Can API key log injection be detected automatically without manual code review?
Yes. Tools like middleBrick test for Data Exposure and Input Validation issues, including scenarios where sensitive values such as API keys could be written into logs in an unsafe or injectable form. These checks complement manual code review by highlighting risky patterns at runtime.
Does hashing API keys before logging fully mitigate the risk of log injection?
Hashing reduces the exposure of the raw secret and helps prevent credential leakage in logs, but it does not alone prevent log injection. You must still sanitize and structure log entries to avoid newline or delimiter injection. Structured logging and avoiding concatenation of untrusted data remain essential.